进阶 docs.web3js.org 2026-10-19 02:32:30 · 11 阅读

第14章 Web3 Eth 模块快速上手

快速上手 eth 包

简介

web3-eth 包提供了一组强大的功能,用于与以太坊区块链及智能合约进行交互。本教程将指导你掌握 web3.js 4.0 版本中 web3-eth 包的基础用法。示例代码将统一使用 TypeScript。

概述

以下是本教程的主要步骤概要:

  • 搭建环境
  • 创建新项目目录并初始化新的 Node.js 项目
  • 配置 web3.js 并连接 Ganache 网络
  • 使用 web3.js 与以太坊区块链交互
  • 导入特定包
  • 发送不同类型的交易

第 1 步:搭建环境

在编写和部署合约之前,我们需要先搭建好开发环境。为此,需要安装以下工具:

提示:你也可以使用 Alchemy、Infura、QuickNode 或从 Chainlist 获取公共端点来代替 Ganache,直接与主网/测试网进行交互。
  • Ganache - Ganache 是用于以太坊开发的个人区块链,可帮助你验证智能合约在真实场景中的表现。下载地址:http://truffleframework.com/ganache
  • Node.js - Node.js 是 JavaScript 运行时环境,允许在服务器端运行 JavaScript 代码。下载地址:https://nodejs.org/en/download/
  • npm - Node Package Manager 用于从公共 npm 仓库或私有 npm 仓库发布和安装包。安装指南:https://docs.npmjs.com/downloading-and-installing-node-js-and-npm(也可以改用 yarn 代替 npm,参考:https://classic.yarnpkg.com/lang/en/docs/getting-started/)

第 2 步:创建项目目录并初始化 Node.js 项目

首先,为项目创建一个新的目录并进入该目录:

mkdir web3-eth-tutorial
cd web3-eth-tutorial

接下来,使用 npm 初始化一个新的 Node.js 项目:

npm init -y

此命令将在项目目录中生成 package.json 文件。

npm i typescript @types/node

此命令将为项目安装 typescript 及 node 的类型定义。

第 3 步:配置 web3.js 并连接 Ganache 网络

在这一步中,我们将配置 web3.js 库并连接到 Ganache 网络。如果尚未启动 Ganache,请确保先运行它。

首先,使用 npm 安装 web3 包:

npm i web3
接下来,在项目目录下新建一个名为 index.ts 的文件,并添加以下代码: import { Web3 } from 'web3';

// 建立到 Ganache 网络的连接
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
/* 注意:
除了使用 Ganache,你还可以通过其他提供商与测试网/主网交互
https://app.infura.io/
https://dashboard.alchemy.com/
或使用公共提供商 https://chainlist.org/
*/

// 将当前区块编号输出到控制台
const block = await web3.eth.getBlockNumber();

console.log('最后区块:', block);
// ↳ 最后区块:4975299n
这段代码建立了与 Ganache 网络的连接,并将当前区块编号打印到控制台。 运行以下命令以测试连接: npx ts-node index.ts
如果一切正常,你应该能在控制台看到当前的区块编号。但如果你遇到 connect ECONNREFUSED 127.0.0.1:7545 错误,请仔细检查是否已在本地 7545 端口上运行 Ganache。 步骤 4:使用 web3.js 与以太坊区块链交互​ 在这一步中,我们将使用 web3.js 与 Ganache 网络进行交互。 在第一个示例中,我们将发送一个简单的价值交易。 创建一个名为 transaction.ts 的文件,并填入以下代码: import { Web3 } from 'web3';
import fs from 'fs';
import path from 'path';

// 建立到以太坊网络的连接
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));
web3.eth.Contract.handleRevert = true;

async function interact() {
//获取所有可用账户
const accounts = await web3.eth.getAccounts();
console.log(accounts);

let balance1, balance2;
//账户的初始余额应为 100 Eth(10^18 wei)
balance1 = await web3.eth.getBalance(accounts[0]);
balance2 = await web3.eth.getBalance(accounts[1]);

console.log(balance1, balance2);

//创建一个从账户 0 向账户 1 发送 1 Ether 的交易
const transaction = {
from: accounts[0],
to: accounts[1],
// value 应以 wei 为单位传入。为了方便使用并避免错误,
// 我们利用辅助函数 `toWei`:
value: web3.utils.toWei('1', 'ether'),
};

//发送实际的交易
const transactionHash = await web3.eth.sendTransaction(transaction);
console.log('transactionHash', transactionHash);

balance1 = await web3.eth.getBalance(accounts[0]);
balance2 = await web3.eth.getBalance(accounts[1]);

// 查看更新后的余额
console.log(balance1, balance2);

// 这与实际交易无关,只是想看看 gasPrice
const gasPrice = await web3.eth.getGasPrice();
console.log(gasPrice);
}

