【问题标题】:Unable to change a state variable in a contract无法更改合约中的状态变量
【发布时间】:2017-07-01 23:44:21
【问题描述】:

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

我已将我的合同缩减为最简单的违约事项:

pragma solidity ^0.4.11;

contract Adder {

    uint public total;

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

    function getTotal() returns(uint){
        return total;
    }
}

这是我的测试:

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

});

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

【问题讨论】:

    标签: ethereum solidity truffle


    【解决方案1】:

    我认为问题在于您总是使用.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))
          )
      );
    });
    

    另外,考虑在 promise 的函数链之外声明 instance 变量,因为上下文不共享。考虑将async/await 用于测试而不是承诺。

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

    【讨论】:

    • 我知道这会很简单!
    • 这需要更多的支持。在我得到这个答案之前,我被困了 2 个小时
    猜你喜欢
    • 2021-12-26
    • 2022-07-09
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    相关资源
    最近更新 更多