预期的主要表达(固体)

时间:2018-08-04 01:00:23

标签: mapping ethereum solidity smartcontracts

我正在创建一个简单的智能合约,但是,上一个函数(“ ViewNotes”)出现错误,指出编译器是“期望的主表达式”?我不能对照值 0 来检查(地址=>字符串)映射的值吗?

我的代码:

pragma solidity ^0.4.4;

contract Logistics{

address public owner;
mapping(address => string) notes;

modifier onlyOwner() {
    require(msg.sender == owner);
    _;
}

constructor(address genesis) public {
   owner = genesis;
}

function sign(string signedNote) public onlyOwner{
        notes[owner] = signedNote; //gaurenteed that msg.sender == owner
}

function transferOwnership(address nuOwner) onlyOwner {
    owner = nuOwner;
}

function viewNotes(address participant) public returns(string){ // signed note on success nothing on fail
    if(notes[participant] !== 0){
        return (notes(participant));   
    }
}

}

1 个答案:

答案 0 :(得分:1)

有两个问题。主要问题是您拼错了!=。 (您有一个等号。!==是JavaScript中的运算符,但不是Solidity中的运算符。)

解决此问题后,您将发现无法将string与数字0进行比较。您可能要检查字符串的长度?您需要强制转换为bytes才能做到:

function viewNotes(address participant) public returns (string) {
    if (bytes(notes[participant]).length != 0) {
        return notes[participant];
    }
}

也就是说,我相信这可能等同于:

function viewNotes(address participant) public returns (string) {
    return notes[participant];
}

您可以改成notes public

mapping(address => string) public notes;

这样,Solidity将为您生成一个getter函数,人们可以只调用notes(addr),从而使viewNotes变得多余。

修正了一些其他警告,摆脱了使用直接所有权检查的修饰符,并将初始所有权分配给部署者,这是我对合同的看法:

pragma solidity ^0.4.24;

contract Logistics{
    address public owner = msg.sender;
    mapping(address => string) public notes;

    function sign(string note) public {
        require(msg.sender == owner);
        notes[owner] = note;
    }

    function transferOwnership(address newOwner) public {
        require(msg.sender == owner);
        owner = newOwner;
    }
}