Skip to content

Instantly share code, notes, and snippets.

@daltyboy11
Created April 11, 2022 17:20
Show Gist options
  • Save daltyboy11/2cd7e58033d8c15672b51e21a56ed61d to your computer and use it in GitHub Desktop.
Save daltyboy11/2cd7e58033d8c15672b51e21a56ed61d to your computer and use it in GitHub Desktop.
Multiple library usage in Soliditiy

Something I didn't realize when I first learned about libraries in Solidity is you can apply multiple libraries to the same type. Here's what I mean:

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

library SafeMath1 {
    function add(uint x, uint y) internal pure returns (uint) {
        uint z = x + y;
        require(z >= x, "uint overflow");
        return z;
    }
}

library SafeMath2 {
    function sub(uint x, uint y) internal pure returns (uint) {
        uint z = x - y;
        require(z <= x, "uint underflow");
        return z;
    }
}

contract TestSafeMath {
    using SafeMath1 for uint;
    using SafeMath2 for uint;

    function testAdd(uint x, uint y) public pure returns (uint) {
        return x.add(y);
    }

    function testSub(uint x, uint y) public pure returns (uint) {
        return x.sub(y);
    }
}

In TestSafeMath we apply SafeMathAdd and SafeMathSub to uint. But what happens if the libraries share one or more method signatures?

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

library Lib1 {
    function foo(uint x, uint y) internal pure returns (uint) {
        return x + y + 1;
    }
}

library Lib2 {
    function foo(uint x, uint y) internal pure returns (uint) {
        return x + y - 1;
    }
}

contract TestSafeMath {
    using Lib1 for uint;
    using Lib2 for uint;

    function testFoo(uint x, uint y) public pure returns (uint) {
        return x.foo(y);
    }
}

What is the result of calling testFoo(2, 7)? a. Does not compile b. Returns 10 c. Returns 8

See answer
Duplicate library methods produce a compilation error: TypeError: Member "foo" not unique after argument-dependent lookup in uint256.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment