进阶 docs.web3js.org 2026-10-19 02:32:30 · 10 阅读
第18章 Web3 插件开发指南:在 web3.js v4 中构建与使用自定义扩展
快速入门
欢迎使用 Web3 插件 🧩 指南,这是 web3.js v4 中新增的功能。除了核心的 web3.js 库外,插件还带来了专为最终用户定制的专业功能(这些功能可由你作为开发者创建)。增强内容可能包括为特定合约创建包装器、为 RPC 方法添加额外功能、引入外部库或逻辑、扩展 web3.js 方法的功能等。
在本指南中,你将学习构建 web3 插件的基础知识,包括设置 Provider、导入和使用不同的 web3.js 包。
插件开发者指南(面向创建者)
插件用户指南(使用方法)
你可以在这里找到所有 web3 插件 🧩
若希望将你的 web3 插件 🧩 列入 web3js.org/plugins 页面,可以在此提交 PR
创建插件
//1. 导入 Web3PluginBase 模块
import { Web3PluginBase } from "web3";
//2. 创建继承自 Web3PluginBase 的类
class MyPlugin extends Web3PluginBase {
//3. 为插件指定名称
pluginNamespace = "pluginExample";
//4. 创建具有期望功能的方法
async doSomething(){
console.log("Hello web3!");
//发送交易
//初始化合约
//部署或交互合约
//添加自定义库、逻辑或功能
//更多...
}
}
module.exports = MyPlugin;
使用插件
//1. 导入插件和 web3 模块
import { Web3 } from "web3";
import MyPlugin from "./plugin";
//2. 初始化 web3 实例
const web3 = new Web3("https://eth.llamarpc.com");
//3. 注册插件以将当前 Web3Context 添加进去
web3.registerPlugin(new MyPlugin());
//4. 使用插件方法
web3.pluginExample.doSomething();
//--> Hello web3!
在插件中使用 web3 包
使用 Eth 模块
import { FMT_NUMBER, Web3PluginBase, eth } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async getChainId() {
// 这里的 this 是你注册插件时使用的 web3context
return await eth.getChainId(this, { number: FMT_NUMBER.NUMBER });
}
async getBlockNumber() {
return await eth.getBlockNumber(this, { number: FMT_NUMBER.NUMBER });
}
// 更多 web3.eth 方法...
}
export default MyPlugin;
使用 Utils
```text
import { Web3PluginBase, utils } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
weiToEth(value) {
//`this` 指的是在注册插件时使用的 web3 上下文
return utils.fromWei(value, 'ether');
}
//更多 web3.eth. 方法…
}
export default MyPlugin;
``` 使用 Accounts ```text import { Web3PluginBase, eth } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async createAccount() {
const account = eth.accounts.create();
console.log("account:", account);
/*
account: {
address: '0x59E797F2F66AffA9A419a6BC2ED4742b7cBc2570',
privateKey: '0x52a81fc3a7fd6ce9644147c9fb5bfbe1f708f37b4611b3c3310eb9a6dc85ccf4',
signTransaction: [Function: signTransaction],
sign: [Function: sign],
encrypt: [Function: encrypt]
}
*/
}
}
export default MyPlugin;
``` 使用 Wallet ```text import { Web3PluginBase, eth } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async createWallet() {
//1. 创建一个随机账户
const accounts = eth.accounts.create();
//2. 将该账户添加到钱包
const wallet = this.wallet.add(accounts);
//创建钱包后,web3.js 会在底层使用该账户对交易进行签名
console.log(wallet);
/*
Wallet(1) [
{
address: '0x233725561B1430bE2C24Ce9EEabe63E4B46EC9E3',
privateKey: '0x6856adf06dd803e0354450ccf251f829a2c9ef1177ce371f8835bbfb56cd0898',
signTransaction: [Function: signTransaction],
sign: [Function: sign],
encrypt: [Function: encrypt]
},
_accountProvider: {
create: [Function: createWithContext],
privateKeyToAccount: [Function: privateKeyToAccountWithContext],
decrypt: [Function: decryptWithContext]
},
_addressMap: Map(1) { '0x233725561b1430be2c24ce9eeabe63e4b46ec9e3' => 0 },
_defaultKeyName: 'web3js_wallet'
]
*/
}
}
export default MyPlugin;
``` 使用 Contract ```text import { Web3PluginBase, Contract } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async interactWithContract() {
//1. 初始化合约
``` ```js const myContract = new Contract(ABI, ADDRESS);
//2. 调用读取函数
const response = myContract.methods.doSomething().call();
//3. 调用写入函数
//必须先初始化钱包,才能用 wallet[0].address 发送交易
const txReceipt = myContract.methods.doSomething().send({from: wallet[0].address})
}
}
export default MyPlugin;
``` 使用 ENS ```js import { Web3PluginBase } from "web3";
import { ENS } from "web3-eth-ens";
class MyPlugin extends Web3PluginBase {
pluginNamespace = "pluginExample";
async getAddressENS() {
const ens = new ENS(undefined, this); // 关联到当前的 web3Context
return ens.getAddress("ethereum.eth");
}
}
``` info 更多 ENS 方法请见这里 Web3 requestManager(自定义 RPC) ```js import { Web3PluginBase } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async customRPC() {
return await this.requestManager.send({
method: "custom_RPC_call",
params: [],
});
}
async getNonce() {
return await this.requestManager.send({
jsonrpc: "2.0",
method: "eth_getTransactionCount",
params: ["0xEA9eEca67682Cd9c6Ce3DdD1681049D7A897289F", "latest"],
});
}
async getBlockNumber() {
return await this.requestManager.send({
jsonrpc: "2.0",
method: "eth_blockNumber",
params: [],
});
}
}
``` info 所有 Ethereum JSON-RPC API 请见这里 Web3 配置参数 ```js import { Web3PluginBase } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async configParams() {
this.config.handleRevert = true;
this.config.defaultTransactionType = 0x1;
// 更多参数...
}
}
``` info 所有 web3 配置参数请见这里 视频 20 分钟创建你的第一个插件! Chainlink 插件:web3.js、viem、ethers 与 web3 插件对比 🧩
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
weiToEth(value) {
//`this` 指的是在注册插件时使用的 web3 上下文
return utils.fromWei(value, 'ether');
}
//更多 web3.eth. 方法…
}
export default MyPlugin;
``` 使用 Accounts ```text import { Web3PluginBase, eth } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async createAccount() {
const account = eth.accounts.create();
console.log("account:", account);
/*
account: {
address: '0x59E797F2F66AffA9A419a6BC2ED4742b7cBc2570',
privateKey: '0x52a81fc3a7fd6ce9644147c9fb5bfbe1f708f37b4611b3c3310eb9a6dc85ccf4',
signTransaction: [Function: signTransaction],
sign: [Function: sign],
encrypt: [Function: encrypt]
}
*/
}
}
export default MyPlugin;
``` 使用 Wallet ```text import { Web3PluginBase, eth } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async createWallet() {
//1. 创建一个随机账户
const accounts = eth.accounts.create();
//2. 将该账户添加到钱包
const wallet = this.wallet.add(accounts);
//创建钱包后,web3.js 会在底层使用该账户对交易进行签名
console.log(wallet);
/*
Wallet(1) [
{
address: '0x233725561B1430bE2C24Ce9EEabe63E4B46EC9E3',
privateKey: '0x6856adf06dd803e0354450ccf251f829a2c9ef1177ce371f8835bbfb56cd0898',
signTransaction: [Function: signTransaction],
sign: [Function: sign],
encrypt: [Function: encrypt]
},
_accountProvider: {
create: [Function: createWithContext],
privateKeyToAccount: [Function: privateKeyToAccountWithContext],
decrypt: [Function: decryptWithContext]
},
_addressMap: Map(1) { '0x233725561b1430be2c24ce9eeabe63e4b46ec9e3' => 0 },
_defaultKeyName: 'web3js_wallet'
]
*/
}
}
export default MyPlugin;
``` 使用 Contract ```text import { Web3PluginBase, Contract } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async interactWithContract() {
//1. 初始化合约
``` ```js const myContract = new Contract(ABI, ADDRESS);
//2. 调用读取函数
const response = myContract.methods.doSomething().call();
//3. 调用写入函数
//必须先初始化钱包,才能用 wallet[0].address 发送交易
const txReceipt = myContract.methods.doSomething().send({from: wallet[0].address})
}
}
export default MyPlugin;
``` 使用 ENS ```js import { Web3PluginBase } from "web3";
import { ENS } from "web3-eth-ens";
class MyPlugin extends Web3PluginBase {
pluginNamespace = "pluginExample";
async getAddressENS() {
const ens = new ENS(undefined, this); // 关联到当前的 web3Context
return ens.getAddress("ethereum.eth");
}
}
``` info 更多 ENS 方法请见这里 Web3 requestManager(自定义 RPC) ```js import { Web3PluginBase } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async customRPC() {
return await this.requestManager.send({
method: "custom_RPC_call",
params: [],
});
}
async getNonce() {
return await this.requestManager.send({
jsonrpc: "2.0",
method: "eth_getTransactionCount",
params: ["0xEA9eEca67682Cd9c6Ce3DdD1681049D7A897289F", "latest"],
});
}
async getBlockNumber() {
return await this.requestManager.send({
jsonrpc: "2.0",
method: "eth_blockNumber",
params: [],
});
}
}
``` info 所有 Ethereum JSON-RPC API 请见这里 Web3 配置参数 ```js import { Web3PluginBase } from 'web3';
class MyPlugin extends Web3PluginBase {
pluginNamespace = 'pluginExample';
async configParams() {
this.config.handleRevert = true;
this.config.defaultTransactionType = 0x1;
// 更多参数...
}
}
``` info 所有 web3 配置参数请见这里 视频 20 分钟创建你的第一个插件! Chainlink 插件:web3.js、viem、ethers 与 web3 插件对比 🧩