Web3.js是以太坊的JavaScript API,它可以在瀏覽器和Node.js中使用。它是Ethereum的官方JavaScript庫,提供了一組API接口,可以與以太坊區塊鏈進行交互,包括訪問區塊鏈數據、交易以及部署合約等操作。在開發以太坊Dapp時,Web3.js是不可或缺的工具。
在開發以太坊Dapp時,需要使用Web3.js與區塊鏈進行交互。Web3.js提供了一組API,可以用于構造區塊鏈交易、發送交易、部署合約、讀取合約等操作。
首先,需要連接到以太坊網絡。Web3.js提供了幾種連接方法,可以連接到本地節點或以太坊公共網絡:
```javascript
// 連接以太坊節點
const Web3 = require('web3')
const web3 = new Web3('http://localhost:8545')
// 連接以太坊公共網絡
const web3 = new Web3('https://mainnet.infura.io/v3/
```
連接成功后,可以使用Web3.js的API操作以太坊區塊鏈。
訪問以太坊區塊鏈數據:
```javascript
// 獲取當前區塊號
web3.eth.getBlockNumber().then(console.log)
// 獲取指定區塊的詳細信息
web3.eth.getBlock(12345).then(console.log)
// 獲取指定地址的余額
web3.eth.getBalance('0x1234567890123456789012345678901234567890').then(console.log)
// 獲取指定交易的詳細信息
web3.eth.getTransaction('0x1234567890123456789012345678901234567890123456789012345678901234').then(console.log)
```
構造、發送交易:
```javascript
// 構造一筆轉賬交易,并簽名
const Tx = require('ethereumjs-tx').Transaction
const privateKey = Buffer.from('private_key', 'hex')
const nonce = await web3.eth.getTransactionCount('sender_address')
const gasPrice = await web3.eth.getGasPrice()
const gasLimit = 21000
const value = web3.utils.toWei('1', 'ether')
const data = ''
const txParams = {
nonce: web3.utils.toHex(nonce),
gasPrice: web3.utils.toHex(gasPrice),
gasLimit: web3.utils.toHex(gasLimit),
to: 'recipient_address',
value: web3.utils.toHex(value),
data: data
}
const tx = new Tx(txParams, { chain: 'mainnet', hardfork: 'petersburg' })
tx.sign(privateKey)
const serializedTx = tx.serialize()
// 發送交易
const receipt = await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
console.log(receipt)
```
部署合約:
```javascript
const solc = require('solc')
const fs = require('fs')
// 編譯合約
const contractCode = fs.readFileSync('contract.sol').toString()
const compiledCode = solc.compile(contractCode)
// 部署合約
const abi = JSON.parse(compiledCode.contracts[':Contract'].interface)
const bytecode = compiledCode.contracts[':Contract'].bytecode
const Contract = new web3.eth.Contract(abi)
const deployTx = Contract.deploy({ data: bytecode, arguments: [] })
const nonce = await web3.eth.getTransactionCount('sender_address')
const gasPrice = await web3.eth.getGasPrice()
const gasLimit = await deployTx.estimateGas()
const txParams = {
nonce: web3.utils.toHex(nonce),
gasPrice: web3.utils.toHex(gasPrice),
gasLimit: web3.utils.toHex(gasLimit),
from: 'sender_address',
data: deployTx.encodeABI()
}
const signedTx = await web3.eth.accounts.signTransaction(txParams, 'private_key')
const deployedContract = await web3.eth.sendSignedTransaction(signedTx.rawTransaction)
console.log(deployedContract.options.address)
```
讀取合約:
```javascript
const abi = JSON.parse(compiledCode.contracts[':Contract'].interface)
const address = 'deployed_contract_address'
const Contract = new web3.eth.Contract(abi, address)
const result = await Contract.methods.methodName(...args).call()
console.log(result)
```
以上是Web3.js的一些基本使用方法,可以用于構建簡單的以太坊Dapp。當然,Web3.js還有更強大的功能,例如連接太坊元數據API、eip-1193、通過WebSocket附加實時事件等。開發者可以根據項目需要選擇更多的功能。
總結:
Web3.js是以太坊Dapp開發不可或缺的工具之一,可以用于訪問以太坊區塊鏈、構建交易、部署合約、調用合約等操作。它提供了豐富的API接口,開發者可以根據項目需求選擇更多的API。