Skip to content

Instantly share code, notes, and snippets.

@SpiralOutDotEu
Last active September 29, 2024 12:58
Show Gist options
  • Save SpiralOutDotEu/2761ae4d5211380b584a06cd8516b292 to your computer and use it in GitHub Desktop.
Save SpiralOutDotEu/2761ae4d5211380b584a06cd8516b292 to your computer and use it in GitHub Desktop.
Solidity function injection
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Reference: https://ethereum.stackexchange.com/questions/117725/passing-functions-as-parameters-how-to-invoke
contract A {
enum Action { Walk, Fly, Swim }
function walk() internal pure returns (uint) {
return 10;
}
function fly() internal pure returns (uint) {
return 50;
}
function swim() internal pure returns (uint) {
return 20;
}
function cost(function () internal pure returns (uint) activity) internal pure returns (uint) {
return activity();
}
// @params numbers {0, 1, 2} that corresponds to Action { Walk, Fly, Swim }
function foo(Action action) public pure returns (uint) {
function () internal pure returns (uint) activity;
if (action == Action.Swim) {
activity = swim;
} else if (action == Action.Fly) {
activity = fly;
} else {
activity = walk;
}
return cost(activity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment