2
pragma solidity 0.8.20;

contract SolidityLimitTest {
    mapping (address => Hack) private Hackable;

    struct Hack {
        uint amount;
        function(uint) returns (uint) ten_x;
    }

    function ten_x(uint x) private pure returns (uint result) {
        return x * 10;
    }

    // The contract compiles, but this function reverts on execution.
    function rabbitHole() public returns (uint) {
        uint a = Hackable[msg.sender].ten_x(1);
        return a;
    }
}

I was limit testing Solidity code today and found to my surprise that the above code compiles correctly (although rabbitHole() reverts). Could this mean that there is an unofficial way to get functions listed as properties of structs to execute as methods?

1 Answer 1

2

It's a perfectly legitimate use. Only there are some restrictions: the called function must be executed within the context of the same contract. You can read the official documentation: https://docs.soliditylang.org/en/latest/types.html#function-types

I've expanded your example a bit so that the functions return values.

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

contract SolidityLimitTest {
    mapping (address => Hack) private Hackable;
    uint public z;

    struct Hack {
        uint amount;
        function(uint) returns (uint) f3;
    }
    constructor(uint _z) {
        z = _z;
        Hackable[msg.sender] = Hack(20, ten_x);
    }

    function ten_x(uint x) private pure returns (uint result) {
        return x * 10;
    }

    // The contract compiles, but this function reverts on execution.
    function rabbitHole(uint a) public returns (uint b) {
        b = Hackable[msg.sender].f3(a);
    }


    function f1(uint a, function(uint) pure returns(uint) b) internal view returns(uint) {
        return a + b(z); 
    }

    function f2(uint a) public returns(uint) {
        z = f1(a+z, ten_x);
        return z;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.