Solidity Library Foundry Forge – Does Foundry Support Dynamic Library Linking in Solidity?

forgefoundrylibrarysolidity

I would like to deploy a contract that has external library dependencies that need to be dynamically linked. This is typically done in hardhat ethers as follows:

const MyLibrary = await ethers.getContractFactory("MyLibrary");
const myLibrary = await MyLibrary.deploy();
await myLibrary.deployed();

// Deploy MyContract, linking MyLibrary library
const MyContract = await ethers.getContractFactory("MyContract", {
  libraries: {
    MyLibrary: myLibrary.address,
  },
});
const myContract = await MyContract.deploy();
await myContract.deployed();

Does Foundry provide built-in support for dynamical library linking in Solidity? I want to deploy a contract to my local foundry node to be able to test it, though I'd imagine the solution if one exists would also be applicable to deploying contracts to live networks.

This question is somewhat related to the following but there isn't a satisfactory answer:

How to link a library to a smart contract using Foundry

How to deploy a contract with linked libraries and a different version in foundry test

Best Answer

Foundry does support library linking, but it handles this by itself. Here's how it works:

Automatic Library Deployment: When deploying a contract that depends on one or more libraries, Foundry will automatically deploy those libraries for you, under the hood. This includes the necessary step of linking the contract to the libraries.

Network Compatibility: This automatic deployment and linking of libraries works across all networks, whether you're deploying to a local Foundry node, a local fork, or even live networks.

Optional Manual Deployment: If you want, you can still manually deploy libraries just like you would deploy regular contracts. However, this manual deployment won't allow you to explicitly link libraries to contracts within Solidity code using Foundry.

If you already have the library addresses that you would like to link to currently foundry does not support this in solidity, however you can configure this via:

  1. the forge create --libraries flag or
  2. directly in the foundry.toml as follows:
forge create src/MyContract.sol:MyContract --libraries src/libraries/MyLibrary.sol:MyLibrary:0x...
# foundry.toml

[profile.default]
  # expected format(example below): libraries = ["<path>:<lib name>:<address>"]
  libraries = ["src/libraries/MyLibrary.sol:MyLibrary:0x..."]
Related Topic