(async () => {
await interact();
})();
important📝 使用 Ganache 运行本地开发区块链时,所有账户默认都是解锁状态,方便在开发和测试中直接访问账户并执行交易。也就是说,访问这些账户不需要私钥或密码。这就是为什么示例中只需在 from 字段里指定账户即可。 运行以下命令: npx ts-node transaction.ts
如果一切正常,你会看到类似下面的输出: [
'0xc68863f36C48ec168AD45A86c96347D520eac1Cf',
'0x80c05939B307f9833d905A685575b45659d3EA70',
'0xA260Cf742e03B48ea1A2b76b0d20aaCfe6F85E5E',
'0xf457b8C0CBE41e2a85b6222A97b7b7bC6Df1C0c0',
'0x32dF9a0B365b6265Fb21893c551b0766084DDE21',
'0x8a6A2b8b00C1C8135F1B25DcE54f73Ee18bEF43d',
'0xAFc526Be4a2656f7E02501bdf660AbbaA8fb3d7A',
'0xc32618116370fF776Ecd18301c801e146A1746b3',
'0xDCCD49880dCf9603835B0f522c31Fcf0579b46Ff',
'0x036006084Cb62b7FAf40B979868c0c03672a59B5'
]
100000000000000000000n 100000000000000000000n

transactionHash {
transactionHash: '0xf685b64ccf5930d3779a33335ca22195b68901dbdc439f79dfc65d87c7ae88b0',
transactionIndex: 0n,
blockHash: '0x5bc044ad949cfd32ea4cbb249f0292e7dded44c3b0f599236c6d20ddaa96cc06',
blockNumber: 1n,
from: '0xc68863f36c48ec168ad45a86c96347d520eac1cf',
to: '0x80c05939b307f9833d905a685575b45659d3ea70',
gasUsed: 21000n,
cumulativeGasUsed: 21000n,
logs: [],
status: 1n,
logsBloom: '0x......000'
}

98999580000000000000n 101000000000000000000n

20000000000n

📝 要计算实际消耗的以太币,需将发送的转账金额与手续费相加。初始余额 = 剩余余额 + 转账金额 + gasUsed * gasPrice。本例中:98999580000000000000 + 1000000000000000000 + (20000000000*21000) = 100 Ether。 接下来的示例中,我们将使用 estimateGas 函数来估算部署合约所需的预期 Gas 消耗。(关于合约的更多细节,请参阅对应的教程)。创建一个名为 estimate.ts 的文件,并填入以下代码: import { Web3, ETH_DATA_FORMAT, DEFAULT_RETURN_FORMAT } from 'web3';

async function estimate() {
// 合约的 abi
const abi = [
{
inputs: [{ internalType: 'uint256', name: '_myNumber', type: 'uint256' }],
stateMutability: 'nonpayable',
type: 'constructor',
},
{
inputs: [],
name: 'myNumber',
outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],
stateMutability: 'view',
type: 'function',
},
{
inputs: [{ internalType: 'uint256', name: '_myNumber', type: 'uint256' }],
name: 'setMyNumber',
outputs: [],
stateMutability: 'nonpayable',
type: 'function',
},
];

const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:7545'));

// 获取可用账户
const accounts = await web3.eth.getAccounts();
let acc = await accounts[0];

let contract = new web3.eth.Contract(abi);

const deployment = contract.deploy({
data: '0x608060405234801561001057600080fd5b506040516101d93803806101d983398181016040528101906100329190610054565b806000819055505061009e565b60008151905061004e81610087565b92915050565b60006020828403121561006657600080fd5b60006100748482850161003f565b91505092915050565b6000819050919050565b6100908161007d565b811461009b57600080fd5b50565b61012c806100ad6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c806323fd0e401460375780636ffd773c146051575b600080fd5b603d6069565b6040516048919060bf565b60405180910390f35b6067600480360381019060639190608c565b606f565b005b60005481565b8060008190555050565b60008135905060868160e2565b92915050565b600060208284031215609d57600080fd5b600060a9848285016079565b91505092915050565b60b98160d8565b82525050565b600060208201905060d2600083018460b2565b92915050565b6000819050919050565b60e98160d8565b811460f357600080fd5b5056fea2646970667358221220d28cf161457f7936995800eb9896635a02a559a0561bff6a09a40bfb81cd056564736f6c63430008000033',
// @ts-expect-error
arguments: [1],
});

