Tìm hiểu

Hướng dẫn phát triển Smart Contract Solidity cơ bản

Hướng dẫn thực hành Solidity dành cho nhà phát triển muốn đi từ kiến thức nền tảng đến các mẫu phổ biến, kiểm thử và ứng dụng hợp đồng thông minh trong thực tế.

SolidityCú pháp cốt lõi, cấu trúc và quy trình làm việc cơ bản
Thực hànhMẫu mã bao gồm hợp đồng, thử nghiệm và bảo mật

Giới thiệu về Solidity

Solidity là gì?

Solidity là ngôn ngữ lập trình hướng đối tượng cấp cao được thiết kế đặc biệt để viết smart contract. Smart contract là các chương trình được thực thi tự động trên blockchain và có thể được sử dụng để triển khai các ứng dụng phi tập trung (DApps) khác nhau.

Lịch sử của Solidity

Solidity được tạo ra vào năm 2014 bởi các thành viên của Ethereum Foundation để cung cấp một ngôn ngữ lập trình dễ sử dụng cho blockchain Ethereum. Kể từ đó, Solidity đã liên tục phát triển và trở thành một trong những ngôn ngữ lập trình smart contract phổ biến nhất.

Cài đặt trình biên dịch Solidity

Có nhiều cách để cài đặt trình biên dịch Solidity. Dưới đây là một số phương pháp phổ biến:
Sử dụng trình quản lý gói Node.js npm:

npm install -g solc

            
Sử dụng Docker:

docker pull ethereum/solc:stable

            
Trình biên dịch trực tuyến:
Remix IDE: https://remix.ethereum.org/

Cú pháp cơ bản Solidity

Biến và kiểu dữ liệu

Solidity hỗ trợ nhiều kiểu dữ liệu, bao gồm các kiểu nguyên thủy và kiểu phức tạp.
  • Kiểu cơ bản
  • Boolean:bool
  • Số nguyên: int,uint
  • Kiểu địa chỉ:address
  • Chuỗi:string
  • Kiểu byte:bytes
  • Kiểu phức tạp
    • Mảng: uint[],uint[5]
    • Ánh xạ:mapping(address => uint)
    • Cấu trúc:struct Person { string name; uint age; }

Hàm

Hàm là các khối xây dựng cơ bản trong Solidity và được sử dụng để định nghĩa hành vi của contract.
        
pragma solidity ^0.8.0;

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

Cấu trúc điều khiển

Solidity hỗ trợ các cấu trúc điều khiển phổ biến như điều kiện và vòng lặp.
Câu lệnh điều kiện
        
function checkAge(uint age) public pure returns (string memory) {
    if (age < 18) {
        return "Underage";
    } else {
        return "Adult";
    }
}

Câu lệnh vòng lặp
        
function sum(uint n) public pure returns (uint) {
    uint result = 0;
    for (uint i = 1; i <= n; i++) {
        result += i;
    }
    return result;
}

Sự kiện

Sự kiện được sử dụng để ghi lại các hoạt động quan trọng của contract, và các sự kiện này có thể được lắng nghe trong ứng dụng front-end.
        
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);
}

Xử lý lỗi

Solidity cung cấp nhiều cơ chế xử lý lỗi như require, assert and revert.
        
function divide(uint a, uint b) public pure returns (uint) {
    require(b != 0, "Divisor cannot be zero");
    return a / b;
}

Cơ bản về Smart Contract

Khái niệm smart contract

Smart contract là hợp đồng tự thực thi với các điều khoản được viết trực tiếp vào code. Trên blockchain, smart contract có thể được sử dụng để triển khai các ứng dụng phi tập trung khác nhau.

Tạo smart contract đầu tiên

        
pragma solidity ^0.8.0;

contract HelloWorld {
    string public message;

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

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

Biến trạng thái contract

Biến trạng thái là các biến được lưu trữ trên blockchain và được sử dụng để lưu thông tin trạng thái của contract.
        
contract Storage {
    uint256 public storedData;

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

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

Modifier hàm

Modifier hàm được sử dụng để sửa đổi hành vi của hàm. Các modifier phổ biến bao gồm 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

Constructor được thực thi khi contract được triển khai và được sử dụng để khởi tạo trạng thái của contract.
 
contract ConstructorExample {
    uint256 public initialValue;

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

Tính năng nâng cao

Kế thừa

Kế thừa cho phép một contract kế thừa chức năng của contract khác.
        
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

Interface định nghĩa một tập hợp các chữ ký phương thức nhưng không bao gồm triển khai.
        
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;
    }
}

Thư viện

Thư viện được sử dụng để định nghĩa một tập hợp các hàm có thể tái sử dụng.
        
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);
    }
}

