Ethers.js Adapters
It is recommended for projects to migrate to viem when using wagmi, but there are some cases where you might still need to use ethers.js in your project:
- You may want to incrementally migrate ethers.js usage to viem
- Some third-party libraries & SDKs may only support ethers.js
We have provided reference implementations for viem → ethers.js adapters that you can copy + paste in your project.
Public Client → Provider
Reference Implementation
Copy the following reference implementation into a file of your choice:
src/ethers.ts
import * as React from 'react'
import { type PublicClient, usePublicClient } from 'wagmi'
import { providers } from 'ethers'
import { type HttpTransport } from 'viem'
 
export function publicClientToProvider(publicClient: PublicClient) {
  const { chain, transport } = publicClient
  const network = {
    chainId: chain.id,
    name: chain.name,
    ensAddress: chain.contracts?.ensRegistry?.address,
  }
  if (transport.type === 'fallback')
    return new providers.FallbackProvider(
      (transport.transports as ReturnType<HttpTransport>[]).map(
        ({ value }) => new providers.JsonRpcProvider(value?.url, network),
      ),
    )
  return new providers.JsonRpcProvider(transport.url, network)
}
 
/** Hook to convert a viem Public Client to an ethers.js Provider. */
export function useEthersProvider({ chainId }: { chainId?: number } = {}) {
  const publicClient = usePublicClient({ chainId })
  return React.useMemo(() => publicClientToProvider(publicClient), [publicClient])
}Usage
Now you can use the useEthersProvider Hook in your components:
src/Example.ts
import { useEthersProvider } from './ethers'
 
function Example() {
  const provider = useEthersProvider()
  ...
}Wallet Client → Signer
Reference Implementation
Copy the following reference implementation into a file of your choice:
src/ethers.ts
import * as React from 'react'
import { type WalletClient, useWalletClient } from 'wagmi'
import { providers } from 'ethers'
 
export function walletClientToSigner(walletClient: WalletClient) {
  const { account, chain, transport } = walletClient
  const network = {
    chainId: chain.id,
    name: chain.name,
    ensAddress: chain.contracts?.ensRegistry?.address,
  }
  const provider = new providers.Web3Provider(transport, network)
  const signer = provider.getSigner(account.address)
  return signer
}
 
/** Hook to convert a viem Wallet Client to an ethers.js Signer. */
export function useEthersSigner({ chainId }: { chainId?: number } = {}) {
  const { data: walletClient } = useWalletClient({ chainId })
  return React.useMemo(
    () => (walletClient ? walletClientToSigner(walletClient) : undefined),
    [walletClient],
  )
}Usage
Now you can use the useEthersSigner Hook in your components:
src/Example.ts
import { useEthersSigner } from './ethers'
 
function Example() {
  const signer = useEthersSigner()
  ...
}