let estimatedGas = await deployment.estimateGas({ from: acc }, DEFAULT_RETURN_FORMAT);
// 返回的数据将以 bigint 格式呈现

console.log('Default format:', estimatedGas);

estimatedGas = await deployment.estimateGas({ from: acc }, ETH_DATA_FORMAT);
// 返回的数据将以十六进制字符串格式呈现

console.log('Eth format:', estimatedGas);
}

(async () => {
await estimate();
})();
运行以下命令: npx ts-node estimate.ts
如果一切正常,你应该看到类似以下的输出: Default format: 140648n
Eth format: 0x22568
📝 注意,web3.js 返回的数字默认采用 BigInt 格式。在此示例中,我们使用了 ETH_DATA_FORMAT 参数。大多数 web3.js 方法都接受该参数,用于将结果格式化为十六进制。 在下一个示例中,我们将签署交易并使用 sendSignedTransaction 来发送该已签署的交易。创建一个名为 sendSigned.ts 的文件,并填入以下代码: import { Web3 } from 'web3';
const web3 = new Web3('http://localhost:7545');

// 请确保从 ganache 复制私钥
const privateKey = '0x0fed6f64e01bc9fac9587b6e7245fd9d056c3c004ad546a17d3d029977f0930a';
const value = web3.utils.toWei('1', 'ether');

async function sendSigned() {
const accounts = await web3.eth.getAccounts();
const fromAddress = accounts[0];
const toAddress = accounts[1];
// 创建一个新的交易对象
const tx = {
from: fromAddress,
to: toAddress,
value: value,
gas: 21000,
gasPrice: web3.utils.toWei('10', 'gwei'),
nonce: await web3.eth.getTransactionCount(fromAddress),
};

// 使用私钥签署交易
const signedTx = await web3.eth.accounts.signTransaction(tx, privateKey);

// 将签署好的交易发送到网络
const receipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);

console.log('Transaction receipt:', receipt);
}
(async () => {
await sendSigned();
})();
运行以下命令: npx ts-node sendSigned.ts
如果一切正常,你应该看到类似以下的输出: Transaction receipt: {
transactionHash: '0x742df8f1ad4d04f6e5632889109506dbb7cdc8a6a1c80af3dfdfc71a67a04ddc',
transactionIndex: 0n,
blockNumber: 1n,
blockHash: '0xab6678d76499b0ee383f182ab8f848ba27bd787e70e227524255c86b25224ed3',
from: '0x66ce32a5200aac57b258c4eac26bc1493fefddea',
to: '0x0afcfc43ac454348d8170c77b1f912b518b4ebe8',
cumulativeGasUsed: 21000n,
gasUsed: 21000n,
logs: [],
logsBloom: '0x...0000',
status: 1n,
effectiveGasPrice: 10000000000n,
type: 2n
}
第5步:导入特定的包​ 如果想使用 web3-eth 包的功能,可以直接导入这个包,而不必依赖全局的 web3 包,这样能减小构建体积。 直接导入 web3-eth​ 例如 getBalance 方法: import { Web3Eth } from 'web3-eth';

const eth = new Web3Eth('http://localhost:7545');

async function test() {
const accounts = await eth.getAccounts();
const currentBalance = await eth.getBalance(accounts[0]);
console.log('Current balance:', currentBalance);
// 115792089237316195423570985008687907853269984665640564039437613106102441895127n
}

(async () => {
await test();
})();
直接为 web3-eth 包设置配置​ import { Web3Eth } from 'web3-eth';

const eth = new Web3Eth('http://localhost:8545');

console.log('defaultTransactionType before', eth.config.defaultTransactionType);
// defaultTransactionType before 0x0

eth.setConfig({ defaultTransactionType: '0x1' });

