web3-types 深度解析:web3.js 4.x 统一类型系统与数据结构全集
web3-types 深度解析:web3.js 4.x 统一类型系统与数据结构全集
导读
web3-types 是 web3.js 生态中的类型基础包,集中定义了整个框架共享的数据结构与接口——从 Address、BlockTag 等以太坊基础类型,到 JSON-RPC 报文、ABI 描述、Provider 抽象乃至返回格式控制(DataFormat),几乎所有 web3.js 模块的类型签名都建立在这套地基之上。读完本文,你将掌握 web3-types 的安装与工程脚本用法,并能按图索骥地在 src 目录 中找到各类接口的定义位置,理解其设计动机与调用关系。
包定位:web3.js 的"类型地基"
web3-types 官方定位是:"Contains the common data structures and interfaces used in web3.js",即 web3.js 各模块共享的数据结构与接口集合。它作为 web3.js 的子包存在(仓库中的 package.json 声明其名为 web3-types,当前仓库版本为 1.10.0),采用 LGPL-3.0 许可,要求 Node.js >=14、npm >=6.12.0,并且面向 ES2020 目标编译。
从包导出入口 src/index.ts 可以看到,它通过 export * 一次性聚合了以下类型模块,这正是理解全包结构的目录地图:
| 导出文件 | 职责 |
|---|---|
| error_types.ts | Web3Error、Web3ValidationErrorObject 等错误契约 |
| apis/eth_execution_api.ts | 以太坊执行层 RPC 方法签名集 |
| apis/web3_eth_execution_api.ts | 扩展的钱包/网络相关 RPC 方法 |
| apis/web3_net_api.ts | net_* RPC 方法签名集 |
| apis/eth_personal_api.ts | personal_* RPC 方法签名集 |
| data_format_types.ts | 返回格式控制(数字/字节的格式化枚举) |
| eth_types.ts | 区块、交易、收据、日志、过滤器等核心实体类型 |
| eth_abi_types.ts | ABI 片段类型与根据 ABI 推导 TS 类型的工具 |
| json_rpc_types.ts | JSON-RPC 请求/响应/通知/批量报文类型 |
| primitives_types.ts | HexString、Bytes、Numbers 等原始类型 |
| utility_types.ts | Mutable、FixedSizeArray 等类型工具 |
| web3_api_types.ts | Web3APISpec 等泛型 RPC API 抽象 |
| web3_base_provider.ts | Provider 抽象基类与 EIP-1193 兼容类型 |
| web3_base_wallet.ts | 钱包抽象接口 |
| web3_deferred_promise_type.ts | 延迟 Promise 接口 |
安装与前置要求
web3-types 是一个纯粹的 TypeScript 类型包(运行时仅含少量枚举与常量),安装方式与普通 npm 包一致。
使用 NPM 安装
npm install web3-types
使用 Yarn 安装
yarn add web3-types
环境前置要求
- NodeJS:建议使用 LTS/Fermium 版本(
engines字段要求>=14); - Yarn / Lerna:仓库采用 monorepo 结构(根目录 lerna.json),本地从源码构建或开发时需要 Yarn 与 Lerna 配合。
说明:在 monorepo 中,
web3-types被各业务包(如web3-core、web3-eth、web3-eth-contract等)以依赖方式引用;作为独立包发布后,任何希望与 web3.js 类型体系对齐的项目也都可以直接安装它。
工程化脚本:Package.json Scripts
package.json 中定义的脚本是开发者日常使用的入口,下表是官方 README 列出的全部脚本及其实际执行内容:
| Script | 作用 |
|---|---|
clean |
使用 rimraf 删除 dist/ 与 lib/ 构建产物 |
build |
使用 tsc 并行构建 CJS、ESM 与类型声明(含依赖包) |
lint |
使用 eslint 检查代码 |
lint:fix |
使用 eslint 检查并自动修复警告 |
format |
使用 prettier 统一格式化代码 |
test |
使用 jest 运行单元测试 |
test:integration |
使用 jest 运行 /test/integration 下的集成测试 |
test:unit |
使用 jest 运行 /test/unit 下的单元测试 |
从 package.json 的 build 脚本链可以看出它的双模块发布策略:
build:cjs → tsc --build tsconfig.cjs.json # 产出 lib/commonjs(type: commonjs)
build:esm → tsc --build tsconfig.esm.json # 产出 lib/esm(type: module)
build:types → tsc --build tsconfig.types.json # 产出 lib/types/*.d.ts
exports 字段据此为三种消费方式分别路由:import 走 lib/esm/index.js、require 走 lib/commonjs/index.js、类型走 lib/types/index.d.ts。这意味着同一份源码同时支持 ESM 与 CommonJS 消费者,类型声明则独立编译,是典型的库工程化样板。
类型体系分模块详解
1. 原始类型:primitives_types
一切类型的起点在 primitives_types.ts:
export type HexString = string; // 十六进制字符串
export type Bytes = Uint8Array | HexString; // 字节的两种表达
export type Numbers = number | bigint | string | HexString; // 数字的四种表达
Numbers 允许 number | bigint | string | HexString 四种形式,这是 web3.js 对"数字"的宽容定义——RPC 结果中的数量既可能是 number,也可能是 hex string,还可能超出 number 安全范围的 bigint。而 Bytes 统一了"十六进制字符串"与 Uint8Array 两种字节形态,为后续 DataFormat 的字节格式化奠定了基础。
2. 返回格式控制:data_format_types 与 FormatType
data_format_types.ts 定义了 web3.js 4.x 最具特色的"输出格式约定"机制:
export enum FMT_NUMBER {
NUMBER = 'NUMBER_NUMBER', // 输出为 number
HEX = 'NUMBER_HEX', // 输出为十六进制字符串
STR = 'NUMBER_STR', // 输出为字符串
BIGINT = 'NUMBER_BIGINT', // 输出为 bigint
}
export enum FMT_BYTES {
HEX = 'BYTES_HEX', // 输出为十六进制字符串
UINT8ARRAY = 'BYTES_UINT8ARRAY', // 输出为 Uint8Array
}
export type DataFormat = {
readonly number: FMT_NUMBER;
readonly bytes: FMT_BYTES;
};
仓库还预置了两个常用格式常量:
export const DEFAULT_RETURN_FORMAT = {
number: FMT_NUMBER.BIGINT,
bytes: FMT_BYTES.HEX,
} as const;
export const ETH_DATA_FORMAT = { number: FMT_NUMBER.HEX, bytes: FMT_BYTES.HEX } as const;
DEFAULT_RETURN_FORMAT:web3.js 默认返回格式——数字一律以bigint返回(避免精度丢失),字节以十六进制字符串返回;ETH_DATA_FORMAT:与以太坊 RPC 原始 wire 格式对齐——数字为 hex,字节为 hex,即"原样返回"。
关键的类型级工具是 FormatType<T, F>,它递归地把一个类型 T 中所有 Numbers 与 Bytes 出现的位置,按格式 F 替换成对应的目标类型:
export type FormatType<T, F extends DataFormat> = number extends Extract<T, Numbers>
? NumberTypes[F['number']] | Exclude<T, Numbers>
: Uint8Array extends Extract<T, Bytes>
? ByteTypes[F['bytes']] | Exclude<T, Bytes>
: T extends object | undefined
? { [P in keyof T]: FormatType<T[P], F> }
: T;
换句话说,传入 ETH_DATA_FORMAT 时得到 hex 化的返回结构,传入 DEFAULT_RETURN_FORMAT 时得到 bigint 化的返回结构。这正是 getBalance、getBlock 等方法在不同 returnFormat 参数下返回不同形态数据背后的类型引擎。这套设计可以配合 docs 中 return-formats 指南 进一步理解。
3. 以太坊核心实体:eth_types
eth_types.ts 是内容最丰富的文件,覆盖了以太坊数据模型的全貌:
基础别名:Address = HexString、TransactionHash = HexString、HexString32Bytes(32 字节哈希)等,均为带语义的字符串别名,便于阅读与 IDE 提示。
区块标签与硬分叉枚举:
export enum BlockTags {
EARLIEST = 'earliest',
LATEST = 'latest',
PENDING = 'pending',
SAFE = 'safe',
FINALIZED = 'finalized',
COMMITTED = 'committed',
}
export type BlockNumberOrTag = Numbers | BlockTag;
HardforksOrdered 则按时间顺序列出了从 chainstart、frontier 到 shanghai 的全部硬分叉名,注释明确要求"保持顺序",因为该枚举还被用于硬分叉优先级比较。
交易类型族:TransactionInput(RPC 原始输入,字段多为 HexString)与 TransactionOutput(格式化输出,字段多为 Numbers)成对出现,Output 通过联合类型强制了 EIP-1559 字段的互斥约束——要么提供 gasPrice,要么提供 maxPriorityFeePerGas + maxFeePerGas,二者不可共存:
} & (
| { maxPriorityFeePerGas: Numbers; maxFeePerGas: Numbers; gasPrice?: never }
| { maxPriorityFeePerGas?: never; maxFeePerGas?: never; gasPrice: Numbers }
);
此外还有 Transaction、TransactionCall、TransactionInfo、PopulatedUnsignedBaseTransaction / PopulatedUnsignedEip2930Transaction / PopulatedUnsignedEip1559Transaction 等派生形态,以及针对本地钱包索引的 TransactionWithFromLocalWalletIndex 等变体——它们被 web3-eth-accounts 与交易签名逻辑直接使用。
区块与收据:BlockInput/BlockOutput、BlockHeaderOutput、ReceiptInput/ReceiptOutput、LogsInput/LogsOutput 均遵循"Input 用 HexString、Output 用 Numbers"的成对设计。BlockHeaderOutput 中还注释说明:author、totalDifficulty、size 等字段仅在 Nethermind 客户端返回,Geth 等其他客户端没有——这是针对真实 RPC 客户端差异的细致处理。
过滤与日志:Filter 严格贴合 Ethereum execution-apis 的 filter schema,其中 topics 使用 (null | Topic | Topic[])[],用 null 表示"任意 topic"(源码注释明确说明这是有意为之以匹配规范)。
EIP-712 与 FeeData:Eip712TypedData 定义了类型化数据的 types/primaryType/domain/message 四段结构;FeeData 则对 EIP-1559 的四个费用字段逐一给出 JSDoc 解释——gasPrice 用于不支持 EIP-1559 的遗留网络,baseFeePerGas 仅作信息参考(实际支付为"未来 baseFee + tip"),maxFeePerGas 用于设置支付上限防止 baseFee 暴涨。
4. JSON-RPC 报文:json_rpc_types
json_rpc_types.ts 用类型系统完整建模了 JSON-RPC 协议:
JsonRpcId = string | number | undefined、JsonRpcIdentifier = string & ('2.0' | '1.0')(模板字面量类型);- 响应被严格二分:
JsonRpcResponseWithError(含error,result?: never)与JsonRpcResponseWithResult(含result,error?: never),利用never从类型层面保证"成功与失败互斥"; JsonRpcNotification描述订阅推送(method+params.subscription+params.result);JsonRpcPayload = JsonRpcRequest | JsonRpcBatchRequest,JsonRpcResponse则进一步联合了单响应、批量响应与通知,构成 Provider 收发报文的完整契约。
这些类型是 web3-core 中 Web3RequestManager 发送请求、web3-providers-* 各 Provider 实现 request 方法的类型依据。
5. ABI 描述与合约类型推导:eth_abi_types
eth_abi_types.ts 一方面完整复刻了 Solidity ABI JSON 规范(AbiConstructorFragment、AbiFunctionFragment、AbiEventFragment、AbiErrorFragment、AbiFallbackFragment 及 ContractAbi),另一方面实现了大量"根据 ABI 推导 TypeScript 类型"的条件类型工具,这是 web3.js 合约类型推断的核心:
PrimitiveAddressType、PrimitiveIntegerType等把 ABI 类型字符串(如address[]、uint256[3])映射为 TS 类型,并支持带固定长度的数组(通过FixedSizeArray与ConvertToNumber实现);MatchPrimitiveType<Type, Components>汇总上述映射,递归处理tuple;ContractMethods<Abis>、ContractEvents<Abis>使用FilterAbis从整个 ABI 中筛出 function/event 片段,按名称生成方法签名映射;ContractMethodOutputParameters对多返回值做了特殊处理:单个返回值直接返回该类型,多个返回值则生成"既可按位置索引、又可按名字访问"的交叉类型(ArrToObjectWithFunctions)。
换句话说,当你用 as const 声明 ABI 并把 ContractAbi 泛型传给 web3-eth-contract 的 Contract 时,方法参数与返回值类型就是由这套条件类型在编译期推导出来的,这也是 docs 中智能合约类型推断指南 所述能力的具体实现。
6. RPC 方法签名:apis 目录
apis/ 目录用"接口方法签名即 RPC 方法"的模式声明了各领域 RPC:
- eth_execution_api.ts:标准
eth_*执行层方法(eth_blockNumber、eth_getBalance、eth_call、eth_sendTransaction等); - web3_eth_execution_api.ts:在
EthExecutionAPI基础上通过交叉类型扩展了 EIP 相关与钱包方法,例如:
export type Web3EthExecutionAPI = EthExecutionAPI & {
eth_pendingTransactions: () => TransactionInfo[];
eth_requestAccounts: () => Address[]; // EIP-1102
eth_chainId: () => Uint; // EIP-695
web3_clientVersion: () => string;
eth_getProof: (address: Address, storageKeys: HexString32Bytes[], blockNumber: BlockNumberOrTag) => AccountObject; // EIP-1186
eth_signTypedData: (address: Address, typedData: Eip712TypedData, useLegacy: true) => HexString256Bytes; // EIP-712
eth_signTypedData_v4: (address: Address, typedData: Eip712TypedData, useLegacy: false | undefined) => HexString256Bytes;
};
- web3_net_api.ts 与 eth_personal_api.ts 分别对应
net_*与personal_*方法族。
web3_api_types.ts 中的 Web3APISpec、Web3APIMethod、Web3APIReturnType 等泛型工具,正是以这些 API 接口为"规格参数",让 request({ method, params }) 在编译期就能推导出对应 RPC 的返回类型。
7. Provider 抽象:web3_base_provider
web3_base_provider.ts 定义了 Provider 层的统一抽象,核心是抽象的 Web3BaseProvider 类:
- 实现了
LegacySendProvider、LegacySendAsyncProvider、EIP1193Provider三套接口,向下兼容旧式send/sendAsync回调风格(均标注@deprecated,建议改用request); - 通过
Symbol.for('web3/base-provider')符号提供跨包版本的isWeb3Provider检测——即使不同包版本导致instanceof失效,符号机制依然可靠; asEIP1193Provider()返回一个request直接 resolve 出result的 EIP-1193 全兼容实例(源码注释指出该能力在未来 v5 将不再需要,因为届时所有 Provider 默认完全兼容 EIP-1193);- 定义了
Web3ProviderStatus = 'connecting' | 'connected' | 'disconnected'、Eip1193EventName五类事件(connect/disconnect/message/chainChanged/accountsChanged)以及SupportedProviders联合类型。
web3-providers-http、web3-providers-ws、web3-providers-ipc 三个实现包均继承自该抽象类。
8. 错误与工具类型:error_types、utility_types
error_types.ts 定义了 Web3Error(含 name、code、stack)与 Web3ValidationErrorObject(AJV 风格校验错误,含 keyword、instancePath、schemaPath、params 等字段,供 web3-validator 校验失败时使用)。
utility_types.ts 提供了若干通用类型工具:Mutable<T> 去除 readonly、Optional<T, K> 将部分键变为可选、FixedSizeArray<T, N>(通过递归元组 GrowToSize 生成固定长度数组类型,配合 ABI 固定长度数组映射使用)、ConnectionEvent(WebSocket 关闭事件结构)以及 EncodingTypes/TypedObject(编码输入类型)。
在 web3.js 生态中的实际运用
web3-types 的实战价值体现在两个层面:
- 作为类型消费者:在
web3、web3-eth、web3-eth-contract等包的源码中,随处可见从web3-types导入Transaction、Block、DataFormat、EthExecutionAPI等类型的语句,例如 packages/web3/src/index.ts 会对外重新导出这些类型,让最终用户无需直接安装web3-types也能拿到完整的类型标注; - 作为类型提供者:编写自定义 Provider、自定义 RPC 插件或扩展合约封装时,可以复用
Web3APISpec、Web3BaseProvider、ContractAbi等抽象,保证与 web3.js 生态的类型互操作(可参考 web3-plugin-example 示例 中自定义 RPC 方法与中间件的类型用法)。
总结
web3-types 虽然"不包含业务逻辑",却是 web3.js 4.x 全栈类型安全的关键支柱:它以 primitives_types 为根,用 eth_types 覆盖以太坊数据模型,用 json_rpc_types 约束报文结构,用 eth_abi_types 驱动合约类型的编译期推导,用 data_format_types 控制返回格式,再用 apis/* 与 web3_base_provider 完成 RPC 方法与 Provider 的统一抽象。理解这套类型体系,是深入 web3.js 源码、编写类型安全的以太坊应用或扩展自定义插件的第一步。