Getting Started
Welcome to the web3.js Plugins Guide, an exciting new feature introduced in web3.js v4! In addition to the core web3.js libraries, plugins bring specialized functionalities tailored for end-users (functionalities that you, as a developer, can create). These enhancements may involve creating wrappers for specific contracts, adding extra features to RPC methods, or extending the capabilities of web3.js methods. Dive in and explore this innovative addition to web3.js v4!
-
You can find all the web3 plugins𧩠here
-
To list your web3 plugin𧩠into the web3js.org/plugins page, you can submit a PR here
Create a pluginβ
//1. import the `Web3PluginBase` module
const { Web3PluginBase } = require("web3");
//2. Create a Class extending the `Web3Pluginbase`
class MyPlugin extends Web3PluginBase {
//3. Add a name to the plugin
pluginNamespace = "pluginExample";
//4. Create any methods with your desired functionality
async doSomething(){
console.log("Hello web3!");
//send transactions
//initialize contracts
//deploy or interact with contracts
//add your own library, logic or functionality
//much more...
}
}
module.exports = MyPlugin;
Use a pluginβ
//1. import the plugin and web3 module
const { Web3 } = require("web3");
const MyPlugin = require("./plugin");
//2. Initialize the web3 instance
const web3 = new Web3("https://eth.llamarpc.com");
//3. Register plugin to add the current Web3Context
web3.registerPlugin(new MyPlugin());
//4. Use the plugin methods
web3.pluginExample.doSomething();
//--> Hello web3!
Initialize a provider for the pluginβ
There are 2 ways to initialize a provider when you are using a plugin, the first one is within the plugin (internally using the this
object and setProvider()
method). And the second one, is done by the final user by using the registerPlugin()
method.
Register plugin (External - Final user)β
When the final user (developer) is using the plugin, they must write the following:
//Step #1: Import the plugin and web3 module
const { Web3 } = require("web3");
const MyPlugin = require("./plugin");
//Step #2: Initialize the web3 instance
const web3 = new Web3("https://eth.llamarpc.com");
//Step #3: Register plugin to add the current Web3Context
web3.registerPlugin(new MyPlugin());
And once the plugin is registered in step #3 by using registerPlugin(new Plugin)
, the provider in the plugin is automatically set to the provider initialized in Step #2
(in this case: https://eth.llamarpc.com
).