
区块链Web3【免费下载链接】web3.jsCollection of comprehensive TypeScript libraries for Interaction with the Ethereum JSON RPC API and utility functions.项目地址https://gitcode.com/gh_mirrors/we/web3.js点击查看免费下载导读web3-plugin-example是 web3.js 4.x 官方维护的插件参考实现包当前版本 1.1.1代码位于 tools/web3-plugin-example它以最小可运行的方式演示了 web3.js 插件系统的三大核心能力包装合约方法以扩展自定义业务逻辑、通过requestManager发起自定义 RPC 方法、以及通过交易中间件在发送前改写交易。本文以该包的 CHANGELOG.md 为演进主线结合包内全部src/源码与单元测试逐层拆解每个插件特性的实现原理、注册机制与测试方式帮助读者在阅读完后能够独立编写并注册自己的 web3.js 插件。一、包的定位与演进主线从 Changelog 看插件能力的增长web3-plugin-example的 CHANGELOG.md 记录了该参考实现随 web3.js 插件系统同步迭代的全过程其内容主线如下0.1.0-alpha.1首个功能版本加入两大核心示例 —— 包装合约方法以提供自定义功能的插件Example plugin for wrapping contract methods to provide custom functionality以及使用requestManager调用自定义 RPC 方法的插件Example plugin for custom RPC methods using therequestManager对应 PR #53930.1.0-alpha.2更新依赖PR #57251.0.0-rc.0 / rc.1更新依赖并在 rc.1 中加入源码文件PR #59561.0.0正式稳定发布Stable release1.0.1 / 1.0.2 / 1.0.4持续更新依赖1.0.6加入**交易中间件Transaction middleware**示例对应 PR #7088这是插件体系从读取类功能扩展到交易改写类功能的关键节点1.1.1再次更新依赖即当前仓库版本。结合 package.json 中的描述Example implementations of Web3.js 4.x plugin system可以看出该包并非独立业务库而是面向插件作者的最小可运行样板。它演示的三类能力与 changelog 的演进顺序一一对应下面按此脉络逐节深入。二、环境要求与包脚本在进入源码之前先明确该示例包的运行环境与工程化设施。依据 package.json 与 README.mdNode.js 14npm 6.12.0编译产物通过tsc --build输出lib/与dist/其中files字段声明发布时包含lib/**/*与src/**/*peerDependencies即插件运行所依赖的宿主包版本区间web3-core 4.1.1 5、web3-eth 4.7.0 5、web3-eth-abi 4.1.1 5、web3-eth-contract 4.0.5 5、web3-types 1.1.1 5、web3-utils 4.0.5 5这从依赖层面印证了插件与核心包严格同版本族的耦合方式常用脚本完整列表见 README.md 的 Package.json Scripts 表脚本作用build使用tsc构建本包及其依赖包lint/lint:fix使用eslint检查 / 修复format使用prettier格式化代码test/test:unit使用jest运行test/unit下的单元测试test:watch监听模式运行测试三、插件一包装合约方法向合约调用注入自定义逻辑0.1.0-alpha.1changelog 0.1.0-alpha.1 记录的第一项能力是wrapping contract methods to provide custom functionality。其实现位于 contract_method_wrappers.ts 的ContractMethodWrappersPlugin类。3.1 类骨架与命名空间import { Web3PluginBase } from web3-core; import Contract from web3-eth-contract; export class ContractMethodWrappersPlugin extends Web3PluginBase { public pluginNamespace contractMethodWrappersPlugin; public readonly _contract: Contracttypeof ERC20TokenAbi; public constructor(abi: ContractAbi, address: Address) { super(); this._contract new Contract(abi, address); } // ... }关键设计点插件必须继承web3-core导出的Web3PluginBase并声明唯一的pluginNamespace字符串此处为contractMethodWrappersPlugin它决定了插件被注册到Web3/Web3Context实例后的挂载属性名构造函数接收合约abi与合约address在插件内部持有一个web3-eth-contract的Contract实例。注意此处源码注释说明字段本应设为private但为便于单测中对_contract.requestManager.send进行 mock 才开放为public——这是测试驱动设计在示例中的直接体现。3.2link方法注册时把宿主上下文注入内部合约public link(parentContext: Web3Context) { super.link(parentContext); this._contract.link(parentContext); }这是 web3.js 插件机制的核心回调当调用Web3.registerPlugin(plugin)时宿主会调用插件的link(parentContext)方法把宿主的Web3Context包含 provider、requestManager等注入插件。该示例在super.link之外把同样的上下文继续转发给内部持有的Contract实例从而让内部合约复用宿主已配置的RequestManager与网络连接——插件与宿主由此共享同一套 RPC 通道。reexported_web3_context.ts中Web3Context是从web3-core直接再导出的见 reexported_web3_context.ts之所以单独再导出是为了支持后文 3.4 的模块声明合并module augmentation。3.3 包装后的业务方法余额格式化与转账插件把底层contract.methods.xxx调用包装成更高层、更产品化的接口public async getFormattedBalanceReturnFormat extends DataFormat( address: Address, returnFormat: ReturnFormat, ) { return format( { format: unit }, await this._contract.methods.balanceOf(address).call(), returnFormat, ); } public async transferAndGetBalancesReturnFormat extends DataFormat( sender: Address, recipient: Address, amount: Numbers, returnFormat?: ReturnFormat, ) { await this._contract.methods .transfer(recipient, numberToHex(amount)) .send({ from: sender, type: 0 }); return { sender: { address: sender, balance: await this.getFormattedBalance(sender, returnFormat ?? DEFAULT_RETURN_FORMAT) }, recipient: { address: recipient, balance: await this.getFormattedBalance(recipient, returnFormat ?? DEFAULT_RETURN_FORMAT) }, }; }技术要点返回值格式化getFormattedBalance通过web3-utils的format({ format: unit }, rawValue, returnFormat)把balanceOf返回的原始数值按unit即 ETH 精度格式化同时支持调用方通过泛型ReturnFormat extends DataFormat指定返回格式默认回落到DEFAULT_RETURN_FORMAT交易发送细节transferAndGetBalances内部将amount用numberToHex转换为十六进制后调用transfer并在send中显式传入type: 0legacy 交易类型与from发送方地址——这是 web3.js 4.x 中可选的交易类型控制写法方法最后返回发送方与接收方转账后余额的结构化对象演示了包装 组合多个合约调用 数据二次加工的典型插件形态。3.4 模块声明合并让插件方法具备类型安全文件末尾的关键技巧是 TypeScript 模块声明合并module augmentationdeclare module ./reexported_web3_context { interface Web3Context { contractMethodWrappersPlugin: ContractMethodWrappersPlugin; } }由于registerPlugin是动态注册TypeScript 无法自动得知web3.contractMethodWrappersPlugin存在。通过在插件包内对Web3Context接口做声明合并使用者便可在编译期获得web3.contractMethodWrappersPlugin.getFormattedBalance(...)的完整类型提示。该模式在包内每个插件文件中反复出现custom_rpc_methods.ts、transaction_middleware_plugin.ts 均有同样写法是 web3.js 插件作者必须掌握的标准做法。四、插件二通过requestManager调用自定义 RPC 方法0.1.0-alpha.1changelog 0.1.0-alpha.1 记录的第二项能力是custom RPC methods using therequestManager实现位于 custom_rpc_methods.ts 的CustomRpcMethodsPlugin。4.1 泛型 RPC API 描述插件通过泛型参数向Web3PluginBase描述它要暴露的 RPC 方法签名type CustomRpcApi { custom_rpc_method: () string; custom_rpc_method_with_parameters: (parameter1: string, parameter2: number) string; }; export class CustomRpcMethodsPlugin extends Web3PluginBaseCustomRpcApi { ... }这为requestManager.send提供了编译期的请求/响应类型约束是 web3.js 4.x 类型安全 RPC 封装的直接体现。4.2 使用requestManager直接发送 JSON-RPCpublic async customRpcMethod() { return this.requestManager.send({ method: custom_rpc_method, params: [], }); } public async customRpcMethodWithParameters(parameter1: string, parameter2: number) { return this.requestManager.send({ method: custom_rpc_method_with_parameters, params: [parameter1, parameter2], }); }this.requestManager并非插件自定义字段而是Web3PluginBase在link之后从宿主上下文注入的RequestManager实例。插件方法因此获得了完整的 JSON-RPC 发送能力含批量请求、超时、错误处理等任何节点端支持的自定义 RPC如自定义eth_*扩展都可以用这一模式暴露为类型安全的方法。4.3 可选的 RequestManager 中间件注入构造函数支持testMiddleware开关当开启时插件会创建一个Web3Middleware实例见下节并在link阶段通过parentContext.requestManager.setMiddleware(this.web3Middleware)把它挂到宿主RequestManager上——演示了插件可以在注册阶段主动改造宿主请求管线的能力。4.4 单元测试如何验证 RPC 载荷test/unit/custom_rpc_methods.test.ts 给出了该插件的标准测试姿势先new Web3Context(http://127.0.0.1:8545)并registerPlugin(new CustomRpcMethodsPlugin())再用jest.fn()替换web3Context.requestManager.send最后断言插件方法被调用时传入的 JSON-RPC 对象精确匹配it(should call customRpcMethodWithParameters with expected RPC object, async () { const parameter1 myString; const parameter2 42; await web3Context.customRpcMethods.customRpcMethodWithParameters(parameter1, parameter2); expect(requestManagerSendSpy).toHaveBeenCalledWith({ method: custom_rpc_method_with_parameters, params: [parameter1, parameter2], }); });同时expect(web3Context.customRpcMethods).toBeDefined()验证了插件注册与命名空间挂载的正确性。同目录下还提供了 contract_method_wrappers.test.ts、request_manager_middleware.test.ts、transaction_middleware.test.ts 等测试共同构成该包的回归保障。五、RequestManager 中间件请求/响应双向拦截1.0.6 前后持续演进request_manager_middleware.ts 中的Web3MiddlewareAPI实现了web3-core的RequestManagerMiddlewareAPI接口提供请求发送前与响应返回后两个钩子processRequest(request)在请求发出前改写。示例逻辑对eth_call请求追加0x0、0x1两个额外参数演示注入状态覆盖参数的用途并且同时处理批量请求数组与单请求对象两种形态代码中分别对Array.isArray(reqObj)分支处理processResponse(response)在响应返回后改写。示例以id 1为条件替换result为0x6a756e616964十六进制串并调用jsonRpc.isBatchResponse跳过批量响应演示响应脱敏/改值的拦截思路。从源码结构看该中间件既可以被插件在link中通过setMiddleware挂载如CustomRpcMethodsPlugin的testMiddleware模式也可以独立配置到任意RequestManager上是 web3.js 4.x 请求管线扩展点如日志、缓存、签名、指标采集的基础设施。六、交易中间件发送前改写交易数据1.0.6PR #7088changelog 1.0.6 新增的Transaction middleware是插件体系从请求层延伸到交易层的里程碑涉及两个文件。6.1 中间件本身Web3TransactionMiddlewaretransaction_middleware.ts 实现web3-eth的TransactionMiddleware接口export class Web3TransactionMiddleware implements TransactionMiddleware { public async processTransaction( transaction: TransactionMiddlewareData, _options?: { [key: string]: unknown } | undefined, ): PromiseTransactionMiddlewareData { let txObj { ...transaction }; // Add your logic here for transaction modification txObj.data 0x123; return Promise.resolve(txObj); } }processTransaction接收待发送的交易对象返回改写后的交易。示例把data强制改为0x123实际场景中可在此实现 gas 价格覆盖、nonce 管理、自定义data注入、交易字段校验等逻辑。返回类型保持TransactionMiddlewareData不变确保改写后的交易仍能继续走完 web3-eth 的发送管线。6.2 插件载体TransactionMiddlewarePlugintransaction_middleware_plugin.ts 将上述中间件包装为插件并在link阶段完成挂载public link(parentContext: Web3Context): void { if (this.txMiddleware) { (parentContext as any).Web3Eth.setTransactionMiddleware(this.txMiddleware); } super.link(parentContext); }源码注释明确指出该写法可以同时影响 Web3-Eth 与 Web3-Eth-Contract 两个包的交易——即无论用户是通过web3.eth.sendTransaction发起交易还是通过contract.methods.xxx().send()发起合约交易都会经过同一份Web3Eth实例上的交易中间件从而被统一改写。link末尾仍需调用super.link(parentContext)完成插件基础上下文注入。七、版本演进汇总与插件开发要点7.1 版本时间线依据 CHANGELOG.md版本关键变更0.1.0-alpha.1新增合约方法包装插件、基于requestManager的自定义 RPC 插件#53930.1.0-alpha.2更新依赖#57251.0.0-rc.0更新依赖1.0.0-rc.1加入源码文件#59561.0.0稳定发布1.0.1 / 1.0.2 / 1.0.4更新依赖1.0.6新增交易中间件#70881.1.1更新依赖当前仓库版本该包的版本节奏与 web3.js 4.x 核心库的peerDependencies版本族保持同步说明插件生态需要紧跟核心包 API如RequestManagerMiddleware、TransactionMiddleware接口的演进。7.2 编写 web3.js 插件的最小清单综合本包全部示例一个合格的 web3.js 4.x 插件通常需要继承Web3PluginBase可选携带 RPC API 泛型声明唯一pluginNamespace在构造函数中准备插件所需资源合约实例、中间件实例等按需重写link(parentContext)将宿主上下文转发给内部资源或向宿主注入中间件通过this.requestManager访问宿主 RPC 通道用declare module对Web3Context做模块声明合并补齐 TypeScript 类型在test/unit中覆盖注册挂载 RPC 载荷 中间件行为三类用例。关于安装与使用方式该包可通过npm install web3-plugin-example或yarn add web3-plugin-example引入见 README.md核心用法即web3.registerPlugin(new ContractMethodWrappersPlugin(abi, address))等注册调用更完整的插件开发指南可进一步阅读仓库文档中的 14_web3_plugin_guide 目录含插件作者与插件用户两篇文档。结语从 0.1.0-alpha.1 的合约方法包装 自定义 RPC到 1.0.6 的交易中间件web3-plugin-example的 changelog 本身就是 web3.js 4.x 插件能力边界的演进缩影。本文所引的每个特性都能在 tools/web3-plugin-example/src 中找到最小实现、在 tools/web3-plugin-example/test/unit 中找到对应测试。对希望为 web3.js 扩展能力的开发者而言这份样板包既是学习插件机制的最佳入口也是新插件工程的直接脚手架。赞分享区块链Web3【免费下载链接】web3.jsCollection of comprehensive TypeScript libraries for Interaction with the Ethereum JSON RPC API and utility functions.项目地址https://gitcode.com/gh_mirrors/we/web3.js点击查看免费下载相关推荐web3.js 事件订阅实战指南从智能合约事件到节点推送与自定义 Subscriptionweb3.js 事件订阅实战指南从智能合约事件到节点推送与自定义 Subscription 导读 本指南以 web3.js本仓库 web3.js https区块链Web3web3.js Web3 Core 包深度解析web3.js 4.x 核心基础设施的工作原理与使用指南web3.js Web3 Core 包深度解析web3.js 4.x 核心基础设施的工作原理与使用指南 导读 web3 core 是 web3.js 4.x区块链Web3web3.js 账户抽象实战指南web3-account-abstraction 的 Bundler RPC 封装与 UserOperation 全解析web3.js 账户抽象实战指南web3 account abstraction 的 Bundler RPC 封装与 UserOperation 全解析 本文区块链Web3创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考