0

I found one link for my question at: 2016 Link

I have got the following code from:link

function GasCost(string memory name, 
    function () internal returns (string memory) fun) 
    internal returns (string memory) 
{
    uint u0 = gasleft();
    string memory sm = fun();
    uint u1 = gasleft();
    uint diff = u0 - u1;
    return concat(name, " GasCost: ", stringOfUint(diff), 
                " returns(", sm, ")");
}

Somebody please explain me what is the name of the above function defining technique? and how to invoke the function GasCost(...) and how to define fun? Provide me the link for the tutorial also.

Zulfi.

1 Answer 1

2

The parameters are named function types. I don't know if the technique has a particular name.

Here is an example where the function are used as primitive sort of dispatcher.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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();
    }

    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);
    }
}

Edit: You could invoke GasCost with something like this:

function ComplexFunction() internal returns (string memory) {
   return "Echo";
}

function Caller(string memory name) public returns (string memory) {
   return GasCost(name, ComplexFunction);
}

2
  • thanks,first argument of GasCost(...) function is 'name', can you please tell me what is the name of 2nd argument in case of GasCost(...) function and how to invoke the GasCost(...) function?
    – zak100
    Commented Jan 3, 2022 at 6:04
  • 1
    @zak100 The type is function () internal returns (string memory) and the name is fun. See the edit for an example how to use GasCost.
    – Ismael
    Commented Jan 3, 2022 at 6:23

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.