adapter-ethers.ts

This file ships in @gibs/bridge-sdk, at node_modules/@gibs/bridge-sdk/docs/examples/adapter-ethers.ts.

/**
 * The ethers adapter: the signer and the chain reads of the examples, written
 * with ethers 6.
 *
 * Install it beside the packages: `npm install ethers`. The search and the
 * planner still read through viem clients, because viem is the peer
 * dependency of the packages. Pass this file's `ethersChainAccess` and
 * `ethersSigner` where Examples A and B take a `ChainAccess` and a
 * `WalletSigner`.
 *
 * Several endpoints for one chain share one `FallbackProvider`. With a quorum
 * of one, it asks the endpoint with the lowest priority number first. It also
 * asks the next one when the first does not answer within the stall timeout
 * (400 ms by default), and takes the first answer.
 *
 * Typechecked only (`docs/examples/tsconfig.json` in `@gibs/bridge-sdk`). Never run against mainnet.
 */
import type { OriginChainReader } from '@gibs/bridge-indexer';
import type { AllowanceReader } from '@gibs/bridge-sdk/execution';
import { Contract, FallbackProvider, JsonRpcProvider, Network, type Provider, type Signer } from 'ethers';
import { erc20Abi, type Hex, zeroAddress } from 'viem';
import {
  type ChainAccess,
  createClientLookup,
  endpointList,
  type ReceiptOutcome,
  type RpcUrlByChainId,
  requireClientWith,
  toTransactionHash,
  type WalletSigner,
} from './shared.js';

/**
 * The clients of the search and the planner, and one ethers provider per chain
 * for your own reads.
 *
 * @param rpcUrlByChainId - your endpoints for each chain, most reliable first
 * @returns the viem lookups and the ethers provider lookup
 */
export const ethersClients = (rpcUrlByChainId: RpcUrlByChainId) => {
  // #region clients
  // The search and the planner read through viem clients. Build them as in the viem example.
  const clientForChain = createClientLookup(rpcUrlByChainId);
  const requireClient = requireClientWith(clientForChain);

  // Your own reads, receipts and status checks go through ethers.
  const ethersProviderFor = (chainId: number, urls: readonly string[]): Provider => {
    const network = Network.from(chainId);
    const providers = urls.map((url) => new JsonRpcProvider(url, network, { staticNetwork: network }));
    const [only] = providers;
    if (only !== undefined && providers.length === 1) return only;
    // A lower priority number is asked first. With a quorum of one, the first answer wins.
    const configs = providers.map((provider, index) => ({ provider, priority: index + 1, weight: 1 }));
    return new FallbackProvider(configs, network, { quorum: 1 });
  };
  const providerByChainId = new Map(
    [...rpcUrlByChainId].map(([chainId, urls]) => [chainId, ethersProviderFor(chainId, endpointList(urls))]),
  );
  const requireProvider = (chainId: number): Provider => {
    const provider = providerByChainId.get(chainId);
    if (provider === undefined) throw new Error(`the wallet has no RPC endpoint for chain ${chainId}`);
    return provider;
  };
  // #endregion clients
  return { clientForChain, requireClient, requireProvider };
};

/**
 * The signer, on one ethers signer per chain.
 *
 * @param options.address - the account that signs
 * @param options.signerByChainId - an ethers `Signer` for each chain, such as a `Wallet` connected to that chain's provider
 * @returns the signer
 */
export const ethersSigner = (options: {
  readonly address: Hex;
  readonly signerByChainId: ReadonlyMap<number, Signer>;
}): WalletSigner => {
  const { address, signerByChainId } = options;
  // #region signer
  const signer: WalletSigner = {
    address,
    sendTransaction: async (request) => {
      const chainSigner = signerByChainId.get(request.chainId);
      if (chainSigner === undefined) throw new Error(`no ethers signer for chain ${request.chainId}`);
      // ethers resolves once the wallet broadcast the transaction, before it is mined.
      const response = await chainSigner.sendTransaction({
        chainId: request.chainId,
        to: request.to,
        data: request.data,
        value: request.value,
        ...(request.gas === undefined ? {} : { gasLimit: request.gas }),
      });
      return toTransactionHash(response.hash);
    },
  };
  // #endregion signer
  return signer;
};

/**
 * Reads one unsigned number from a contract. ethers types a contract call's
 * answer as `any`, so the answer is checked here.
 */
const readUint = async (contract: Contract, method: string, ...parameters: readonly unknown[]): Promise<bigint> => {
  const value: unknown = await contract.getFunction(method)(...parameters);
  if (typeof value !== 'bigint') throw new Error(`${method} did not answer a number`);
  return value;
};

/**
 * The chain reads, on the ethers providers.
 *
 * @param requireProvider - the provider lookup from {@link ethersClients}
 * @returns the chain reads
 */
export const ethersChainAccess = (requireProvider: (chainId: number) => Provider): ChainAccess => {
  // #region allowance
  const readAllowance: AllowanceReader = (chainId, token, owner, spender) =>
    readUint(new Contract(token, erc20Abi, requireProvider(chainId)), 'allowance', owner, spender);
  // #endregion allowance

  // #region receipt
  const waitForReceipt = async (request: { chainId: number; hash: Hex }): Promise<ReceiptOutcome> => {
    const receipt = await requireProvider(request.chainId).waitForTransaction(request.hash);
    if (receipt === null) throw new Error(`no receipt for ${request.hash}`);
    // ethers reports 1 for success and 0 for a revert.
    return receipt.status === 1 ? 'success' : 'reverted';
  };
  // #endregion receipt

  // #region origin-reader
  // `fetchTransferStatus` makes two reads on the origin chain. ethers answers block numbers as plain numbers.
  const originReaderFor = (chainId: number): OriginChainReader => {
    const provider = requireProvider(chainId);
    return {
      getTransactionReceipt: async ({ hash }) => {
        const receipt = await provider.getTransactionReceipt(hash);
        // A throw tells `fetchTransferStatus` that the transaction is not mined yet.
        if (receipt === null) throw new Error(`no receipt for ${hash} yet`);
        return { blockNumber: BigInt(receipt.blockNumber) };
      },
      getBlock: async ({ blockTag }) => {
        const block = await provider.getBlock(blockTag);
        return { number: block === null ? null : BigInt(block.number) };
      },
    };
  };
  // #endregion origin-reader

  return {
    readAllowance,
    waitForReceipt,
    originReaderFor,
    readBalance: ({ chainId, token, owner }) => {
      const provider = requireProvider(chainId);
      if (token.toLowerCase() === zeroAddress) return provider.getBalance(owner);
      return readUint(new Contract(token, erc20Abi, provider), 'balanceOf', owner);
    },
  };
};