adapter-viem.ts

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

/**
 * The viem adapter: the signer and the chain reads of the examples, written
 * with viem.
 *
 * viem is already installed, because it is the peer dependency of the
 * packages. Examples A and B use this adapter.
 *
 * The `#region` comments mark the parts that the docs site shows beside the
 * same parts in `adapter-walletconnect.ts`, `adapter-ethers.ts` and
 * `adapter-web3.ts`.
 *
 * 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 { type Account, type Chain, erc20Abi, type Hex, type PublicClient, type Transport, type WalletClient, zeroAddress } from 'viem';
import {
  type ChainAccess,
  createClientLookup,
  type ReceiptOutcome,
  requireClientWith,
  type WalletSigner,
} from './shared.js';

/**
 * The clients of the search and the planner, on placeholder endpoints. Every
 * adapter builds these, because the packages read through viem.
 *
 * @returns the lookup and its strict form
 */
export const exampleViemClients = () => {
  // #region clients
  const clientForChain = createClientLookup(
    new Map([
      [1, ['https://your-ethereum-node.example', 'https://your-backup-ethereum-node.example']],
      [369, ['https://your-pulsechain-node.example']],
    ]),
  );
  const requireClient = requireClientWith(clientForChain);
  // #endregion clients
  return { clientForChain, requireClient };
};

/** A viem wallet client with its account and chain set. */
export type ConnectedWalletClient = WalletClient<Transport, Chain, Account>;

/**
 * The signer, on one viem wallet client per chain.
 *
 * @param options.account - the account that signs
 * @param options.walletClientForChain - the wallet client for a chain, such as `createWalletClient({ account, chain, transport: custom(window.ethereum) })`
 * @returns the signer
 */
export const viemSigner = (options: {
  readonly account: Account;
  readonly walletClientForChain: (chainId: number) => ConnectedWalletClient;
}): WalletSigner => {
  const { account, walletClientForChain } = options;
  // #region signer
  const signer: WalletSigner = {
    address: account.address,
    sendTransaction: (request) => {
      const walletClient = walletClientForChain(request.chainId);
      return walletClient.sendTransaction({
        account,
        chain: walletClient.chain,
        to: request.to,
        data: request.data,
        value: request.value,
        ...(request.gas === undefined ? {} : { gas: request.gas }),
      });
    },
  };
  // #endregion signer
  return signer;
};

/**
 * The chain reads, on the viem clients.
 *
 * @param requireClient - see `requireClientWith` in `shared.ts`
 * @returns the chain reads
 */
export const viemChainAccess = (requireClient: (chainId: number) => PublicClient): ChainAccess => {
  // #region allowance
  const readAllowance: AllowanceReader = (chainId, token, owner, spender) =>
    requireClient(chainId).readContract({
      address: token,
      abi: erc20Abi,
      functionName: 'allowance',
      args: [owner, spender],
    });
  // #endregion allowance

  // #region receipt
  const waitForReceipt = async (request: { chainId: number; hash: Hex }): Promise<ReceiptOutcome> => {
    const receipt = await requireClient(request.chainId).waitForTransactionReceipt({ hash: request.hash });
    return receipt.status;
  };
  // #endregion receipt

  // #region origin-reader
  // A viem public client already has the two reads that `fetchTransferStatus` makes.
  const originReaderFor = (chainId: number): OriginChainReader => requireClient(chainId);
  // #endregion origin-reader

  return {
    readAllowance,
    waitForReceipt,
    originReaderFor,
    readBalance: ({ chainId, token, owner }) => {
      const client = requireClient(chainId);
      if (token.toLowerCase() === zeroAddress) return client.getBalance({ address: owner });
      return client.readContract({ address: token as Hex, abi: erc20Abi, functionName: 'balanceOf', args: [owner] });
    },
  };
};