I have a contract where I often set stuff for a combination of 2 addresses. Because the parameters addressA and addressB are interchangeable I currently save the information redundantly.


    mapping ( address => mapping ( address => uint256 )) public maxNextUpdateInBlocks;

    function configureCurrencyPair(address _currencyA, address _currencyB, uint256 maxNextUpdateInBlocks) public onlyOwner {
        maxNextUpdateInBlocks[_currencyA][_currencyB] = maxNextUpdateInBlocks;
        maxNextUpdateInBlocks[_currencyB][_currencyA] = maxNextUpdateInBlocks;

Can this be improved? I am thinking about a hash of the address combination where it doesn't matter if I hash currencyA+currencyB or currencyB+currencyA

And just set in one line:

maxNextUpdateInBlocks[currencyAB] = maxNextUpdateInBlocks;

1 Answer 1


You could order the addresses first before storing them:

mapping(bytes32 => uint256) maxNextUpdateInBlocks;

function configureCurrencyPair(address _currencyA, address _currencyB, uint256 _maxNextUpdateInBlocks) public onlyOwner {
    bytes32 key;
    if(_currencyA > _currencyB)
        key = keccak256(_currencyA, _currencyB);
        key = keccak256(_currencyB, _currencyA);

    maxNextUpdateInBlocks[key] = _maxNextUpdateInBlocks

This can probably be done in a cleaner way, but you'll get the idea.

Gas cost: 20593


As Raghav Sood commented, it's also possible to skip hashing:

mapping(address => mapping(address=> uint256)) maxNextUpdateInBlocks;

function configureCurrencyPair(address _currencyA, address _currencyB, uint256 _maxNextUpdateInBlocks) public onlyOwner {

    if(_currencyA > _currencyB)
        maxNextUpdateInBlocks[_currencyA][_currencyB] = _maxNextUpdateInBlocks;
        maxNextUpdateInBlocks[_currencyB][_currencyA] = _maxNextUpdateInBlocks;

This is a bit less expensive: 20525 Gas

  • 2
    If he's already ordering them, wouldn't it make more sense to just use the current setup, with an order, without the additional keccak steps? I'm not sure which one would use more gas, a 2d array or the keccak op. In either case, you make at least one storage modification, so you could be better off skipping keccak Aug 3, 2018 at 8:06
  • Ah yes for a moment I forgot that an address is just a number. Thanks guys this is so useful right now :) Aug 3, 2018 at 8:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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