Your First Contract

Your First Contract

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

contract Counter{
    uint count;

    constructor() public{
        count=0;
    }

    function getCount() public view returns(uint){
        return count;
    }

    function incrementCount() public{
        count=count+1;
    }
}

An SPDX-License-Identifier comment, specifies the license under which the smart contract is released. In this case, it is MIT (Massachusetts Institute of Technology) License.

The code should be compiled using a Solidity compiler of version 0.8.0 or higher.

The contract is named 'Counter'. Contracts in Solidity are similar to classes in object-oriented programming.

"uint count;": This declares a state variable named count of type uint (unsigned integer). It will be used to store a numerical value.

The constructor is executed only once when the contract is deployed. In this case, it initializes the count variable to 0 when the contract is deployed.

This function is a getter function named getCount that allows external parties to retrieve the value of the count variable. It is marked as public view, indicating that it can be called externally and does not modify the state of the contract.

This function is named incrementCount and is marked as public, meaning it can be called externally. It increments the value of the count variable by 1 each time it is called. This function modifies the state of the contract. Thus it requires some Gas.

Next we just compile the smart contract.

And next we deploy it.

Output

We can do some refactoring in the smart contract

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

contract Counter{
    uint public count = 0;

    function incrementCount() public{
        count=count+1;
    }
}

by writing 'uint public count' solidity exposes it free so now we can call it.

Did you find this article valuable?

Support Reuben D'souza by becoming a sponsor. Any amount is appreciated!