What is a contract in Solidity?

Overview

A Solidity contract is a block of code that contains functions and state variables. It is stored on a specific address on the Ethereum blockchain.

Creating a contract

Every Solidity code starts with the pragma version. The pragmaversion specifies the version of the compiler that the code should use.

pragma solidity ^0.5.0;
Pragma version declaration

To create a contract, we use the contract keyword followed by the contract name. Inside the {} brackets, we create the variables and functions.

Syntax

contract contractName {
// code
}
Syntax of a contract

Example

Let’s see how to create a contract in Solidity.

// declare pragma version
pragma solidity ^0.5.0;
// create contract
contract Example {
// create state variable
string str = "Edpresso";
// create function
function getStr() public view returns(string memory) {
return str;
}
}

Explanation

  • Line 2: We declare the pragma version ^0.5.0.
  • Line 5: We create a contract named Example.
  • Line 7: We declared a state variable str.
  • Line 10: We define a function getStr() that returns the value of str.

    Free Resources