Solidity

Truffle migrate:將部署的合約地址儲存在變數中

  • May 12, 2018

如何將已部署合約的地址儲存到另一個合約的變數中,例如使用佔位符?

contract One{ 
  function One(){
  }
}

contract Two{
  address oneAdd = "Put Contract One address here automatically?!";
  function Two(){
  }
}

可以通過編輯松露的遷移文件來實現嗎?

通過 Truffle 遷移文件實現此目的的一種方法是修改合約Two,使其建構子將地址作為輸入並將其儲存為oneAdd,然後使用以下遷移文件部署合約:

var One = artifacts.require("./One.sol");
var Two = artifacts.require("./Two.sol");

module.exports = (deployer, network) => {
 deployer.deploy(One).then(function() {
   return deployer.deploy(Two, One.address)
 });
};

或者,您可以先部署OneTwo然後呼叫一個函式Two來設置One非同步遷移的地址,如下所示:

var One = artifacts.require('./One.sol');
var Two = artifacts.require('./Two.sol');

module.exports = async(deployer) => {
   let deployOne = await deployer.deploy(One);
   let deployTwo = await deployer.deploy(Two);
   contractTwo = await Two.deployed()
   let setAddress = await contractTwo.setAddress(
       One.address,
       { gas: 200000 }
   );
 };

請注意,如果您選擇此選項,您需要仔細考慮誰可以呼叫該setAddress函式以防止惡意行為者破壞您的契約;理想情況下,僅允許來自授權地址的交易使用某種onlyOwneronlyAdmin修飾符呼叫此函式

引用自:https://ethereum.stackexchange.com/questions/48235