shared.ts

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

/**
 * Helpers both wallet examples share: the signer the examples expect, the
 * chain reads your own library makes ({@link ChainAccess}), one viem client per
 * chain for the search and the planner, a sender that honours
 * `waitForReceipt`, and a status poller.
 *
 * The packages do not depend on a wallet library, so the signer and the chain
 * reads are small interfaces. The adapter files fill them with viem,
 * WalletConnect, ethers or web3.js. The search and the planner still read
 * through viem clients, because viem is their peer dependency.
 *
 * These files are typechecked only. They are never run against a live chain.
 */
import {
  type FetchTransferStatusOptions,
  fetchTransferStatus,
  type OriginChainReader,
  type TransferSource,
  type TransferStatus,
} from '@gibs/bridge-indexer';
import type { AllowanceReader, PlannedTx } from '@gibs/bridge-sdk/execution';
import { type Chain, createPublicClient, fallback, type Hex, http, type PublicClient, type Transport } from 'viem';
import { mainnet, pulsechain } from 'viem/chains';

/** One transaction for the wallet to sign and broadcast. */
export type WalletTransactionRequest = {
  readonly chainId: number;
  readonly from: Hex;
  readonly to: Hex;
  readonly data: Hex;
  readonly value: bigint;
  /** Set only when the plan names a gas limit. Otherwise the wallet estimates it. */
  readonly gas?: bigint;
};

/**
 * The signer the examples expect. It broadcasts one transaction on the chain
 * the request names and resolves with the transaction hash, before the
 * transaction is mined. The examples wait for receipts themselves, through
 * {@link ChainAccess}, only where the plan says `waitForReceipt`.
 *
 * Each adapter file builds one: `adapter-viem.ts`, `adapter-walletconnect.ts`,
 * `adapter-ethers.ts` and `adapter-web3.ts`.
 */
export type WalletSigner = {
  readonly address: Hex;
  readonly sendTransaction: (request: WalletTransactionRequest) => Promise<Hex>;
};

/** How a mined transaction ended. */
export type ReceiptOutcome = 'success' | 'reverted';

/** One balance to read: a token, or the native coin when the token is the zero address. */
export type BalanceRequest = {
  readonly chainId: number;
  readonly token: string;
  readonly owner: Hex;
};

/**
 * The chain reads the examples make through your own library. Each adapter
 * file builds one: `viemChainAccess`, `walletConnectChainAccess`,
 * `ethersChainAccess` and `web3ChainAccess`.
 */
export type ChainAccess = {
  /** The allowance reader `planCandidateExecution` takes. */
  readonly readAllowance: AllowanceReader;
  /** What an account holds. The examples read it before and after a crossing. */
  readonly readBalance: (request: BalanceRequest) => Promise<bigint>;
  /** Resolves once the transaction is mined. */
  readonly waitForReceipt: (request: { readonly chainId: number; readonly hash: Hex }) => Promise<ReceiptOutcome>;
  /** The `originClient` that `fetchTransferStatus` takes, for one chain. */
  readonly originReaderFor: (chainId: number) => OriginChainReader;
};

/**
 * Checks that a library handed back a transaction hash. ethers and web3.js
 * type a hash as a plain string.
 *
 * @param value - the hash the library returned
 * @returns the hash, typed as hex
 * @throws when the value is not 32 bytes of hex
 */
export const toTransactionHash = (value: string): Hex => {
  if (!/^0x[0-9a-fA-F]{64}$/.test(value)) throw new Error(`not a transaction hash: ${value}`);
  return value as Hex;
};

/** The endpoints of one chain as a list, most reliable first. */
export const endpointList = (urls: string | readonly string[]): readonly string[] =>
  typeof urls === 'string' ? [urls] : urls;

/**
 * The wallet's own RPC endpoints for each chain it supports, by decimal chain
 * id, most reliable first. One endpoint or several: several share one client
 * through viem's `fallback`, which is what the Gibs interface does.
 */
export type RpcUrlByChainId = ReadonlyMap<number, string | readonly string[]>;

/** The chains these examples touch. A real wallet lists every chain it supports. */
const viemChainById: ReadonlyMap<number, Chain> = new Map<number, Chain>([
  [mainnet.id, mainnet],
  [pulsechain.id, pulsechain],
]);

/**
 * The transport for a chain's endpoints: plain `http` for one, `fallback` over
 * all of them, in the order given, for several.
 *
 * viem's `fallback` moves on only when an endpoint fails with an HTTP error or
 * an unreadable answer, so put the most reliable endpoint first.
 *
 * @param urls - one endpoint, or several, most reliable first
 * @returns the transport for that chain's client
 */
const transportFor = (urls: string | readonly string[]): Transport => {
  const list = endpointList(urls);
  if (list.length === 1) return http(list[0]);
  return fallback(list.map((url) => http(url)));
};

/**
 * Builds one viem public client per chain, from the wallet's own endpoints.
 * A chain with several endpoints gets one client that falls back across them.
 * Never the demo endpoints (`demoRpcUrls` in `@gibs/bridge-sdk/chains`).
 *
 * @param rpcUrlByChainId - the wallet's endpoints for each chain
 * @returns a lookup that answers null for a chain the wallet has no endpoint for
 */
