Search code examples
mappingethereumsoliditysmartcontracts

Expected Primary Expression (Solidity)


I am creating a simple smart contract, however, I am getting an error on my last function ("ViewNotes") stating that the compiler was "Expected Primary Expression"? Can I not check the value at a mapping (of address => string) against the value 0 ?

My code:

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));   
    }
}

}


Solution

  • There are a couple issues. The primary issue is that you misspelled !=. (You have an extra equals sign. !== is an operator in JavaScript, but not in Solidity.)

    Once you fix that, you'll find that you can't compare a string to the number 0. You probably want to check the string's length? You'll need to cast to bytes to do that:

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

    That said, I believe this is probably equivalent to just:

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

    And you could instead just make notes public:

    mapping(address => string) public notes;
    

    That way, Solidity will generate a getter function for you, and people can just call notes(addr), making viewNotes redundant.

    Fixing up a couple other warnings, getting rid of the modifier in favor of a direct ownership check, and assigning initial ownership to the deployer, here's my take on the contract:

    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;
        }
    }