Truffle Suite: How to Link Libraries when Running Migrations

Truffle Suite help you run migrations to the Ethereum network with JavaScript APIs.

$ truffle migrate

When there are libraries that your contracts are depending on, you have to link them in the migration files.

Example

Let's assume that there is a Search library that implements max() function for finding the maximum number from the uint[] array.

// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.0 <0.9.0;

library Search {
    function max(uint[] storage self) public view returns (uint) {
        //...
    }
}

Let's also assume that your contract, SearchArray, depends on the Search library.

using Search for uint[];

contract SearchArray {
    uint[] public data;

    function getMax() public view returns (uint) {
        return data.max();
    }
}

Migration File

In this example, you might want to write a migration file as follows:

var Search = artifacts.require("Search")
var SearchArray = artifacts.require("SearchArray")
module.exports = function(deployer) {
    deployer.deploy(Search)
    // NOTE: here the library is linked to the contract
    deployer.link(Search, [SearchArray])
    deployer.deploy(SearchArray)
}

Here, you'll find that deployer.link(library, destinations) is required. This API link an already-deployed library to your contracts during running migrations.

Otherwise, you might encounter the migration error saying: Unresolved libraries error with a single sol file.

2022-11-01