区块链学习笔记:投票智能合约 之 初始化投票

in HIVE CN 中文社区3 years ago (edited)

人常说,眼过千遍不如手过一遍,这话还真的很多,尤其是学习计算机编程,所谓“好记性不如烂笔头”,更是要勤动手,切忌眼高手低。

看了下教程的关于solidity,里边有个案例是做一个智能合约的投票系统,想了下,还是跟着动手去尝试做下,毕竟孔子都说过,学而不思则罔嘛。

投票系统的设想如下,

1> 四个人分别为A、B、C、D

2>有三个提议可以投票,分别为P1、P2、P3

接下来尝试开始编写初始化投票智能合约,见如下图,

image.png

刚开始编写,就发现几个地方有问题。
首先是提示:

SPDX license identifier not provided in source file. Before publishing, consider adding a comment containing "SPDX-License-Identifier: " to each source file. Use “SPDX-License-Identifier: UNLICENSED” for non-open-source code. Please see https://spdx.org for more information.

我按照提示,在代码最顶部加上了如下代码,就可以了。

// SPDX-License-Identifier: SimPL-2.0

第二个问题,就是在构造函数这里。
我开始用的是solidity ^0.8.6 版本,

function Ballot(bytes32[] proposalNames)
系统提示出错,说建议将此构造函数改为新的写法
constructor()

我改成如下,

constructor Ballot(bytes32[] proposalNames)

却发现始终提示如下错误,

ParserError: Expected '(' but got identifier--> contracts/Ballot.sol:40:15:|40 | constructor >Ballot(bytes32[] proposalNames)
| ^^^^^^

只好又改回老版本 solidity ^0.4.17,这才编译成功。

这次以为OK了,结果在测试的时候,发现输入数组["item1","item2"]后,总是提示如下错误,

creation of Ballot errored: Error encoding arguments: Error: invalid arrayify value (argument="value", value="item1", code=INVALID_ARGUMENT, version=bytes/5.4.0)

这又是怎么回事呢?

继续研究中。。。

Sort:  

原来是说这个参数无效,需要32 bytes long才可以

尝试输入:

["0x6c00000000000000000000000000000000000000000000000000000000000000","0x6c00000000000000000000000000000000000000000000000000000000000001"]

显示:

[vm] from: 0x5B3...eddC4to: Ballot.(constructor)value: 0 weidata: 0x608...00001logs: 0hash: 0x093...29398

查看明细,果然可以了。

有意思,这编程确实需要一个一个问题去找和解决