Skip to content

Provider

Utilities & types for working with EIP-1193 Providers

Examples

Below are some examples demonstrating common usages of the Provider module:

Instantiating External Providers

External EIP-1193 Providers can be instantiated with Provider.from:

import 'ox/window'
import { Provider } from 'ox'
 
const provider = Provider.from(window.ethereum)
 
const blockNumber = await provider.request({ method: 'eth_blockNumber' })

Instantiating with an RPC Transport

Ox's RpcTransport is also EIP-1193 compliant, and can be used to instantiate an EIP-1193 Provider. This means you can use any HTTP RPC endpoint as an EIP-1193 Provider.

import { Provider, RpcTransport } from 'ox'
 
const transport = RpcTransport.fromHttp('https://1.rpc.thirdweb.com')
const provider = Provider.from(transport)

Instantiating a Provider with Events

Event emitters for EIP-1193 Providers can be created using Provider.createEmitter:

Useful for Wallets that distribute an EIP-1193 Provider (e.g. webpage injection via window.ethereum).

import { Provider, RpcRequest, RpcResponse } from 'ox'
 
// 1. Instantiate a Provider Emitter.
const emitter = Provider.createEmitter()
 
const store = RpcRequest.createStore()
 
const provider = Provider.from({
  // 2. Pass the Emitter to the Provider.
  ...emitter, 
  async request(args) {
    return await fetch('https://1.rpc.thirdweb.com', {
      body: JSON.stringify(store.prepare(args)),
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    })
      .then((res) => res.json())
      .then(RpcResponse.parse)
  },
})
 
// 3. Emit Provider Events.
emitter.emit('accountsChanged', ['0x...'])

Functions

NameDescription
Provider.createEmitterCreates an EIP-1193 flavored event emitter to be injected onto a Provider.
Provider.fromInstantiates an EIP-1193 Provider.Provider from an arbitrary EIP-1193 Provider interface.

Errors

NameDescription
Provider.IsUndefinedErrorThrown when the provider is undefined.
Provider.ProviderRpcError

Types

NameDescription
Provider.ConnectInfo
Provider.EmitterType for an EIP-1193 Provider's event emitter.
Provider.EventListenerFnType for an EIP-1193 Provider's event listener functions (on, removeListener, etc).
Provider.EventMap
Provider.Message
Provider.OptionsOptions for a Provider.Provider.
Provider.ProviderRoot type for an EIP-1193 Provider.
Provider.RequestFnEIP-1193 Provider's request function.