我正在尝试使用Hardhat/ether/TypeChain测试我的投票选票合同,但出于某种原因,选票结构的类型记录界面没有显示我在智能契约中定义的选择结构字段的数组。

下面是TypeScript测试文件,它没有在选票映射返回的选票中显示Choice[]选择字段。

以下是整个智能契约代码: // SPDX-许可证-标识符: MIT实用主义稳固性^0.8.0;
合约投票{
// @dev for voters we need to check address has been approved for voting using mapping
mapping(address => bool) public voters;
// e.g. inflate jewel by 5% - id: 1, string: 5% inflation, votes: (0)
struct Choice {
uint id;
string name;
uint votes;
}
// e.g. Ballot = vote, id: 1, name: jewel inflation, list of choices, end of ballot/time
struct Ballot {
uint id;
string name;
Choice[] choices;
uint end;
}
// @dev id of each ballot
mapping(uint => Ballot) public ballots;
uint nextBallotId;
address public admin;
// @dev check if address of voter has already voted for a given ballot
mapping(address => mapping(uint => bool)) public votes;
constructor() {
admin = msg.sender;
}
// [0xef..., 0xerfdf..]
function addVoters(address[] calldata _voters) onlyAdmin() external {
for(uint i = 0; i < _voters.length; i++) {
// e.g. voters[[0xef]] = true
voters[_voters[i]] = true;
}
}
function createBallot(
string memory name,
string[] memory _choices,
uint offset
) public onlyAdmin() {
// @dev can't assign due to Choices[] array as ballot's data location is STORAGE not MEMORY
// e.g. Choice[] memory _choices = new ...
// ballots[nextBallotId] = Ballot(nextBallotId, name, **_choices**, end)
// @dev can acccess field of struct that hasn't been created yet
ballots[nextBallotId].id = nextBallotId;
ballots[nextBallotId].name = name;
ballots[nextBallotId].end = block.timestamp + offset;
for(uint i = 0; i < _choices.length; i++) {
ballots[nextBallotId].choices.push(Choice(i, _choices[i], 0));
}
nextBallotId++;
}
function vote(uint ballotId, uint choiceId) external {
require(voters[msg.sender] = true, 'only voters can vote');
require(votes[msg.sender][ballotId] == false, 'voter can only vote once per ballot');
require(block.timestamp < ballots[ballotId].end, 'can only vote after ballot end date');
votes[msg.sender][ballotId] = true;
ballots[ballotId].choices[choiceId].votes++;
}
function results(uint ballotId)
view
external
returns(Choice[] memory) {
require(block.timestamp >= ballots[ballotId].end, 'cannot see the ballot result before ballot end');
return ballots[ballotId].choices;
}
modifier onlyAdmin() {
require(msg.sender == admin, 'only admin');
_;
}}
发布于 2022-04-08 19:19:07
注意,在您发布的代码中,您还没有指定具有公共可见性的ballots变量。
必须指定public状态变量的ballots可见性。在您的例子中,请更改以下内容:
mapping(uint => Ballot) ballots;并将其替换为:
mapping(uint => Ballot) public ballots;定义public时,编译器会自动为变量生成getter函数,这些变量允许查看或处理这些值。
有关可见性这里的更多信息。
https://ethereum.stackexchange.com/questions/125369
复制相似问题