Gọi nội bộ và bên ngoài

Gọi nội bộ và gọi bên ngoài được sử dụng để gọi các hàm trong cùng một contract và các hàm của các contract khác nhau tương ứng.
        
contract InternalExternalCalls {
    uint256 public value;

    function internalCall() internal {
        value = 100;
    }

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

Tối ưu hóa Gas

Gas là phí cần thiết để thực thi các hoạt động smart contract trong mạng Ethereum. Tối ưu hóa tiêu thụ Gas có thể giảm chi phí giao dịch và cải thiện hiệu quả contract.
Các kỹ thuật tối ưu hóa Gas phổ biến
  • Giảm đọc ghi lưu trữ: Giảm thiểu các hoạt động đọc và ghi vào biến trạng thái.
  • Hoạt động hàng loạt: kết hợp nhiều hoạt động thành một giao dịch.
  • Sử dụng biến memory: Sử dụng biến memory bên trong hàm thay vì biến trạng thái.
  • Tránh vòng lặp: Cố gắng tránh sử dụng vòng lặp trong contract của bạn, đặc biệt khi liên quan đến lượng lớn dữ liệu.
Ví dụ: Tối ưu hóa đọc ghi lưu trữ
        
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;
    }
}

Sự kiện và Log

Sự kiện và log được sử dụng để ghi lại các hoạt động quan trọng của contract, và các sự kiện này có thể được giám sát trong ứng dụng front-end.
Ví dụ: Sử dụng sự kiện để ghi lại chuyển khoản
        
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);
    }
}

Kiểm thử tự động

Kiểm thử tự động là bước quan trọng để đảm bảo tính đúng đắn của smart contract. Các công cụ như Truffle và Mocha có thể được sử dụng để dễ dàng viết và chạy các test case.
Ví dụ: Viết 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");
    });
});

Các mẫu thiết kế phổ biến

  • Mẫu Proxy: được sử dụng để nâng cấp smart contract.
  • Mẫu Factory: được sử dụng để tạo nhiều instance contract.
  • Mẫu kiểm soát truy cập: được sử dụng để hạn chế quyền truy cập vào contract.

Bảo mật và best practice

Các lỗ hổng bảo mật phổ biến

  • Tấn công reentrancy: Đánh cắp tiền bằng cách gọi các hàm contract nhiều lần.
  • Tràn số và thiếu số: Lỗi do các phép tính số.
  • Phụ thuộc timestamp: Phụ thuộc vào timestamp của block để ra quyết định.

Công cụ kiểm toán bảo mật

  • MythX: Công cụ kiểm toán bảo mật smart contract chuyên nghiệp.
  • Slither: Công cụ phân tích bảo mật smart contract mã nguồn mở.
  • Echidna: Công cụ kiểm toán bảo mật dựa trên fuzz testing.

Viết smart contract an toàn

  • Sử dụng phiên bản Solidity mới nhất.
  • Tránh sử dụng các cuộc gọi cấp thấp.
  • Sử dụng thư viện OpenZeppelin.

Ứng dụng Contract

Contract token ERC20 đơn giản

        
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);
    }
}

Hệ thống bỏ phiếu phi tập trung

        
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;
            }
        }
    }
}

Contract NFT Marketplace

        
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];
    }
}

Sàn giao dịch phi tập trung (DEX)

Sàn giao dịch phi tập trung (DEX) là nền tảng giao dịch dựa trên smart contract nơi người dùng có thể trao đổi tài sản trực tiếp trên chuỗi.
Tính năng cốt lõi
  • Sổ lệnh: ghi lại các lệnh mua và bán của người dùng.
  • Công cụ khớp lệnh: khớp các lệnh mua và bán và thực hiện giao dịch.
  • Lưu ký tài sản: quản lý an toàn tài sản của người dùng.

Code mẫu


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);
    }
}

Nền tảng cho vay phi tập trung

Nền tảng cho vay phi tập trung cho phép người dùng cho vay và vay tiền mã hóa, tự động hóa quy trình cho vay thông qua smart contract.
Tính năng cốt lõi
  • Pool cho vay: quản lý quỹ cho vay của người dùng.
  • Mô hình lãi suất: điều chỉnh động tỷ lệ cho vay.
  • Kiểm soát rủi ro: ngăn chặn rủi ro vỡ nợ.
Code mẫu
        
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);
    }
}