Search code examples
blockchainethereumsoliditysmartcontractsether

Solidity Error :: ParserError: Expected '(' but got 'public'


I keep getting this error.......

"from solidity:
ParserError: Expected '(' but got 'public'
 --> contracts/3_Ballot.sol:6:24:
  |
6 |     function PiggyBank public()
  |                        ^^^^^^", 

what to do?

    pragma solidity ^0.8.0;
    contract PiggyBank{
    address creator;
    uint deposits;

    function PiggyBank public()          \\error in this line
    {
        creator=msg.sendor;
        deposits=0;
    }

    function deposit() payable returns(uint)
    {
        if(msg.value>0)
        deposits=deposits+1;
        return getNumberofDeposits();  
    }

    function getNumberofDeposits() constant returns(uint)
    {
        return deposit;
    }
    
    function Killl();{
    if(msg.sendor==creator)
    selfdestruct(creator);
    }
}

Solution

  • You're using syntax from older solidity versions, which is not supported in the current 0.8 version.

    First, to get rid of the syntax error, replace function PiggyBank public() to function PiggyBank() public.

    In older versions of Solidity (up to 0.5), a function with the same name as the contract was used as a constructor. In the current version 0.8, you need to use the constructor keyword - otherwise the function would be publicly invokable by anyone and anytime (not just during the contract deployment).

    // replace `function PiggyBank public()` to `constructor()`
    constructor() {
        creator=msg.sendor;
        deposits=0;
    }
    

    Then few more syntax errors (incorrectly defined functions; an extra semicolon at the Killl() function definition; missing visibility modifiers), a type error (selfdestruct argument needs to be payable), and typos (your code uses msg.sendor instead of msg.sender) show up. See the corrected code:

    pragma solidity ^0.8.0;
    
    contract PiggyBank {
        address creator;
        uint deposits;
    
        constructor() {
            creator=msg.sender;
            deposits=0;
        }
    
        function deposit() public payable returns(uint) {
            if(msg.value>0) {
                deposits=deposits+1;
            }
            return getNumberofDeposits();  
        }
    
        function getNumberofDeposits() public view returns(uint) {
            return deposits;
        }
        
        function Killl() public {
            if(msg.sender==creator) {
                selfdestruct(payable(creator));
            }
        }
    }