19

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?

MBB
  • 1,635
  • 3
  • 9
  • 19

2 Answers2

25

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});
    }
}
Adam Kipnis
  • 10,175
  • 10
  • 35
  • 48
3

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);
    }
}
chriscrutt
  • 500
  • 3
  • 5
  • 17
  • But, with this solution how I can use both `f` methods from web3? Because I could only use the first method f. – Henry Palacios Mar 02 '21 at 21:09
  • 1
    @HenryPalacios I believe if it doesn't work by calling `f()` with the supplied arguments (2 vs 3) you may need to get the HASH ID name and call the function that way from a web3 perspective. – rabbitt Sep 06 '21 at 15:50