Dynamic linking for Libraries

Libraries are a bit difficult to use because of the linking process. Should we open up the concept of libraries to behave more like contracts?

This means you could have library instances whose functions you can call in the same way as contract functions, just that they would use delegatecall for the call. In combination with immutable, it should have almost the same cost as current libraries have, but there would be less magic. You could even have library factory contracts that use new in connection with a library.

library L { function f(uint[] storage x) public returns (uint) { return x[0]; }
contract C {
  // immutable library instance
  L immutable l = L(0x1234...67);
  // library instance whose address is stored in storage
  L x;
  function f() public {
    uint t = l.f();
    uint r = x.f(); // will revert if x is unassigned
    x = new L(); // create a new instance of the library
  }
}

One problem I see is that because of the delegatecall, you can potentially create a lot of damage to the contract.

An open question is if something like “library interfaces” should be allow or at least “abstract libraries” - but without inheritance in libraries this is maybe not too useful.

Related issue: https://github.com/ethereum/solidity/issues/11695

1 Like

This is cool. So it would work like regular external functions from libraries but the linking is handled automatically by the compiler?

Not at all. Currently, the linking is kind of handled automatically by the compiler. With this feature, that aspect does not change, but you also have the option of doing the linking manually (i.e. you have to write code) at deploy time - and you can “re-link”, i.e. change the address of a library.

I see, thanks. Being able to change the address of a library adds more flexibility, I like that.

1 Like