Skip to content

EthersProviderAdapter

EthersProviderAdapter is an extension of the ethers.js JsonRpcProvider which includes a SmartAccountClient field to integrate EIP-4337 smart accounts. The interface is similar to a standard JsonRpcProvider, with additional methods to leverage the Alchemy Account Abstraction stack.

Notable differences between EthersProviderAdapter and JsonRpcProvider are implementations for:

  1. send -- sends EIP-1193-compliant requests through the account provider.
  2. connectToAccount -- connects the provider to an account and returns an AccountSigner.
  3. getBundlerClient -- gets the underlying viem client with ERC-4337 compatibility.
  4. fromEthersProvider -- static method that converts an ethers.js JsonRpcProvider to an EthersProviderAdapter.

Usage

ts
import { provider } from "./ethers-provider";
import {
  LightSmartContractAccount,
  getDefaultLightAccountFactoryAddress,
} from "@alchemy/aa-accounts";
import { LocalAccountSigner, type SmartAccountSigner } from "@alchemy/aa-core";
import { polygonMumbai } from "@alchemy/aa-core";
import { http } from "viem";


// EIP-1193 compliant requests
const chainId = await provider.send("eth_chainId", []);

// get the provider's underlying viem client with EIP-4337 capabilities
const client = provider.getBundlerClient();

// connect the provider to an AccountSigner
const signer: SmartAccountSigner = LocalAccountSigner.mnemonicToAccountSigner(
  process.env.YOUR_OWNER_MNEMONIC!
);
const accountSigner = provider.connectToAccount(
  await createLightAccount({
    chain,
    transport: http("RPC_URL"),
    signer,
  })
);
ts
import {
  createSimpleSmartAccount,
  getChain,
  getDefaultSimpleAccountFactoryAddress,
} from "@alchemy/aa-core";
import { EthersProviderAdapter } from "@alchemy/aa-ethers";
import { Alchemy, Network } from "alchemy-sdk";
import { signer } from "snippets/aa-core/lightAccountClient";
import { http } from "viem";

// 1. Create alchemy instance
const alchemy = new Alchemy({
  apiKey: process.env.API_KEY!,
  network: Network.MATIC_MUMBAI,
});
const ethersProvider = await alchemy.config.getProvider();

const chain = getChain(ethersProvider.network.chainId);

// 2. smart account client from alchemy's ethers provider and connect with simple smart account
export const provider = EthersProviderAdapter.fromEthersProvider(
  ethersProvider
).connectToAccount(
  await createSimpleSmartAccount({
    chain,
    signer,
    factoryAddress: getDefaultSimpleAccountFactoryAddress(chain),
    transport: http(
      `${chain.rpcUrls.alchemy.http[0]}/${ethersProvider.apiKey}`
    ),
  })
);