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.