0

I was trying to transact between two contracts inside my truffle test case. But not been able to do it. The second contract instance comes back undefined always.

As per the truffle documentation, deploying new contract inside a test case is as shown below, Contract2.new().then(function(instance) { contract2Instance = instance; });

The error I'm getting is TypeError: Cannot read property 'address' of undefined on Contract2Address = contract2Instance.address;

Any idea what I'm doing wrong?

var Contract1 = artifacts.require("./Contract1.sol");
var Contract2 = artifacts.require("./Contract2.sol");

contract('Contract1', function(accounts) {
  it("should put 30000000 in the second account", function() {
    var contract1Instance;
    var contract2Instance;

    var Contract1Address;
    var Contract2Address;

    return Contract1.deployed().then(function(instance) {
      contract1Instance = instance;
      Contract1Address = contract1Instance.address;  
      console.log("Contract1Address:" + Contract1Address);
      Contract2.new().then(function(instance) { contract2Instance = instance; });
      console.log("contract2Instance:" + contract2Instance);
      Contract2Address = contract2Instance.address;

      contract1Instance.deposit({from: accounts[0], value: web3.toWei(2, "ether") });
      contract2Instance.claim({ value: web3.toWei(1, "ether"), gas: 1000000 });
      return web3.eth.getBalance(Contract2Address).toString(10);
    }).then(function(balance) {
      assert.equal (30000000, 30000000, "30000000 wasn't in the first account");
    });
  });

PS: Please pardon the mix of the new and old syntax. The whole test works in truffle console though.

1 Answer 1

0

You're trying to get the address before the variable has been assigned to. See if these comments help:

// Contract2.new() runs first.
Contract2.new().then(function(instance) {
    // This assignment runs third (or at any time in the future).
    contract2Instance = instance;
});

// This code runs second.
console.log("contract2Instance:" + contract2Instance);
Contract2Address = contract2Instance.address;

Remember that a promise is resolved in the future, so that's when your callback code runs. In the meantime, execution keeps going.

You want something like this instead:

return Contract2.new().then(function (contract2Instance) {
  // All the code that requires contract2Instance must be in here.

  contract1Instance.deposit({from: accounts[0], value: web3.toWei(2, "ether") });
  contract2Instance.claim({ value: web3.toWei(1, "ether"), gas: 1000000 });
  return web3.eth.getBalance(contract2Instance.address).toString(10);
});

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.