Getting Ethers

Phiên bản của Ethers trong các ví dụ bên dưới là 5.x.

Cài đặt như sau:

yarn add ethers@5.4.7

Import:

import { ethers } from "ethers";

Connecting to the Network

Kết nối đến các JSON-RPC based provider như sau:

const provider = new ethers.providers.JsonRpcProvider('http://localhost:7545');
 
const signer = provider.getSigner();

Với đối số truyền vào JsonRpcProvider là địa chỉ của mạng cần kết nối.

Querying the Blockchain

Sau khi kết nối đến provider thì ta có thể thực hiện truy vấn thông tin.

Ví dụ:

async function query(){
    // Look up the current block number
    const blockNumber = await provider.getBlockNumber()
    console.log('Current block number: ', blockNumber)
    // Current block number:  22
 
    // Get the balance of an account (by address or ENS name, if supported by network)
    const balance = await provider.getBalance("0xF54aFBE31a6e78ED2Cd73ca1C78B12DD3473E44d")
    console.log('Balance: ', balance)
    // Balance:  BigNumber { _hex: '0x05794be12e660da1b8', _isBigNumber: true }
 
    // Often you need to format the output to something more user-friendly, such as in ether (instead of wei)
    const formattedBalance = ethers.utils.formatEther(balance)
    console.log('Formatted balance: ', formattedBalance)
    // Formatted balance:  100.974047459787252152
 
    // If a user enters a string in an input field, you may need
    // to convert it from ether (as a string) to wei (as a BigNumber)
    const wei = ethers.utils.parseEther("1.0")
    console.log('Wei: ', wei)
    // Wei:  BigNumber { _hex: '0x0de0b6b3a7640000', _isBigNumber: true }
}
query();

Writing to the Blockchain

Để ghi dữ liệu (thực hiện giao dịch), ta cần dùng đến biến signer như sau:

async function write(){
    // Send 1 ether to an address.
    const tx = await signer.sendTransaction({
        to: "0xeda19141fdDEb5355e034161e5e61DD9730E799c",
        value: ethers.utils.parseEther("1.0")
    });
}
write();