adapter-web3.ts

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

/**
 * The web3.js adapter: the signer and the chain reads of the examples, written
 * with web3.js 4.
 *
 * Install it beside the packages: `npm install web3`. The search and the
 * planner still read through viem clients, because viem is the peer
 * dependency of the packages. Pass this file's `web3ChainAccess` and
 * `web3Signer` where Examples A and B take a `ChainAccess` and a
 * `WalletSigner`.
 *
 * web3.js 4 has no fallback provider. So this file keeps one `Web3` per
 * endpoint, most reliable first, and tries them in order: a read moves to the
 * next endpoint when the one before it throws.
 *
 * 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 Hex, zeroAddress } from 'viem';
import { Web3 } from 'web3';
import {
  type ChainAccess,
  createClientLookup,
  endpointList,
  type ReceiptOutcome,
  type RpcUrlByChainId,
  requireClientWith,
  sleep,
  toTransactionHash,
  type WalletSigner,
} from './shared.js';

/** Runs one read on a chain's endpoints in order, and answers with the first that does not throw. */
export type Web3Reader = <T>(chainId: number, read: (web3: Web3) => Promise<T>) => Promise<T>;

/**
 * The clients of the search and the planner, and an ordered list of `Web3`
 * instances per chain for your own reads.
 *
 * @param rpcUrlByChainId - your endpoints for each chain, most reliable first
 * @returns the viem lookups and the web3.js reader
 */
export const web3Clients = (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 web3.js. It has no
  // fallback provider, so keep one Web3 per endpoint and try them in order.
  const web3ListByChainId = new Map(
    [...rpcUrlByChainId].map(([chainId, urls]) => [chainId, endpointList(urls).map((url) => new Web3(url))]),
  );
  const readWithFallback: Web3Reader = async (chainId, read) => {
    let lastError: unknown = new Error(`the wallet has no RPC endpoint for chain ${chainId}`);
    for (const web3 of web3ListByChainId.get(chainId) ?? []) {
      try {
        return await read(web3);
      } catch (error) {
        lastError = error;
      }
    }
    throw lastError;
  };
  // #endregion clients
  return { clientForChain, requireClient, readWithFallback };
};

/**
 * The signer, on one wallet-connected `Web3` per chain.
 *
 * @param options.address - the account that signs
 * @param options.web3ByChainId - a `Web3` for each chain, such as `new Web3(window.ethereum)` after the wallet switched to it
 * @returns the signer
 */
export const web3Signer = (options: {
  readonly address: Hex;
  readonly web3ByChainId: ReadonlyMap<number, Web3>;
}): WalletSigner => {
  const { address, web3ByChainId } = options;
  // #region signer
  const signer: WalletSigner = {
    address,
    sendTransaction: (request) =>
      new Promise((resolve, reject) => {
        const web3 = web3ByChainId.get(request.chainId);
        if (web3 === undefined) return reject(new Error(`no web3 for chain ${request.chainId}`));
        // `sendTransaction` returns a PromiEvent. Awaiting it gives the mined
        // receipt. The `transactionHash` event fires first, and the signer resolves with it.
        web3.eth
          .sendTransaction({
            from: request.from,
            to: request.to,
            data: request.data,
            value: request.value,
            ...(request.gas === undefined ? {} : { gas: request.gas }),
          })
          .on('transactionHash', (hash) => resolve(toTransactionHash(String(hash))))
          .on('error', reject);
      }),
  };
  // #endregion signer
  return signer;
};

/** The two token reads, as an ABI that web3.js types. */
const erc20ReadAbi = [
  {
    type: 'function',
    name: 'allowance',
    stateMutability: 'view',
    inputs: [
      { name: 'owner', type: 'address' },
      { name: 'spender', type: 'address' },
    ],
    outputs: [{ name: '', type: 'uint256' }],
  },
  {
    type: 'function',
    name: 'balanceOf',
    stateMutability: 'view',
    inputs: [{ name: 'owner', type: 'address' }],
    outputs: [{ name: '', type: 'uint256' }],
  },
] as const;

/** Checks that a contract call answered a number. web3.js types the answer loosely. */
const asBigInt = (value: unknown, method: string): bigint => {
  if (typeof value !== 'bigint') throw new Error(`${method} did not answer a number`);
  return value;
};

/**
 * The chain reads, on the web3.js reader.
 *
 * @param readWithFallback - the reader from {@link web3Clients}
 * @returns the chain reads
 */
export const web3ChainAccess = (readWithFallback: Web3Reader): ChainAccess => {
  // #region allowance
  const readAllowance: AllowanceReader = (chainId, token, owner, spender) =>
    readWithFallback(chainId, async (web3) => {
      const value: unknown = await new web3.eth.Contract(erc20ReadAbi, token).methods.allowance(owner, spender).call();
      return asBigInt(value, 'allowance');
    });
  // #endregion allowance

  // #region receipt
  // web3.js 4 has no call that waits for a receipt, so poll for it.
  const waitForReceipt = async (request: { chainId: number; hash: Hex }): Promise<ReceiptOutcome> => {
    for (;;) {
      const receipt = await readWithFallback(request.chainId, (web3) => web3.eth.getTransactionReceipt(request.hash));
      // web3.js answers null while the transaction is not mined, although its type does not say so.
      if (receipt !== null && receipt !== undefined) return BigInt(receipt.status) === 1n ? 'success' : 'reverted';
      await sleep(4_000);
    }
  };
  // #endregion receipt

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

  return {
    readAllowance,
    waitForReceipt,
    originReaderFor,
    readBalance: ({ chainId, token, owner }) =>
      readWithFallback(chainId, async (web3) => {
        if (token.toLowerCase() === zeroAddress) return web3.eth.getBalance(owner);
        const value: unknown = await new web3.eth.Contract(erc20ReadAbi, token).methods.balanceOf(owner).call();
        return asBigInt(value, 'balanceOf');
      }),
  };
};