Building your own connector is as simple as defining a class that implements a specific interface!
First, define your connector class:
import { Connectors } from `web3-vanilla`
const { Connector } = Connectors
class MyConnector extends Connector {
...
}
For ideas on how to implement required functions, see src/connectors/ repo.
async getProvider(networkId?: number): Promise<Provider>
For ideas on how to implement optional functions, or for default behavior, see src/connectors/ repo.
async onActivation(): Promise<void>
onDeactivation(Error | null): void
async getNetworkId(provider: Provider): Promise<number>
async getAccount(provider: Provider): Promise<string | null>
It's likely that if you're writing a custom connector, you'll want to use the convenience classes exported by @0x/subproviders
(which in turn relies on web3-provider-engine), as most of the default connectors do. To facilitate this, all exports of @0x/subproviders
are provided under the named subproviders
export of this package.
import { subproviders } from 'web3-vanilla'
Connectors
can emit one of 3 events to trigger specific functionality within web3-vanilla
. The way to do this is to call the appropriate wrapper function in the underlying Connector
class:
_web3UpdateHandler({ updateNetworkId?: boolean, updateAccount?: boolean, overrideNetworkIdCheck?: boolean, overrideAccountCheck?: boolean, networkId?: number, account?: string})
: update the current network ID and/or account. One/Both ofupdateNetworkId
/updateAccount
must be passed.networkId
/account
are optional arguments that indicate the new network id account (if not passed, these values are fetched using.getNetworkId
/.getAccount
).overrideNetworkIdCheck
/overrideAccountCheck
control whether, ifnetworkId
/account
are passed, whether to override calling the.getNetworkId
/.getAccount
methods of the active connector._web3ErrorHandler(error: Error, clearConnector?: boolean)
: set an error, optionally clearing the current active connector._web3ResetHandler()
: unset the connector.
If your connector emits custom error codes that you want to recognize and deal with in specific ways within your dApp, your connector should be defined as follows:
import { Connectors } from `web3-vanilla`
const { Connector, ErrorCodeMixin } = Connectors
const MyConnectorErrorCodes = ['MY_ERROR_CODE', ...]
class MyConnector extends ErrorCodeMixin(Connector, MyConnectorErrorCodes) {
...
}
This ensures that a static .errorCodes
property will exist on your connector, which will contain an object with keys and values equal to the passed error code strings.
console.log(MyConnector.errorCodes) // { MY_ERROR_CODE: 'MY_ERROR_CODE', ... }