For now I use this code to link library during truffle migration:

deployer.link(SafeMathLibExt, [CrowdsaleTokenExt]);

This code deploys library each time and I don't like it. I want to deploy library only once and then always use it. So I want something like that (pseudo code):

const library = deployer.getLibrary(libraryAddress);
deployer.link(library, [CrowdsaleTokenExt]);

is it possible to achieve in truffle?

2 Answers 2


Well you would have to go outside truffle and deploy the script manually. By doing that the library contract would be outside the purview of truffle, so whenever you do truffle migrate, only the token contract is deployed again.

So it would work something like this:

var web3 = require("web3");
var fs = require("fs");
var solc = require("solc");

web3 = new web3(new web3.providers.HttpProvider("http://localhost:8545"));

var compiledCode = 

solc.compile(fs.readFileSync('./contracts/SafeMathLibExt.sol', 'utf8'),1);

var source = compiledCode.contracts[":SafeMathLibExt"];

var tokencontract = new  web3.eth.Contract(JSON.parse(source.interface));

tokencontract.deploy({data: source.bytecode}).send({from: Owneraddress, 
gas:1500000}).on('confirmation', function(confirmationNumber, receipt){ 
console.log(confirmationNumber); tokencontract.options.address = 
receipt.contractAddress; }).on('receipt', function(receipt)
  • Thanks for the answer, I got your idea. How can I pass deployed library address into truffle deployer? Could you provide code example or link to truffle documentation? Dec 6, 2017 at 19:51
  • this doesn't answer the question
    – okwme
    Mar 22, 2018 at 16:58
  • 3
    This is ridiculous that truffle doesn't allow this natively. Feb 19, 2020 at 16:10

Truffle does support this

Your migration file needs to look like this;

const CrowdsaleTokenExt = artifacts.require("CrowdsaleTokenExt");
const Lib = artifacts.require("Lib");

module.exports = async function (deployer, network, accounts) {
  const [admin] = accounts;

  try {
    const lib = await Lib.deployed();
    if (!lib.address) throw "Not Deployed";
  } catch (error) {
    await deployer.deploy(Lib);
  await deployer.link(Lib, [CrowdsaleTokenExt]);

  await deployer.deploy(CrowdsaleTokenExt);

What happens is this, we will check if Lib is deployed in the try block, and if it doesn't have an address(not deployed), we trigger the catch block which deploys the Lib then we link the Lib to the contract right before deploying the contract

NOTE: This would only work if the Lib was deployed with truffle, if you are trying to connect to an external Lib, I think truffle has a at method for artifacts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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