console.log('eth.config.defaultTransactionType after', eth.config.defaultTransactionType);
// defaultTransactionType before 0x1
第6步:发送不同类型的交易: 传统交易 在以太坊中,“传统交易”通常指早期那种由发送者手动设定燃气费(gas fee)、且费用会随网络需求波动的交易形式。此类交易在以太坊改进提案(EIP)1559实施之前一直是网络上的主流。 传统交易的主要特点包括: 燃气价格:在传统交易中,发送者需指定愿意为每个燃气单位支付的燃气价格(以 Gwei 为单位)。该价格可由发送者调整,直接决定了交易被矿工处理的优先级;价格越高,确认速度越快。 燃气上限:发送者还需设定燃气上限,即交易最多可消耗的燃气量。燃气是执行以太坊交易和智能合约所消耗的计算资源,设置上限主要是为了防止发送者在交易处理过程中耗尽以太币;同时,这一参数也可能影响交易能否成功。 费用不确定性:传统交易的费用受网络拥堵程度影响,燃气价格随之波动。在网络高峰期,价格飙升,用户需支付更高费用才能快速处理交易;而在网络平稳期,用户则可享受较低费率。 手动估算费用:用户须自行估算合理的燃气价格并填入交易,以确保及时处理。这一过程颇具挑战:价格定得过低会导致确认缓慢,定得过高则造成多付费用。 下文介绍的 EIP-1559 对以太坊交易费用体系进行了改革,使其对用户更友好、更可预测。在 EIP-1559 框架下,“基础费用”(base fee)取代了手动设定燃气价格的方式,有效降低了传统交易中常见的不确定性。 尽管 EIP-1559 显著改善了用户体验,但以太坊网络仍支持传统交易,用户如愿意,仍可发送手动指定燃气价格和上限的交易。不过,对于大多数交易,目前推荐使用 EIP-1559 机制,因为它简化了操作流程,并降低了多付费用的风险。 发送传统交易的代码如下: import { Web3 } from 'web3';

const web3 = new Web3('http://localhost:8545');

async function test() {
const privateKey = 'YOUR PRIVATE KEY HERE';
// 将私钥添加到钱包,以便启用交易自动签名功能
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);

// 创建交易对象
const tx = {
from: account.address,
to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab',
value: '0x1',
gas: BigInt(21000),
gasPrice: await web3.eth.getGasPrice(),
type: BigInt(0), // <- 指定交易类型
};

// 发送交易
const receipt = await web3.eth.sendTransaction(tx);

console.log('Receipt:', receipt);
// 返回的交易回执示例:
// {
// blockHash: '0xc0f2fea359233b0843fb53255b8a7f42aa7b1aff53da7cbe78c45b5bac187ad4',
// blockNumber: 21n,
// cumulativeGasUsed: 21000n,
// effectiveGasPrice: 2569891347n,
// from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e',
// gasUsed: 21000n,
// logs: [],
// logsBloom: '0x0...00000',
// status: 1n,
// to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab',
// transactionHash: '0x0ffe880776f5631e4b64caf521bd01cd816dd2cc29e533bc56f392211856cf9a',
// transactionIndex: 0n,
// type: 0n
// }
}
(async () => {
await test();
})();
EIP-2930 交易 EIP-2930(Ethereum Improvement Proposal 2930)是对以太坊网络的一项改进提案,随 2021 年 4 月激活的 Berlin 硬分叉一并上线。它引入了名为"Transaction Type and Access List(交易类型与访问列表)"的新特性,能提升某些智能合约交互的 gas 效率,并在指定谁可以访问合约内特定资源方面提供了更大的灵活性。EIP-2930 的核心内容包括: 交易类型:EIP-2930 引入了一种新交易类型——"Access List Transaction(访问列表交易)"。发送方可以在交易中声明一个将被访问或修改的地址列表,从而使部分智能合约交互更加高效。 访问列表(Access List):访问列表是随交易一起提交的结构化数据,包含交易执行过程中预期会被访问或修改的地址和存储键(storage key)列表。矿工可以据此优化执行,从而降低这些操作所需的 gas。 节省 gas:EIP-2930 旨在显著降低使用访问列表功能的交易 gas 成本。通过预先声明交易相关的存储槽和地址,gas 的使用效率更高,在状态庞大的智能合约交互场景中尤为明显。 合约交互:在与状态结构复杂的合约交互时,这一改进特别有用,因为它能减少读写特定存储槽所需的 gas,既帮用户省钱,也让某些交互变得更切实可行。 EIP-2930 是以太坊持续提升网络效率、降低交易成本努力的一部分,让去中心化应用和用户用起来更经济、扩展性更好。对于依赖特定存储操作和访问控制机制的有状态合约交互,它的收益尤其显著。 发送 EIP-2930 交易可使用以下代码: import { Web3 } from 'web3';

