1

I have a function in my contract minter.sol that creates another contract etnX.sol:

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

I want to call this function in truffle and get new contract address. I'm trying to do so:

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);
    })
};

However, it doesn't deploy. Can someone explain me how to do this?

1 Answer 1

3

1.) You can make the function emit an event that broadcasts the new address and then check the logs of the transaction receipt. Receipt


// 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.) You can return the contract address in the solidity function and then instead of initiating a transaction make a call() to get the address. (Then make the transaction....it will be deployed at the same address as returned by the 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.) Manually calculate it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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