Solidity
Truffle migrate:將部署的合約地址儲存在變數中
如何將已部署合約的地址儲存到另一個合約的變數中,例如使用佔位符?
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) }); };
或者,您可以先部署
One
,Two
然後呼叫一個函式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
函式以防止惡意行為者破壞您的契約;理想情況下,僅允許來自授權地址的交易使用某種onlyOwner
或onlyAdmin
修飾符呼叫此函式