const web3 = new Web3('http://localhost:8545');

async function test() {
const privateKey = 'YOUR PRIVATE KEY HERE';
// add private key to wallet to have auto-signing transactions feature
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);

// 创建交易对象
const tx = {
from: account.address,
to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab',
value: '0x1',
gasLimit: BigInt(21000),
type: BigInt(1), // <- 指定类型
// gasPrice - 你可以直接指定该属性,否则 web3js 会自动填充此字段
};

// 发送交易
const receipt = await web3.eth.sendTransaction(tx);

console.log('Receipt:', receipt);
// Receipt: {
// blockHash: '0xd8f6a3638112d17b476fd1b7c4369d473bc1a484408b6f39dbf64410df44adf6',
// blockNumber: 24n,
// cumulativeGasUsed: 21000n,
// effectiveGasPrice: 2546893579n,
// from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e',
// gasUsed: 21000n,
// logs: [],
// logsBloom: '0x...0000',
// status: 1n,
// to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab',
// transactionHash: '0xd1d682b6f6467897db5b8f0a99a6be2fb788d32fbc1329b568b8f6b2c15e809a',
// transactionIndex: 0n,
// type: 1n
// }
}
(async () => {
await test();
})();
这里展示了如何在交易中使用访问列表(Access List)。 注:Greeter 合约的代码可以在此处找到 import { Web3 } from 'web3';

import { GreeterAbi, GreeterBytecode } from './fixture/Greeter';

const web3 = new Web3('http://localhost:8545');

async function test() {
const privateKey = 'YOUR PRIVATE KEY HERE';
// 将私钥添加到钱包以启用自动签名交易功能
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);

// 部署合约
const contract = new web3.eth.Contract(GreeterAbi);
const deployedContract = await contract
.deploy({
data: GreeterBytecode,
arguments: ['My Greeting'],
})
.send({ from: account.address });
deployedContract.defaultAccount = account.address;

const transaction = {
from: account.address,
to: deployedContract.options.address,
data: '0xcfae3217', // greet 函数的调用数据编码
};
const { accessList } = await web3.eth.createAccessList(transaction, 'latest');

console.log('AccessList:', accessList);
// AccessList: [
// {
// address: '0xce1f86f87bd3b8f32f0fb432f88e848f3a957ed7',
// storageKeys: [
// '0x0000000000000000000000000000000000000000000000000000000000000001'
// ]
// }
// ]

// 创建带 accessList 的交易对象
const tx = {
from: account.address,
to: deployedContract.options.address,
gasLimit: BigInt(46000),
type: BigInt(1), // <- 指定交易类型
accessList,
data: '0xcfae3217',
// gasPrice - 你可以直接指定此属性,或者由 web3js 自动填充该字段
};

// 发送交易
const receipt = await web3.eth.sendTransaction(tx);

console.log('回执:', receipt);
// 回执:{
// blockHash: '0xc7b9561100c8ff6f1cde7a05916e86b7d037b2fdba86b0870e842d1814046e4b',
// blockNumber: 43n,
// cumulativeGasUsed: 26795n,
// effectiveGasPrice: 2504325716n,
// from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e',
// gasUsed: 26795n,
// logs: [],
// logsBloom: '0x...00000000000',
// status: 1n,
// to: '0xce1f86f87bd3b8f32f0fb432f88e848f3a957ed7',
// transactionHash: '0xa49753be1e2bd22c2a8e2530726614c808838bb0ebbed72809bbcb34f178799a',
// transactionIndex: 0n,
// type: 1n
// }
}
(async () => {
await test();
})();
EIP-1559 交易 EIP-1559(Ethereum Improvement Proposal 1559)是以太坊网络手续费市场和交易定价机制的一次重大升级,于 2021 年 8 月随伦敦硬分叉上线。它改变了以太坊区块链上交易费用的运作方式,主要目标是提升用户体验和网络效率。 EIP-1559 引入的关键特性如下: Base Fee(基础费用):EIP-1559 引入了"基础费用"的概念。基础费用是交易被打包进区块所需的最低费用,由网络通过算法确定,并根据网络拥堵程度动态调整:网络繁忙时基础费用上升,空闲时则下降。 Inclusion Fee(打包小费):除了基础费用外,用户可以自愿附加一笔"小费"来激励矿工优先打包自己的交易,从而加快交易确认速度。 费用可预测:有了 EIP-1559,用户可以更准确地估算交易费用。他们只需设定愿意支付的最高费用(包含基础费用和小费),无需再去猜测合适的 gas 价格。 销毁机制:EIP-1559 会将基础费用从流通中"销毁",从而减少 ETH 的总供应量。这一通缩机制有助于缓解 ETH 供应持续增长的担忧,并可能使其成为更好的价值储存手段。 更高效的费用拍卖:在 EIP-1559 下,费用拍卖更有效率。用户设定愿意支付的最高费用,协议会自动调整小费,确保交易及时被打包,同时避免支付过高费用。 交易流程更简单:用户无需手动设置 gas 价格,只需指定愿意支付的最高费用,剩下的交给钱包软件处理即可,交易流程大大简化。 EIP-1559 因有望打造更友好、更高效的交易费用体系而广受好评,让以太坊网络对用户来说更易用、更可预测。它也被视为迈向 Ethereum 2.0 过程中的重要一步,有助于解决网络的可扩展性和可持续性难题。 发送 EIP-1559 交易的代码如下: import { Web3 } from 'web3';

