Learn

Solidity Smart Contract Development Basic Tutorial

A practical Solidity primer for builders who want to move from fundamentals into common patterns, testing, and real contract use cases.

SolidityCore syntax, structure, and workflow basics
Hands-onCode samples covering contracts, testing, and security

Introduction to Solidity

What is Solidity?

Solidity is an object-oriented high-level programming language specifically designed for writing smart contracts. Smart contracts are programs that are automatically executed on the blockchain and can be used to implement various decentralized applications (DApps).

History of Solidity

Solidity was created in 2014 by members of the Ethereum Foundation to provide an easy-to-use programming language for the Ethereum blockchain. Since then, Solidity has continued to evolve and become one of the most popular smart contract programming languages.

Installing the Solidity compiler

There are many ways to install the Solidity compiler. Here are some common methods:
Using the Node.js package manager npm:

npm install -g solc

            
Using Docker:

docker pull ethereum/solc:stable

            
Online compiler:
Remix IDE: https://remix.ethereum.org/

Solidity Basic Syntax

Variables and Data Types

Solidity supports a variety of data types, including primitive types and complex types.
  • Basic Types
  • Boolean:bool
  • Integer: int,uint
  • Address type:address
  • String:string
  • Byte type:bytes
  • Complex Types
    • Array: uint[],uint[5]
    • Mapping:mapping(address => uint)
    • Structure:struct Person { string name; uint age; }

function

Functions are the basic building blocks in Solidity and are used to define the behavior of a contract.
        
pragma solidity ^0.8.0;

contract Example {
    function add(uint a, uint b) public pure returns (uint) {
        return a + b;
    }
}

Control Structure

Solidity supports common control structures such as conditionals and loops.
Conditional Statements
        
function checkAge(uint age) public pure returns (string memory) {
    if (age < 18) {
        return "Underage";
    } else {
        return "Adult";
    }
}

Loop Statements
        
function sum(uint n) public pure returns (uint) {
    uint result = 0;
    for (uint i = 1; i <= n; i++) {
        result += i;
    }
    return result;
}

event

Events are used to record important operations of the contract, and these events can be listened to in the front-end application.
        
event Transfer(address indexed from, address indexed to, uint value);

function transfer(address _to, uint _value) public {
    // Execute transfer logic
    emit Transfer(msg.sender, _to, _value);
}

Error handling

Solidity provides a variety of error handling mechanisms such as require, assert and revert.
        
function divide(uint a, uint b) public pure returns (uint) {
    require(b != 0, "Divisor cannot be zero");
    return a / b;
}

Smart Contract Basics

The concept of smart contracts

A smart contract is a self-executing contract whose terms are written directly into the code. On the blockchain, smart contracts can be used to implement a variety of decentralized applications.

Creating the first smart contract

        
pragma solidity ^0.8.0;

contract HelloWorld {
    string public message;

    constructor(string memory initMessage) {
        message = initMessage;
    }

    function updateMessage(string memory newMessage) public {
        message = newMessage;
    }
} 

Contract state variables

State variables are variables stored on the blockchain and are used to save the state information of the contract.
        
contract Storage {
    uint256 public storedData;

    function set(uint256 x) public {
        storedData = x;
    }

    function get() public view returns (uint256) {
        return storedData;
    }
}

Function modifiers

Function modifiers are used to modify the behavior of a function. Common modifiers include view, pure and payable.
        
contract ModifierExample {
    uint256 public value;

    function setValue(uint256 _value) public {
        value = _value;
    }

    function getValue() public view returns (uint256) {
        return value;
    }

    function add(uint256 a, uint256 b) public pure returns (uint256) {
        return a + b;
    }

    function payMe() public payable {
        // Receive Ether
    }
}

Constructor

The constructor is executed when the contract is deployed and is used to initialize the state of the contract.
 
contract ConstructorExample {
    uint256 public initialValue;

    constructor(uint256 _initialValue) {
        initialValue = _initialValue;
    }
}

Advanced Features

inherit

Inheritance allows one contract to inherit the functionality of another contract.
        
contract Base {
    uint256 public baseValue;

    function setBaseValue(uint256 _value) public {
        baseValue = _value;
    }
}

contract Derived is Base {
    uint256 public derivedValue;

    function setDerivedValue(uint256 _value) public {
        derivedValue = _value;
    }
}

interface

An interface defines a set of method signatures but does not include implementations.
        
interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
}

contract MyToken is IERC20 {
    uint256 private _totalSupply;
    mapping(address => uint256) private _balances;

    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view override returns (uint256) {
        return _balances[account];
    }

    function transfer(address recipient, uint256 amount) public override returns (bool) {
        _balances[msg.sender] -= amount;
        _balances[recipient] += amount;
        return true;
    }
}

Library

Libraries are used to define a set of reusable functions.
        
