2

What is the benefit of a linked library over a standalone contract? Let's say I want to reuse code between multiple contracts. The code itself has no state.

Example library:

library SafeMath {
  function add(uint256 _a, uint256 _b) external pure returns (uint256) {
      uint256 c = _a + _b;
      require(c >= _a, "ERROR_ADD_OVERFLOW");
      return c;
  }
}

contract UsingLibrary {
  using SafeMath for uint256;

  uint256 x = 0;

  function doSomething() public {
    x = x.add(1);
  }
}

Example external contract

contract SafeMath {
  function add(uint256 _a, uint256 _b) external pure returns (uint256) {
      uint256 c = _a + _b;
      require(c >= _a, "ERROR_ADD_OVERFLOW");
      return c;
  }
}

contract UsingExternalContract {
  SafeMath private constant math = 0x123abc...;
 
  uint256 x = 0;

  function doSomething() public {
    x = math.add(x, 1);
  }
}

Is there some difference in terms of gas costs? Both call and delegatecall cost the same amount of gas and if the destination address of the SafeMath contract is stored in a constant variable, there isn't any gas cost to read the address of the library contract. What are reasons one should use an external (linked) library over a separate contract that effectively does the same?

2
  • Maybe not the answer that u are looking for, but I think it is a programming philosophy and you need to deploy 2 contracts instead of one. In other cases you don’t want to rely on another external contract for security issues even if it is controlled by you.
    – Majd TL
    Jul 9, 2022 at 8:29
  • well in both cases you need to deploy 2 times. In the first case a library and a contract and in the second case two contracts. I'm not talking about embedded libraries, only linked libraries Jul 10, 2022 at 14:04

1 Answer 1

1

Gas used

With Library:
SafeMath = 118864 gas
UsingLibrary = 111831 gas

Total = 230695 gas

With External Contract:
SafeMath = 116299 gas
UsingExternalContract = 111831 gas

Total = 228130 gas

Conclusion: External Contract is better to save gas.

Tested in Remix with Solidity compiler version 0.8.17.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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