首页 > App

web3

2024-02-04 浏览: 41

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。

标签: web3