Truffle

通過 Truffle 中的另一個合約函式部署新合約

  • April 18, 2019

我的契約minter.sol中有一個功能可以創建另一個契約etnX.sol

function createNewContract(string memory name, string memory symbol, uint256 _maxSupply) 
public onlyOwner {
   etnX c = new etnX(name, symbol, _maxSupply, address(store));
}

我想在松露中呼叫這個函式並獲取新的合約地址。我正在嘗試這樣做:

const minter = artifacts.require('../contracts/minter.sol')
const etnX = artifacts.require('etnX')
const etnXs = [100,200,500,1000,10000,100000,1000000,10000000]
module.exports = async function(deployer) {
   deployer.deploy(minter).then(async() => {
      var minterInstance = await minter.deployed();
      for (var i=0; i<etnXs.length;i++)
          await minterInstance.createNewContract("x","x", etnXs[i]);
          var x = await etnX.deployed();
          console.log(x.address);
   })
};

但是,它不會部署。有人可以解釋我該怎麼做嗎?

1.) 你可以讓函式發出一個廣播新地址的事件,然後檢查交易收據的日誌。 收據


// Solidity
function createNewContract(string memory name, string memory symbol, uint256 _maxSupply) 
public onlyOwner {
   etnX c = new etnX(name, symbol, _maxSupply, address(store));
   emit NewContract(address(c));
}

// Javascript
let tx = await minterInstance.createNewContract("x", "x", 300); 
// Look through tx.logs for event results

2.) 您可以在solidity 函式中返回合約地址,然後呼叫() 來獲取地址,而不是發起交易。(然後進行交易……它將部署在與 call() 返回的地址相同的地址)


// Solidity
function createNewContract(string memory name, string memory symbol, uint256 _maxSupply) 
public onlyOwner 
returns (address) {
   etnX c = new etnX(name, symbol, _maxSupply, address(store));
   return address(c)
}

// Javascript
let addr = await minterInstance.createNewContract.call("x", "x", 300); 

3.) 手動計算

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