web3.js icon indicating copy to clipboard operation
web3.js copied to clipboard

Enhance plugin module augmentation and replace it with a better pattern

Open Muhammad-Altabba opened this issue 1 year ago • 0 comments
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

Muhammad-Altabba avatar Jan 29 '24 14:01 Muhammad-Altabba