Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapping functions in solidity

I'm wondering if it's possible to map functions in a map in solidity, something like:

mapping (uint256=> function) function_map;
f(){
    do something;
}
function_map[1] = f;
like image 732
Anton Andell Avatar asked May 30 '26 18:05

Anton Andell


2 Answers

While you can't store the function as a type, you can store the bytes4 representation and then invoke through call().

pragma solidity ^0.4.20;

contract Test {
    uint public _val;

    mapping(uint => bytes4) _methodToInvoke;

    function Test() public {
        _methodToInvoke[1] = bytes4(keccak256("incrementBy1()"));
        _methodToInvoke[2] = bytes4(keccak256("incrementBy2()"));
    }

    function incrementBy1() public {
        _val++;
    }

    function incrementBy2() public {
        _val += 2;
    }

    function invoke(uint idx) public returns (bool) {
        return this.call(_methodToInvoke[idx]);
    }
}
like image 144
Adam Kipnis Avatar answered Jun 02 '26 10:06

Adam Kipnis


As you can read in the ethereum solidity documentation: Mapping in ethereum solidity

Mappings are only allowed for state variables (or as storage reference types in internal functions).

So the answer is no. (so far)

like image 20
q0re Avatar answered Jun 02 '26 10:06

q0re