DEV Community

Loading Blocks
Loading Blocks

Posted on

First Smart Contract

Basic Struct of smart contract

Pragma version declaration

Each Solidity source file should begin with a pragma statement.

It specifies the compatible compiler version range. It helps prevent potential errors or vulnerabilities.

For example:

pragma solidity >=0.7.0 <0.9.0;: This pragma means that contract can be compiled with versions from 0.7.0 up to, but not including 0.9.0.

contract definition

Use the contract keyword to define a contract, similar to a class in other languages.

The contract name usually matches the file name and uses PascalCase.

State variables

Variables declared inside the contract but outside functions are called state variables.

Their values are permanently stored on the blockchain, representing the contract's state.

On-chain storage is very expensive because all nodes in the network must store the data permanently and network-wide consensus to ensure immutable, trustworthiness.

Who pays the cost?

  1. The developer pays the deployment fee.
  2. any user initiating a transaction to modify these state variables must pay the corresponding Gas fee.

function

Functions are executable blocks of code defining contract behavior. They can accept parameters and return values.

A simple HelloWorld contract

// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;

contract HelloWorld {
   uint256 number;
   function store(uint256 num) public {
      number = num;
   }

   function get() public view returns (uint256) {
      return number;
   }
}
Enter fullscreen mode Exit fullscreen mode

This is a simple HelloWorld contract demonstrating state variable storage and retrieval.

Interaction

After deployment, the contract instance appears in the 'Deployed Contract' area.

You can input parameters to call the store function, which modifies the blockchain state and also you can click the get function to read the current state value, which is a read-only operation.

Top comments (0)