web3.js
web3.js copied to clipboard
Enhance plugin module augmentation and replace it with a better pattern
trafficstars
First of all update the documentation for the module augmentation. As, no need to augment the Web3Context, and augmenting Web3 is enough.
Additionally, I suggest to set the module augmentation pattern as deprecated in the docs, and to replace that old pattern in the documentation with the following:
class SamplePlugin extends Web3PluginBase {
/**
* Register the plugin with web3 and return the web3 instance.
* @param web3
* @returns web3 instance with the plugin registered
*/
public registerAt(web3: Web3){
web3.registerPlugin(this);
return web3 as Web3 & { YOUR_PLUGIN_NAMESPACE: SamplePlugin };
}
}
And the usage will be like this for the plugin users:
let web3 = new Web3('http://some-rpc-provider.com');
// web3.YOUR_PLUGIN_NAMESPACE is undefined and un-accessible
web3 = new SamplePlugin().registerAt(web3);
// web3.YOUR_PLUGIN_NAMESPACE is now defined and accessible
// or
const originalWeb3 = new Web3('http://some-rpc-provider.com');
const web3WithPlugin = new SamplePlugin().registerAt(originalWeb3);
// web3WithPlugin.YOUR_PLUGIN_NAMESPACE is defined and accessible