Sample Solidity smart contract

Below is a sample Solidity smart contract called My First Contract. The contract sets and gets two variables (name and age). Experiment with the contract below to learn the basics of setters and getters.

Remember:

  • Saving a state variable to the blockchain uses gas
  • Pure, view and payable dictate a Solidity functions behavior.
  • If a behavior is not set the default behavior is read and write
  • Viewing state variables from the blockchain does not use gas

Deploy the sample Solidity smart contract below to the Ethereum test network using Remix. Try to add another set and get function. To start follow the pattern of the existing functions to create your own.

Try it in Remix

//define which compiler to use
pragma solidity ^0.8.6;

//contract name is MyFirstContract
contract MyFirstContract {

//create two variables.  A sting and an integer

    string private name;
    uint private age;

//set
    function setName(string memory newName) public {
        name = newName;
    }

//get
    function getName () public view returns (string memory) {
        return name;
    }
    
//set
    function setAge(uint newAge) public {
        age = newAge;
        
    }

//get
    function getAge () public view returns (uint) {
        return age;
    }
    
}

Try it in Remix

This code is for learning and entertainment purposes only. The code has not been audited and use at your own risk. Remember smart contracts are experimental and could contain bugs.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – Create an Address book smart contract in Solidity

-->

Leave a Reply