Published on

How to Initialize a Contract from a Contract Address in Ethereum

Authors

Getting the address of a contract initialised in another contract

In Solidity if you initialise a contract inside a function and do not mark that variable as memory then that contract has its address added to the chain:

function someFunction() {
...
address contractsAddress = new YourContract();
...
}

To access this address you should emit it using an event:

event EventFiredOnYourContract(address newContractAddress);

function someFunction() {
...
address contractsAddress = new YourContract();

emit EventFiredOnYourContract(contractAddress);
...
}

Determining the ABI for a contract

You now need to get the ABI for your contract so that you can use it in your web3 code. To see what the JSON ABI for your contract looks like:

  1. Write a truffle migration for it
  2. Run truffle migrate
  3. Look in the build folder for a JSON file that has the same name as your contract. In that JSON file you'll find what the ABI JS object looks like.

Using the ABI together with the contract's address to initialise the contract in web3

You can then use this contract's ABI together with this address to initialize that specific version of the contract. It would look something like this in web3:

var contractConstructor = web3.eth.contract(abiObjectHere)

var contract = contractConstructor.at(addressYouEmitted)
//you can now access any contract methods and variables defined on contract

Caution

One thing to watch out for is if you Google web3 the readthedocs page comes up, but this page is for version 1.0 of the API which -as of the writing of this post- has not been released yet. Instead rather refer to the web3 wiki.