logoAcademy

Solidity File Structure

Learn about Solidity

Now that we understand how to write (very basic) smart contracts in their entirety, we are certainly ready to deploy smart contracts onto the blockchain... right?

Unfortunately, we are not yet ready to do so. To understand why, consider the EVM, the virtual machine which will be executing the logic of your smart contract. The EVM does not execute Solidity code - rather, it executes opcodes in the form of bytes. Therefore, for any Solidity smart contract that we develop, we need a way to convert it into EVM bytecode that the EVM can then parse.

Although the above sounds like a complex task, this is actually not the case! All we need to do is put our smart contract logic into a .sol file, which a Solidity compiler can then convert into EVM bytecode!

Compiler and License

At the top of every Solidity file goes the SPDX-License-Identifier. This identifier specifies how you wish for the source code of your file to be used by other people. The most popular SPDX-License-Identifier is the MIT identifier. Afterwards, we will want to specify the version of Solidity that we want to use to compile our source code. This is usually in the format of the following:

pragma solidity <version>;

For more information regarding which version of Solidity you should use, head over to the official Solidity documentation where you can find more information about the details of each release version. Generally speaking though, the following can be observed about the age of release versions:

  • Older release versions are less optimized and lack many features of newer Solidity versions, but they have been battle-tested over the years and are thus more secure
  • Newer release versions bring much-desired features and are more optimized, but have had less time to be tested for security purposes

Sometimes, you might see the following inside a Solidity file:

pragma solidity ^<version>;

The caret specifies that the source file is meant to be compiled with any version of Solidity that is compatible with version. As an example, consider the line: pragma solidity ^0.6.4;

Then the source file can be compiled with any version of Solidity that has the prefix 0.6. However, any compiler whose prefix does not match that of 0.6 cannot compile the source file above.

Tying Everything Together

The below is an example of a Solidity source file that can be compiled into bytecode:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract A {
 
    uint256 num;
  
    function getNum() public view returns(uint) {
        return num; 
    }
  
    function setNum(uint _num) public {
        num = _num;
    }
  
}

On this page