Please explain use cases for deploy.link() function in migrations in truffle framework.
How would you use it and for what.
- 4,337
- 2
- 25
- 42
4 Answers
EDIT: As stated in the comment by @feihcsim
autolinkhas been deprecated
Let's say ecosystem of your dapp has a library and a contract that calls functions from that library. So you have:
library Converter {
function weiToEther() returns (uint256) { //return ether value }
}
Then you have contract:
import "Converter.sol";
contract MainContract {
function getBalanceInEth() returns (uint256) {
return Converter.weiToEther(this.balance);
}
}
So, in order for the MainContract to work, you will first need library deployed on the chain and also MainContract needs to know address of that library. To explicitly do this, you use:
module.exports = function(deployer) {
deployer.deploy(Converter);
deployer.link(Converter, MainContract);
deployer.deploy(MainContract);
};
or you can use:
module.exports = function(deployer) {
deployer.deploy(Converter);
deployer.autolink();
deployer.deploy(MainContract);
};
You can also find lots of useful information in this video
- 129
- 8
- 543
- 4
- 14
This function adds the given library to the links property of the destination contract. This ensures that the location of the deployed library can be found when the contract's bytecode is generated.
It also merges all of the library's events in with the destination contract.
API docs here: https://github.com/trufflesuite/truffle-contract#mycontractlinkinstance
See source here: https://github.com/trufflesuite/truffle-contract/blob/develop/contract.js#L539
As mentioned above by @feihcsim, this has to be done manually now: https://github.com/trufflesuite/truffle-deployer/commit/52e63189453e078f64b84aa3a50a2c7991b022b4
- 195
- 6
Take the default metacoin project that comes with truffle for example
// deploy ConvertLib into the network
deployer.deploy(ConvertLib);
// Take the deployed ConvertLib address and link it to MetaCoin contract in bytecode
deployer.link(ConvertLib, MetaCoin);
// Now deploy the linked metacoin contract to the network
deployer.deploy(MetaCoin);
From documentation:
Link an already-deployed library to a contract or multiple contracts. destinations can be a single contract or an array of multiple contracts. If any contract within the destination doesn't rely on the library being linked, the deployer will ignore that contract.
Example:
// Deploy library LibA, then link LibA to contract B, then deploy B.
deployer.deploy(LibA);
deployer.link(LibA, B);
deployer.deploy(B);
// Link LibA to many contracts
deployer.link(LibA, [B, C, D]);
- 5,143
- 29
- 47
autolinkhas been deprecated – feihcsim Dec 30 '17 at 14:18