library Math {
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }
}

contract LibraryExample {
    using Math for uint256;

    function getMax(uint256 a, uint256 b) public pure returns (uint256) {
        return a.max(b);
    }
}

Internal and external calls

Internal calls and external calls are used to call functions within the same contract and functions of different contracts respectively.
        
contract InternalExternalCalls {
    uint256 public value;

    function internalCall() internal {
        value = 100;
    }

    function externalCall() public {
        internalCall();
    }
}   

Gas Optimization

Gas is the fee required to execute smart contract operations in the Ethereum network. Optimizing Gas consumption can reduce transaction costs and improve contract efficiency.
Common Gas Optimization Techniques
  • Reduce storage read and write: Minimize the read and write operations on state variables.
  • Batch operations: combine multiple operations into one transaction.
  • Use memory variables: Use memory variables inside functions instead of state variables.
  • Avoid loops: Try to avoid using loops in your contracts, especially when large amounts of data are involved.
Example: Optimizing storage reads and writes
        
pragma solidity ^0.8.0;

contract GasOptimization {
    uint256[] public data;

    function addData(uint256[] memory newData) public {
        for (uint256 i = 0; i < newData.length; i++) {
            data.push(newData[i]);
        }
    }

    function getDataLength() public view returns (uint256) {
        return data.length;
    }

    function optimizeGetDataLength() public view returns (uint256) {
        uint256 len = data.length;
        return len;
    }
}

Events and Logs

Events and logs are used to record important operations of the contract, and these events can be monitored in the front-end application.
Example: Using events to record transfers
        
pragma solidity ^0.8.0;

contract EventExample {
    event Transfer(address indexed from, address indexed to, uint256 value);

    function transfer(address _to, uint256 _value) public {
        emit Transfer(msg.sender, _to, _value);
    }
}

Automated testing

Automated testing is a key step to ensure the correctness of smart contracts. Tools such as Truffle and Mocha can be used to easily write and run test cases.
Example: Writing a unit test
        
const MyContract = artifacts.require("MyContract");

contract("MyContract", (accounts) => {
    let instance;

    beforeEach(async () => {
        instance = await MyContract.new();
    });

    it("should set the initial value", async () => {
        const value = await instance.getValue();
        assert.equal(value, 0, "Initial value should be 0");
    });

    it("should update the value", async () => {
        await instance.setValue(100);
        const value = await instance.getValue();
        assert.equal(value, 100, "Value should be updated to 100");
    });

    it("should emit an event on value update", async () => {
        const result = await instance.setValue(100);
        const event = result.logs[0].args;
        assert.equal(event.newValue.toNumber(), 100, "Event should log the new value");
    });
});

Common design patterns

  • Proxy mode: used to upgrade smart contracts.
  • Factory pattern: used to create multiple contract instances.
  • Access control mode: used to limit access rights to the contract.

Security and best practices

Common security vulnerabilities

  • Reentrancy attack: Stealing funds by calling contract functions multiple times.
  • Overflow and underflow: Errors caused by numerical operations.
  • Timestamp dependency: Depends on block timestamps for decision making.

Security Audit Tools

  • MythX: Professional smart contract security audit tool.
  • Slither: An open source smart contract security analysis tool.
  • Echidna: A security audit tool based on fuzz testing.

Writing secure smart contracts

  • Use the latest Solidity version.
  • Avoid using low-level calls.
  • Use OpenZeppelin library.

Contract Application

Simple ERC20 token contract

        
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract MyToken is ERC20 {
    constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
        _mint(msg.sender, initialSupply);
    }
}

Decentralized voting system

        
pragma solidity ^0.8.0;

contract Voting {
    struct Proposal {
        bytes32 name;
        uint256 voteCount;
    }

    address public chairperson;
    mapping(address => bool) public voters;
    Proposal[] public proposals;

    modifier onlyChairperson() {
        require(msg.sender == chairperson, "Only chairperson can call this function");
        _;
    }

    constructor(bytes32[] memory proposalNames) {
        chairperson = msg.sender;
        for (uint256 i = 0; i < proposalNames.length; i++) {
            proposals.push(Proposal({name: proposalNames[i], voteCount: 0}));
        }
    }

    function giveRightToVote(address voter) public onlyChairperson {
        require(!voters[voter], "The voter already has the right to vote");
        voters[voter] = true;
    }

    function vote(uint256 proposal) public {
        require(voters[msg.sender], "You do not have the right to vote");
        require(proposal < proposals.length, "Invalid proposal");
        proposals[proposal].voteCount++;
    }

    function winningProposal() public view returns (uint256 winningProposal_) {
        uint256 winningVoteCount = 0;
        for (uint256 p = 0; p < proposals.length; p++) {
            if (proposals[p].voteCount > winningVoteCount) {
                winningVoteCount = proposals[p].voteCount;
                winningProposal_ = p;
            }
        }
    }
}

