1

How can I store the address of a deployed contract into a variable of another contract, e.g. using a placeholder?

contract One{ 
   function One(){
   }
}

contract Two{
   address oneAdd = "Put Contract One address here automatically?!";
   function Two(){
   }
}

Is that possible by editing the migration file of truffle?

1

One way to achieve this through the Truffle Migration files would be to modify contract Two such that its constructor takes an address as input and stores it as oneAdd, then deploy the contracts with the following migration file:

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

Alternatively, you could deploy One and Two first, then call a function in Two to set the address of One with an async migration as follows:

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

Note that if you choose this option you need to think carefully about who can call the setAddress function to prevent malicious actors from breaking your contract; ideally only transactions from authorised addresses would be allowed to call this function using some sort of onlyOwner or onlyAdmin modifier

  • I see how this works. Is there a solution without using the constructor tho? – Senju May 12 '18 at 9:20
  • Yes - I've updated my answer to show how this can be done – TC8 May 12 '18 at 9:57
0

just pass it through the constructor

pragma solidity ^0.4.23;


contract Two {
   address oneAdd;

   constructor(address _contractAddress) public {
      oneAdd = _contractAddress;
   }
}

or even better

pragma solidity ^0.4.23;

contract One{ 
   function One(){
   }
}
contract Two {
   One one;

   constructor(address _contractAddress) public {
      one = One(_contractAddress);
   }
}

when you deploy the contract via truffle or web3 you need to provide the address of the first contract in the constructor of the contract two.

If you do it via truffle migrations this is the syntax

deployer.deploy(Two, '[one_address]');
  • I see how this works. Is there a solution without using the constructor tho? – Senju May 12 '18 at 9:19
  • no, unless you manually define the address in your contract. – mirg May 12 '18 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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