truffle deployed contract – How to Get a Deployed Contract Instance in Truffle Console

consoletruffletruffle-deploymenttruffle-migration

I have a contract deployed with truffle to a testrpc local testnet.
This contract has has a function that deploys a new contract.

This new contract I can check the address in the testrpc console similar to this:

  Transaction: 0x85a7f17406536dd9618c6647d7d0595a2cee7e7e065ffc08a99e58aa5473ab71
  Contract created: 0x1104c5adf4476aec333ee687c725eacc8d417a7c
  Gas usage: 2642382
  Block Number: 7
  Block Time: Mon Feb 26 2018 19:27:25 GMT+0900 (JST)

But how can I use this new contract in the truffle console to interact with?
The json file of the contract (the ABI etc) was created in truffle's build directory, but because the contract is not migrated I cannot use this command:

MyNewContract.deployed().then(_app => { app = _app })
app.showMeTheMoney()

Does anyone how, in the truffle console, I can interact with contracts deployed through other contracts?

Best Answer

You could manually modify the contract file in the build directory to include the address, but it will get overwritten eventually, so it's not a good way to do this.

Moreover deployed() is meant to be used in the sense of a singleton. If your contract is not a singleton then you shouldn't query it via deployed().

If you have the following constellation: contract A (singleton) instantiates contract B then you can store the reference(s) to B in A and query it from JavaScript.

Example

contract A {
    B[] public arrayOfBs;
    function create() returns (B) {
        B b = new B();
        arrayOfBs.push(b);
        return b;
    }
}

deployer.deploy(A);
...
A.deployed()
    .then(a => {return a.arrayOfBs(idx)})
    .then(bAddr => {return B.at(b)})
    .then(b => {b.showMeTheMoney()})

If B should be a singleton, then you need to change your migration script and deploy it like this.

deployer.deploy(A); 
deployer.deploy(B);

Then you'll be able to query it via B.deployed().

Related Topic