NFT Marketplace Contract

        
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract NFTMarket is ERC721URIStorage, Ownable {
    uint256 private _tokenIds;
    mapping(uint256 => uint256) private _tokenPrices;

    event TokenListed(uint256 tokenId, uint256 price);
    event TokenSold(uint256 tokenId, address buyer, uint256 price);

    constructor() ERC721("NFTMarket", "NFTM") {}

    function createToken(string memory tokenURI, uint256 price) public onlyOwner returns (uint256) {
        _tokenIds++;
        uint256 newItemId = _tokenIds;
        _mint(msg.sender, newItemId);
        _setTokenURI(newItemId, tokenURI);
        _tokenPrices[newItemId] = price;
        emit TokenListed(newItemId, price);
        return newItemId;
    }

    function purchaseToken(uint256 tokenId) public payable {
        require(_exists(tokenId), "Token does not exist");
        require(msg.value >= _tokenPrices[tokenId], "Insufficient funds");
        address seller = ownerOf(tokenId);
        _transfer(seller, msg.sender, tokenId);
        payable(seller).transfer(msg.value);
        emit TokenSold(tokenId, msg.sender, msg.value);
    }

    function setTokenPrice(uint256 tokenId, uint256 newPrice) public onlyOwner {
        require(_exists(tokenId), "Token does not exist");
        _tokenPrices[tokenId] = newPrice;
    }

    function getTokenPrice(uint256 tokenId) public view returns (uint256) {
        return _tokenPrices[tokenId];
    }
}

Decentralized Exchange (DEX)

A decentralized exchange (DEX) is a trading platform based on smart contracts where users can exchange assets directly on the chain.
Core Features
  • Order book: records users' buy and sell orders.
  • Matching engine: matches buy and sell orders and executes trades.
  • Asset custody: securely manage users' assets.

Sample Code


pragma solidity ^0.8.0;

contract DecentralizedExchange {
    struct Order {
        address trader;
        bool isBuyOrder;
        uint256 price;
        uint256 amount;
    }

    mapping(uint256 => Order) public orders;
    uint256 public orderCount;

    event OrderCreated(uint256 orderId, address trader, bool isBuyOrder, uint256 price, uint256 amount);
    event OrderFilled(uint256 orderId, address taker, uint256 filledAmount);

    function createOrder(bool isBuyOrder, uint256 price, uint256 amount) public {
        orderCount++;
        orders[orderCount] = Order(msg.sender, isBuyOrder, price, amount);
        emit OrderCreated(orderCount, msg.sender, isBuyOrder, price, amount);
    }

    function fillOrder(uint256 orderId, uint256 amount) public {
        Order storage order = orders[orderId];
        require(order.amount >= amount, "Insufficient order amount");
        order.amount -= amount;
        emit OrderFilled(orderId, msg.sender, amount);
    }
}

Decentralized lending platform

The decentralized lending platform allows users to lend and borrow cryptocurrencies, automating the lending process through smart contracts.
Core Features
  • Lending pool: manages users' lending funds.
  • Interest rate model: dynamically adjust lending rates.
  • Risk control: prevent default risk.
Sample Code
        
pragma solidity ^0.8.0;

contract LendingPlatform {
    struct Loan {
        address borrower;
        uint256 amount;
        uint256 interestRate;
        uint256 repaymentDate;
    }

    mapping(address => uint256) public balances;
    mapping(uint256 => Loan) public loans;
    uint256 public loanCount;

    event LoanCreated(uint256 loanId, address borrower, uint256 amount, uint256 interestRate, uint256 repaymentDate);
    event LoanRepaid(uint256 loanId, uint256 amount);

    function deposit(uint256 amount) public payable {
        require(msg.value == amount, "Deposit amount must match the sent Ether");
        balances[msg.sender] += amount;
    }

    function createLoan(uint256 amount, uint256 interestRate, uint256 repaymentPeriod) public {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        loanCount++;
        uint256 repaymentDate = block.timestamp + repaymentPeriod;
        loans[loanCount] = Loan(msg.sender, amount, interestRate, repaymentDate);
        balances[msg.sender] -= amount;
        emit LoanCreated(loanCount, msg.sender, amount, interestRate, repaymentDate);
    }

    function repayLoan(uint256 loanId) public payable {
        Loan storage loan = loans[loanId];
        require(loan.borrower == msg.sender, "Not the borrower");
        require(block.timestamp <= loan.repaymentDate, "Repayment period expired");
        uint256 totalAmount = loan.amount + (loan.amount * loan.interestRate / 100);
        require(msg.value == totalAmount, "Incorrect repayment amount");
        balances[msg.sender] += totalAmount;
        delete loans[loanId];
        emit LoanRepaid(loanId, totalAmount);
    }
}