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

第19章 Web3.js 从 1.x 升级至 4.x 指南

从 1.x 升级 本指南适用于从 web3.js 1.x 升级到 4.x。 破坏性变更 web3 包现在返回所有 web3.js 导出的对象 `require('web3')` 现在将返回按命名空间组织的所有 web3 导出对象(少数对象保留在顶层)。因此,以下代码不再受支持: // 这将返回命名空间,下一行会抛出错误!
const Web3 = require('web3');

const web3 = new Web3();
现在的正确用法是: JavaScriptTypeScriptconst { Web3 } = require('web3');

const web3 = new Web3();
import { Web3 } from 'web3';

const web3 = new Web3();
向函数传递回调 不再支持向函数传递回调,事件监听器除外。 例如,在 4.x 版本中,订阅和监听区块链事件的方式已变更。详细说明请参阅 web3.eth.subscribe 迁移指南。 然而,订阅 Provider 事件的方式保持不变,仍使用 Providers Events Listening 指南中描述的回调机制。需要注意的是,Provider 发生了一些破坏性变更,包括将 `on('close', ...)` 重命名为 `on('disconnect', ...)`。 不可用 web3.bzz 包(用于与 Swarm 交互)尚未实现 web3.shh 包(用于与 Whisper 交互)尚未实现 `const web3 = new Web3(Web3.givenProvider);` 将不再包含: // web3.bzz 不可用
// web3.shh 不可用
默认值和配置 `givenProvider` 的默认值为 `undefined` 而非 `null` `currentProvider` 的默认值为 `undefined` 而非 `null`(当 web3 实例未传入 provider 时) 注意在 4.x 版本中,所有数字均以 BigInt 形式返回,而非字符串或数字。这对于习惯在代码中将数字处理为字符串或数字的用户来说是一个破坏性变更。例如,`web3.eth.getBalance` 现在返回 BigInt 而非字符串或数字。如果你希望保留数字为 number 或 string 类型,请参考本指南了解如何在 web3js 4.x 中设置返回类型。 Web3 BatchRequest `const batch = new web3.BatchRequest();` `batch.add()` 在 1.x 中,`batch.add()` 不返回任何内容;而在 4.x 中,它返回一个延迟 Promise,可用于在执行完相应请求后运行特定代码。 // 在 1.x 中
batch.add(
web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', callback),
);

// 在 4.x 中

const request1 = {
jsonrpc: '2.0',
id: 10,
method: 'eth_getBalance',
params: ['0xf4ffff492596ac13fee6126846350433bf9a5021', 'latest'],
};
const request2 = {
jsonrpc: '2.0',
id: 12,
method: 'eth_getBalance',
params: ['0xdc6bad79dab7ea733098f66f6c6f9dd008da3258', 'latest'],
};
batch.add(request1);
const request2Promise = batch.add(request2);
request2Promise.then(response => {
console.log(response);
});
batch.execute()​ 在 4.x 中,execute 返回一个 promise;而 1.x 是基于传给 add 的请求回调。 // in 1.x
batch.execute();

// in 4.x
const responses = await batch.execute();
类型(Types)​ 以前从 web3 包导出的所有可复用类型,现在都移到了独立的 web3-types 包中。 注意:我们不推荐使用 @types/web3 包。 // Provider 类型
// in 1.x
import type { Provider, Callback, JsonRPCResponse } from 'web3/providers';

// in 4.x
import type {
Web3BaseProvider as Provider,
Web3ProviderRequestCallback as Callback,
JsonRpcResponse,
} from 'web3-types';
类似地,旧包 web3-core 中的一些常用类型也移到了 web3-types: // in 1.x
import type { Transaction, TransactionReceipt } from 'web3-core';

// in 4.x
import type { Transaction, TransactionReceipt } from 'web3-types';
Web3 Extend​ web3.extend 仍然可用,但不再支持设置 methods.params、methods.inputFormatter 和 methods.outputFormatter。在 TypeScript 中,你需要按下面的示例进行模块扩展(module augmentation)。 // in 1.x
web3.extend({
property: 'myModule',
methods: [
{
name: 'getBalance',
call: 'eth_getBalance',
params: 2,
inputFormatter: [
web3.extend.formatters.inputAddressFormatter,
web3.extend.formatters.inputDefaultBlockNumberFormatter,
],
outputFormatter: web3.utils.hexToNumberString,
},
{
name: 'getGasPriceSuperFunction',
call: 'eth_gasPriceSuper',
params: 2,
inputFormatter: [null, web3.utils.numberToHex],
},
],
});

// in 4.0.4+
declare module 'web3' {
interface Web3Context {
myModule: {
getBalance(address: Address, blockTag: BlockTag): Promise;
getGasPriceSuperFunction(blockTag: BlockTag): Promise;
};
}
}

web3.extend({
property: 'myModule',
methods: [
{
name: 'getBalance',
call: 'eth_getBalance',
},
{
name: 'getGasPriceSuperFunction',
call: 'eth_gasPriceSuper',
},
],
});
Formatters​ 从 4.x 版本开始,web3-core-helpers 包不再维护,格式化器已迁移至 web3-core 包中。 // in 1.x
import { formatters } from 'web3-core-helpers';

// in 4.x
import { formatters } from 'web3-core';
PromiEvent​ 从 4.x 版本开始,web3-core-promievent 包不再维护,相关类已迁移至 web3-core 包中。 // in 1.x
import Web3PromiEvent from 'web3-core-promievent';

// in 4.x
import { Web3PromiEvent } from 'web3-core';
PromiEvent 类不支持 removeEventListener 或 addEventListener 方法,建议改用 on 和 off。

评论 (0)