web3js


title: Web3js note date: '2024-01-31' tags: ['code'] draft: true

web3-eth-abi

web3-eth-accounts

web3-eth-Contract

//Uniswap token address in mainnet
const address = '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984'
//you can find the complete ABI in etherscan.io
const ABI = 
[
    {
    name: 'symbol',
    outputs: [{ type: 'string' }],
    type: 'function',
    },
    {
    name: 'totalSupply',
    outputs: [{ type: 'uint256' }],
    type: 'function',
    },
];

//instantiate the contract
const uniswapToken = new web3.eth.Contract(ABI, address);
console.log(`uniswapToken:`, uniswapToken);

web3-eth-ens

web3-eth-iban

web3-net

web3-eth-personal

web3-utils

Web3-eth

附加支援軟體包 Web3 Types:型別。該軟體包包含常用的型別指令碼型別。

Web3 Validator:驗證器。該軟體包提供使用所提供的模式進行驗證的功能。

Web3 Core:Web3 Core 具有其他 Web3 軟體包所使用的配置、訂閱和請求管理功能。

Web3 Errors:Web3 Errors 包含其他 Web3 軟體包使用的錯誤程式碼和常見錯誤類。

Web3 RPC 方法:這是用於構建更輕量級應用程式的高階用途。它具有使用給定提供程式向以太坊發出 RPC 請求的功能。

const web3 = new Web3(`https://opbnb-mainnet-rpc.bnbchain.org`);
// 獲取最後一個區塊編號
web3.eth.getBlockNumber().then(console.log);
// 獲取地址餘額
web3.eth.getBalance('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045').then(console.log);
// 獲取當前提供商的鏈ID
web3.eth.getChainId().then(console.log);
// get the nonce of an address
web3.eth.getTransactionCount('0x37826D8B5F4B175517A0f42c886f8Fca38C55Fe7').then(console.log);
// 獲取當前gas價
web3.eth.getGasPrice().then(console.log);

// 數字錢包:存放多個以太坊賬戶的陣列,管理賬戶集合並與之互動。用來儲存和組織各種以太坊地址。
const wallet = web3.eth.accounts.wallet.create(1); // 隨機建立一個錢包

// 新增私人金鑰以建立錢包 the private key must start with the '0x' prefix
const account = web3.eth.accounts.wallet.add('0x50d349f5cf627d44858d6fcb6fbf15d27457d35c58ba2d5cfeaf455f25db5bec');
console.log(account[0].address);// 0xcE6A5235d6033341972782a15289277E85E5b305
console.log(account[0].privateKey);

const tx =
{
    from: account[0].address, // 地址必須與之前透過 wallet.add 新增的地址一致
    to: '0xa3286628134bad128faeef82f44e99aa64085c94',
    value: web3.utils.toWei('1', 'ether')
};
send the transaction
async function demo() {
    const txReceipt = await web3.eth.sendTransaction(tx);
    console.log('Tx hash:', txReceipt.transactionHash)
}