const web3 = new Web3('http://localhost:8545');

async function test() {
const privateKey = 'YOUR PRIVATE KEY HERE';
// 将私钥加入钱包以启用自动签名交易功能
const account = web3.eth.accounts.privateKeyToAccount(privateKey);
web3.eth.accounts.wallet.add(account);

// 创建交易对象
const tx = {
from: account.address,
to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab',
value: '0x1',
gasLimit: BigInt(21000),
type: BigInt(2), // <- 指定类型
// maxFeePerGas - 可手动指定此属性,否则 Web3.js 会自动填充
// maxPriorityFeePerGas - 可手动指定此属性,否则 Web3.js 会自动填充
};

// 发送交易
const receipt = await web3.eth.sendTransaction(tx);

console.log('Receipt:', receipt);
// Receipt: {
// blockHash: '0xfe472084d1471720b6887071d32a793f7c4576a489098e7d2a89aef205c977fb',
// blockNumber: 23n,
// cumulativeGasUsed: 21000n,
// effectiveGasPrice: 2546893579n,
// from: '0xe2597eb05cf9a87eb1309e86750c903ec38e527e',
// gasUsed: 21000n,
// logs: [],
// logsBloom: '0x0000...00000000000',
// status: 1n,
// to: '0x27aa427c1d668ddefd7bc93f8857e7599ffd16ab',
// transactionHash: '0x5c7a3d2965b426a5776e55f049ee379add44652322fb0b9fc2f7f57b38fafa2a',
// transactionIndex: 0n,
// type: 2n
// }
}
(async () => {
await test();
})();
结论 在本教程中,我们学习了如何使用 web3-eth 包提供的不同方法。 凭借这些知识,你可以开始探索 Ethereum 区块链。请牢记,这仅仅是起点,关于 Ethereum 和 web3.js 还有大量内容等待学习。继续探索与构建,享受其中的乐趣! Web3.js 4.x 版本为与 Ethereum 网络交互及构建去中心化应用程序提供了强大且易用的接口。虽然它已使用 TypeScript 重写,但为了简化本教程,我们使用 JavaScript 进行交互。 Ethereum 生态系统在不断演进,总有新的知识和发现等待挖掘。随着你技能与知识的提升,请继续探索和实验新技术与工具,以构建创新且去中心化的解决方案。 额外资源 - 官方 web3.js 文档 - Solidity 文档 - Ganache - Truffle - Remix IDE 技巧与最佳实践 - 在部署到主网之前,务必在 Ganache 或 Hardhat 等本地网络上测试智能合约。 - 使用最新版本的 web3.js 和 Solidity,以利用最新功能和安全补丁。 - 妥善保管私钥,切勿与他人分享。 - 谨慎使用 gas limit 和 gas price 参数,避免在交易费用上花费过多。 - 在将交易发送到网络之前,使用 web3.js 中的 estimateGas 函数估算所需 gas。 - 使用事件通知客户端应用程序智能合约中的状态变化。 - 使用 Solhint 等 linter 检查常见的 Solidity 编码错误。

评论 (0)