Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default parameters to functions in Solidity

Tags:

solidity

I came across below example from the Solidity Documentation and have similar code in my project and want to set default value to key parameter if the key is not passed from the caller

pragma solidity ^0.4.0;

contract C {
    function f(uint key, uint value) public {
        // ...
    }

    function g() public {
        // named arguments
        f({value: 2, key: 3});
    }
}

My questions are -

  • Do Solidity language provides default parameters?
  • How to achieve the same if default parameters are not allowed then?

Appreciate the help?

like image 373
MBB Avatar asked Aug 31 '18 10:08

MBB


2 Answers

Solidity does not support default parameters, but it is on their roadmap (see https://github.com/ethereum/solidity/issues/232). To work around this, just use function overloading:

pragma solidity ^0.4.0;

contract C {
    function f(uint key, uint value) public {
        // ...
    }

    function h(uint value) public {
        f(123, value);
    }

    function g() public {
        // named arguments
        f({value: 2, key: 3});
    }

    function i() public {
        h({value: 2});
    }
}
like image 172
Adam Kipnis Avatar answered Sep 19 '22 01:09

Adam Kipnis


Openzeppelin does a great job exemplifying how you can make "default" arguments. Check out their SafeMath Library.

In it, they have two sub (subtraction) contracts that are identical visibility and mutability wise- but a key difference:

function sub(
    uint256 a,
    uint256 b
)internal pure returns (uint256) {
    return sub(a, b, "SafeMath: subtraction overflow");
}

function sub(
    uint256 a,
    uint256 b,
    string memory errorMessage
) internal pure returns (uint256) {
    require(b <= a, errorMessage);
    uint256 c = a - b;

    return c;
}

The first one by default takes two arguments a & b (which will be subtracted). If a third argument is not given (the error statement) it will default to

SafeMath: subtraction overflow

If a third argument is given, it will replace that error statement.

Essentially:

pragma solidity >=0.6.0 <0.9.0;

contract C {
    function f(unit value) public {
        uint defaultVal = 5;
        f(defaultVal, value);

    function f(uint key, uint value) public {
        // ...
    }

    function g() public {
        // named arguments
        f(2, 3);
    }
}
like image 21
chriscrutt Avatar answered Sep 21 '22 01:09

chriscrutt