【问题标题】:Using events to read solidity struct使用事件读取solidity struct
【发布时间】:2022-08-04 02:38:48
【问题描述】:

我的智能合约有一个结构和一个填充它的函数:

    struct voter {
    uint ID;
    string firstName;
    string lastName;
    uint phone;
    string addy;
    //add picture
    }

contract Poll {
    uint public numVoters;

    event VoterAdded(
        voter newVoter
    );

    function AddVoter(string memory _firstName, string memory _lastName, uint _phone, string 
    memory _addy) public returns (voter memory){
        numVoters++;
        voter memory _voter = voter(numVoters, _firstName, _lastName, _phone, _addy);
        _voter.ID = numVoters;
        _voter.firstName = _firstName;
        _voter.lastName = _lastName;
        _voter.phone = _phone;
        _voter.addy = _addy;
        emit VoterAdded(_voter);
        return _voter;
    }
}

我正在使用 truffle 来测试这个结构,我试图填充一个结构,然后将一个结构变量存储在一个 javascript 变量中。

const Poll = artifacts.require(\'Poll.sol\');

it(\'Poll 1 : create voter and candidate objects2\', async () => 

        const tx = await poll.AddVoter(\'Jack\', \'Jackson\', 0, \'\');

        const results = await poll.getPastEvents(
            \'VoterAdded\',
            {
                fromBlock: 0, toBlock: \'latest\'
            });
    
        console.log(\"Results\", results, \'${results.length} results\');

        const JJ = results[0];      
        assert.equal(JJ.firstName, \'Jack\');

    });

我认为 getPastEvents() 之后的行有问题。

这是我得到的错误: 投票 1:创建选民和候选人对象2: AssertionError: 预期未定义等于 \'Jack\'

    标签: javascript solidity web3js truffle


    【解决方案1】:

    我不知道它是否有用,但我总是使用queryFilter 来获取过去的事件。

    const eventFilter = poll.filters.VoterAdded();
    const events = await poll.queryFilter(eventFilter);
    console.log(events);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 2019-09-16
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多