Solidity – Resolving DeclarationError for File Level Constants in Remix

remixsolidity

i just start learning the solidity and smart contract and i got this error

DeclarationError : Only constant variables are allowed at file level
this is my code :

    // SPDX-License-Identifier: MIT
    
    pragma solidity >=0.7.0 <0.9.0;
    
    contract SimpleStorage {
        address Address;
        string name;
    }
    
    struct People {
        string Name;
        address Address;
    
    }
    
    People[]  people;
    
         

 mapping(string => address)  NametoAddress;

          
    
    function addPerson(string memory _Name, address memory _address)  {
        people.push(People(_Name, _address));
        NametoAddress [_Name] = _address;
       

}

the error is in this 3 lines :

People[] people;

mapping(string => address) NametoAddress;

function addPerson(string memory _Name, address memory _address) {

Best Answer

The issue is because of the wrong placement of the }.

contract SimpleStorage {
    address Address;
    string name;
}

Because of this, the contract, technically ends after declaring the name string. Everything else is considered to be outside the contract, hence you got the error.

However, there are a couple more issues in the code, unrelated to this error.

  1. You need to mention the visibility for addPerson function.
  2. Input parameter _address doesn't need the keyword 'memory' as data location is only required for arrays, mapping and stucts.
function addPerson(string memory _Name, address _address) public {
    ...
}

The whole contract after the changes will be like this

// SPDX-License-Identifier: MIT
    
pragma solidity >=0.7.0 <0.9.0;
    
contract SimpleStorage {
        
    address Address;
    string name;
    
    struct People {
        string Name;
        address Address;
    }
    
    People[]  people;
    
    mapping(string => address)  NametoAddress;
    
    function addPerson(string memory _Name, address  _address)  public {
        people.push(People(_Name, _address));
        NametoAddress [_Name] = _address;
    }

}

All the best with solidity!

Related Topic