无法更改合同中的状态变量

Pet*_*all 1 ethereum solidity truffle

我正在使用Truffle和TestRPC开发以太坊合约.但是我无法获得要更新的状态变量.我认为可能只是因为我太早访问它,但其他示例测试似乎工作得很好并且非常相似.

我已经将合同减少到最简单的可能性:

pragma solidity ^0.4.11;

contract Adder {

    uint public total;

    function add(uint amount) {
        total += amount;
    }

    function getTotal() returns(uint){
        return total;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的考验:

var Adder = artifacts.require("./Adder.sol");

contract('Adder', accounts => {
  it("should start with 0", () =>
    Adder.deployed()
      .then(instance => instance.getTotal.call())
      .then(total => assert.equal(total.toNumber(), 0))
  );

  it("should increase the total as amounts are added", () =>
    Adder.deployed()
      .then(instance => instance.add.call(10)
        .then(() => instance.getTotal.call())
        .then(total => assert.equal(total.toNumber(), 10))
      )
  );

});
Run Code Online (Sandbox Code Playgroud)

第一次测试通过了.但第二次测试失败,因为getTotal仍然返回0.

Kla*_*aus 5

我相信问题是你总是使用这种.call()方法.

实际上,此方法将执行代码但不会保存到区块链.

.call()只有在从区块链中读取或测试时,才应使用该方法throws.

只需删除.call()添加功能,它应该工作.

var Adder = artifacts.require("./Adder.sol");

contract('Adder', accounts => {
  it("should start with 0", () =>
    Adder.deployed()
      .then(instance => instance.getTotal.call())
      .then(total => assert.equal(total.toNumber(), 0))
  );

  it("should increase the total as amounts are added", () =>
    Adder.deployed()
      .then(instance => instance.add(10)
        .then(() => instance.getTotal.call())
        .then(total => assert.equal(total.toNumber(), 10))
      )
  );
});
Run Code Online (Sandbox Code Playgroud)

另外,考虑instance在promise的函数链之外声明变量,因为不共享上下文.考虑使用async/await进行测试而不是promises.

var Adder = artifacts.require("./Adder.sol");

contract('Adder', accounts => {
  it("should start with 0", async () => {
    let instance = await Adder.deployed();
    assert.equal((await instance.getTotal.call()).toNumber(), 0);
  });

  it("should increase the total as amounts are added", async () => {
    let instance = await Adder.deployed();
    await instance.add(10);
    assert.equal((await instance.getTotal.call()).toNumber(), 10);
  });
});
Run Code Online (Sandbox Code Playgroud)