Bereitstellung eines neuen Vertrags im Truffle-Testfall

Ich habe versucht, in meinem Trüffel-Testfall zwischen zwei Verträgen zu handeln. Habe es aber nicht geschafft. Die zweite Vertragsinstanz kommt immer undefiniert zurück.

Gemäß der Truffle-Dokumentation ist die Bereitstellung eines neuen Vertrags in einem Testfall wie unten gezeigt:Contract2.new().then(function(instance) { contract2Instance = instance; });

Der Fehler, den ich bekomme, ist TypeError: Cannot read property 'address' of undefinedeingeschaltetContract2Address = contract2Instance.address;

Irgendeine Idee, was ich falsch mache?

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: Bitte entschuldigen Sie die Mischung aus neuer und alter Syntax. Der gesamte Test funktioniert jedoch in der Truffle-Konsole.

Antworten (1)

Sie versuchen, die Adresse abzurufen, bevor die Variable zugewiesen wurde. Sehen Sie, ob diese Kommentare helfen:

// 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;

Denken Sie daran, dass ein Promise in der Zukunft aufgelöst wird, also wird Ihr Callback-Code dann ausgeführt. In der Zwischenzeit geht die Hinrichtung weiter.

Du willst stattdessen so etwas:

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