Web3.js是以太坊的JavaScript API,它可以在瀏覽器和Node.js中使用。它是Ethereum的官方JavaScript庫(kù),提供了一組API接口,可以與以太坊區(qū)塊鏈進(jìn)行交互,包括訪問區(qū)塊鏈數(shù)據(jù)、交易以及部署合約等操作。在開發(fā)以太坊Dapp時(shí),Web3.js是不可或缺的工具。
在開發(fā)以太坊Dapp時(shí),需要使用Web3.js與區(qū)塊鏈進(jìn)行交互。Web3.js提供了一組API,可以用于構(gòu)造區(qū)塊鏈交易、發(fā)送交易、部署合約、讀取合約等操作。
首先,需要連接到以太坊網(wǎng)絡(luò)。Web3.js提供了幾種連接方法,可以連接到本地節(jié)點(diǎn)或以太坊公共網(wǎng)絡(luò):
```javascript
// 連接以太坊節(jié)點(diǎn)
const Web3 = require('web3')
const web3 = new Web3('http://localhost:8545')
// 連接以太坊公共網(wǎng)絡(luò)
const web3 = new Web3('https://mainnet.infura.io/v3/
```
連接成功后,可以使用Web3.js的API操作以太坊區(qū)塊鏈。
訪問以太坊區(qū)塊鏈數(shù)據(jù):
```javascript
// 獲取當(dāng)前區(qū)塊號(hào)
web3.eth.getBlockNumber().then(console.log)
// 獲取指定區(qū)塊的詳細(xì)信息
web3.eth.getBlock(12345).then(console.log)
// 獲取指定地址的余額
web3.eth.getBalance('0x1234567890123456789012345678901234567890').then(console.log)
// 獲取指定交易的詳細(xì)信息
web3.eth.getTransaction('0x1234567890123456789012345678901234567890123456789012345678901234').then(console.log)
```
構(gòu)造、發(fā)送交易:
```javascript
// 構(gòu)造一筆轉(zhuǎn)賬交易,并簽名
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()
// 發(fā)送交易
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的一些基本使用方法,可以用于構(gòu)建簡(jiǎn)單的以太坊Dapp。當(dāng)然,Web3.js還有更強(qiáng)大的功能,例如連接太坊元數(shù)據(jù)API、eip-1193、通過WebSocket附加實(shí)時(shí)事件等。開發(fā)者可以根據(jù)項(xiàng)目需要選擇更多的功能。
總結(jié):
Web3.js是以太坊Dapp開發(fā)不可或缺的工具之一,可以用于訪問以太坊區(qū)塊鏈、構(gòu)建交易、部署合約、調(diào)用合約等操作。它提供了豐富的API接口,開發(fā)者可以根據(jù)項(xiàng)目需求選擇更多的API。