将字符串作为参数传递时出错(Solidity)
Posted
技术标签:
【中文标题】将字符串作为参数传递时出错(Solidity)【英文标题】:Error passing string as parameter (Solidity) 【发布时间】:2020-03-16 18:54:07 【问题描述】:我做了一个智能合约来投票,但我的一个功能(“结果”)有问题。智能合约来了:
pragma solidity ^0.5.7;
contract Voting
struct Option
string name;
uint256 votes;
Option[] private options;
address[] private alreadyVote;
address private owner = msg.sender;
constructor() public
function addOption(string memory _name) public
require(msg.sender==owner,"Permiso denegado");
options.push(Option(_name,0));
function vote(string memory _name) public
require(find(msg.sender,alreadyVote)==-1,"Ya ha ejercido su derecho a voto");
int candidateIndex = findOption(_name);
require(candidateIndex!=-1,"No se ha encontrado el candidato deseado");
options[uint(candidateIndex)].votes++;
alreadyVote.push(msg.sender);
function findOption(string memory _name) private view returns (int)
int result = -1;
for(uint i = 0;i<options.length;i++)
if(compareStrings(options[i].name,_name))
result = int(i);
return result;
function compareStrings (string memory a, string memory b) private pure returns (bool)
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) );
function find(address ad, address[] memory v) private pure returns (int)
int result = -1;
for(uint i = 0;i<v.length;i++)
if(v[i]==ad)
result = int(i);
return result;
function concat(string memory _base, string memory _value) public pure returns (string memory)
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for(i=0; i<_baseBytes.length; i++)
_newValue[j++] = _baseBytes[i];
for(i=0; i<_valueBytes.length; i++)
_newValue[j++] = _valueBytes[i];
return string(_newValue);
function getResult(string memory _name) public view returns (string memory ,uint)
require(msg.sender==owner,"Denied");
int index = findOption(_name);
string memory error = concat("Didn't found candidate ",_name);
require(index!=-1,error);
return (options[uint(index)].name,options[uint(index)].votes);
问题是,当我调用 gunction 结果时,会弹出第二个 require 语句。 Tgos os 我如何从 Web3.py 调用它:
tx = contract_instance.functions.getResult("Name").call('from':acct.address)
我认为这应该可行,因为我已经使用相同的语句调用函数 vote,但它非常有效。我是这样称呼它的:
tx = contract_instance.functions.vote(candidato).buildTransaction('nonce':w3.eth.getTransactionCount(acc),'gas': 1728712,'gasPrice': w3.toWei('21', 'gwei'))
#Get tx receipt to get contract address
signed_tx = w3.eth.account.signTransaction(tx, key)
我在 remix 上对其进行了测试并且工作正常,所以我真的不知道会发生什么。
【问题讨论】:
【参考方案1】:你有没有在getResult
之前调用addOption
函数?
正如你所说,你在第二个 require 语句上失败了,如果你传入一个不在候选列表中的名字,就会发生这种情况。
【讨论】:
以上是关于将字符串作为参数传递时出错(Solidity)的主要内容,如果未能解决你的问题,请参考以下文章
E0312, C2664 尝试将矢量对象作为函数参数传递时出错