export const createClientLookup = (
  rpcUrlByChainId: RpcUrlByChainId,
): ((chainId: number) => PublicClient | null) => {
  const clients = new Map<number, PublicClient>();
  for (const [chainId, urls] of rpcUrlByChainId) {
    const chain = viemChainById.get(chainId);
    if (chain === undefined) continue;
    if (typeof urls !== 'string' && urls.length === 0) continue;
    clients.set(chainId, createPublicClient({ chain, transport: transportFor(urls) }));
  }
  return (chainId) => clients.get(chainId) ?? null;
};

/**
 * Wraps a client lookup so that a missing chain fails fast with a clear message.
 *
 * @param clientForChain - the lookup from {@link createClientLookup}
 * @returns a lookup that throws for a chain with no client
 */
export const requireClientWith =
  (clientForChain: (chainId: number) => PublicClient | null) =>
  (chainId: number): PublicClient => {
    const client = clientForChain(chainId);
    if (client === null) throw new Error(`the wallet has no RPC endpoint for chain ${chainId}`);
    return client;
  };

/** One transaction the sender broadcast, with its hash. */
export type SentTransaction = { readonly transaction: PlannedTx; readonly hash: Hex };

/**
 * Sends a plan's transactions in order.
 *
 * - It waits for a receipt only where the plan sets `waitForReceipt`.
 * - A receipt is not arrival. When the next transaction is on another chain,
 *   it calls `waitForArrival` with the transaction that started the crossing,
 *   and sends nothing more until that resolves.
 *
 * @param options.transactions - the plan's transactions, in plan order
 * @param options.signer - the wallet's signer
 * @param options.waitForReceipt - from your {@link ChainAccess}
 * @param options.waitForArrival - resolves once the crossing's funds arrived on the next chain
 * @returns every transaction sent, with its hash, in order
 * @throws when a receipt reports a revert
 */
export const sendPlannedTransactions = async (options: {
  readonly transactions: readonly PlannedTx[];
  readonly signer: WalletSigner;
  readonly waitForReceipt: ChainAccess['waitForReceipt'];
  readonly waitForArrival: (crossing: SentTransaction) => Promise<void>;
}): Promise<readonly SentTransaction[]> => {
  const { transactions, signer, waitForReceipt, waitForArrival } = options;
  const sent: SentTransaction[] = [];
  for (const [index, transaction] of transactions.entries()) {
    const hash = await signer.sendTransaction({
      chainId: transaction.chainId,
      from: signer.address,
      to: transaction.to,
      data: transaction.data,
      value: transaction.value,
      ...(transaction.gasLimit === null ? {} : { gas: transaction.gasLimit }),
    });
    sent.push({ transaction, hash });
    if (!transaction.waitForReceipt) continue;
    const outcome = await waitForReceipt({ chainId: transaction.chainId, hash });
    if (outcome !== 'success') {
      throw new Error(
        `${transaction.kind} transaction ${hash} reverted on chain ${transaction.chainId}`,
      );
    }
    const next = transactions[index + 1];
    if (next !== undefined && next.chainId !== transaction.chainId) {
      await waitForArrival({ transaction, hash });
    }
  }
  return sent;
};

/**
 * Waits for a time, or rejects when the signal fires.
 *
 * @param milliseconds - how long to wait
 * @param signal - cancels the wait
 */
export const sleep = (milliseconds: number, signal?: AbortSignal): Promise<void> =>
  new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const timer = setTimeout(resolve, milliseconds);
    signal?.addEventListener(
      'abort',
      () => {
        clearTimeout(timer);
        reject(signal.reason);
      },
      { once: true },
    );
  });

/** A transfer that ended badly. Waiting longer does not change it. */
export class TransferEndedError extends Error {
  constructor(readonly status: TransferStatus) {
    super(`the transfer ended as ${status.state}`);
    this.name = 'TransferEndedError';
  }
}

/**
 * Polls `fetchTransferStatus` until `isDone` accepts an answer.
 *
 * @param options.source - the transaction that started the transfer
 * @param options.statusOptions - passed through to `fetchTransferStatus`
 * @param options.isDone - true for the answer the caller waits for
 * @param options.intervalMs - the pause between polls
 * @returns the first answer `isDone` accepts
 * @throws {TransferEndedError} on `failed` or `stranded`
 */
export const waitForTransferStatus = async (options: {
  readonly source: TransferSource;
  readonly statusOptions: FetchTransferStatusOptions;
  readonly isDone: (status: TransferStatus) => boolean;
  readonly intervalMs: number;
}): Promise<TransferStatus> => {
  const { source, statusOptions, isDone, intervalMs } = options;
  for (;;) {
    const status = await fetchTransferStatus(source, statusOptions);
    if (status.state === 'failed' || status.state === 'stranded')
      throw new TransferEndedError(status);
    if (isDone(status)) return status;
    await sleep(intervalMs, statusOptions.signal);
  }
};

/**
 * The unix-seconds deadline a PulseX swap carries, `seconds` from now.
 *
 * @param seconds - how long the swap stays valid
 * @returns the deadline
 */
export const deadlineIn = (seconds: number): bigint =>
  BigInt(Math.floor(Date.now() / 1000) + seconds);