From 01621b85704306b12f64628aae7ac60acde5e1e1 Mon Sep 17 00:00:00 2001 From: Kaylee George <62825936+kayleegeorge@users.noreply.github.com> Date: Fri, 30 Aug 2024 16:05:14 -0700 Subject: [PATCH] common: add viem client common functions (#1299) --- packages/daimo-common/src/index.ts | 1 + packages/daimo-common/src/viemClient.ts | 64 +++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 packages/daimo-common/src/viemClient.ts diff --git a/packages/daimo-common/src/index.ts b/packages/daimo-common/src/index.ts index db26a25b6..f4d9b1b95 100644 --- a/packages/daimo-common/src/index.ts +++ b/packages/daimo-common/src/index.ts @@ -27,3 +27,4 @@ export * from "./chain"; export * from "./retryBackoff"; export * from "./cctp"; export * from "./sendPair"; +export * from "./viemClient"; diff --git a/packages/daimo-common/src/viemClient.ts b/packages/daimo-common/src/viemClient.ts new file mode 100644 index 000000000..4c7f87c01 --- /dev/null +++ b/packages/daimo-common/src/viemClient.ts @@ -0,0 +1,64 @@ +import { extractChain, Chain } from "viem"; +import { + mainnet, + sepolia, + base, + optimism, + polygon, + baseSepolia, + arbitrum, + arbitrumSepolia, + optimismSepolia, + avalanche, + avalancheFuji, +} from "viem/chains"; + +/** Retrieve the Viem chain config for a given chainId. */ +export function getViemChainById(chainId: number): Chain { + if (!supportedChainIds.includes(chainId)) + throw new Error(`Unsupported chainId ${chainId}`); + + return extractChain({ + chains: [ + mainnet, + sepolia, + polygon, + arbitrum, + arbitrumSepolia, + base, + baseSepolia, + optimism, + optimismSepolia, + avalanche, + avalancheFuji, + ], + id: chainId as any, + }); +} + +/** Get the RPC URL for a given chainId. */ +export function getAlchemyTransportUrl(chainId: number, alchemyApiKey: string) { + const network = alchemyChainNames[chainId]; + if (!network) { + throw new Error(`Invalid chainId: ${chainId}`); + } + const alchemyRpcUrl = `https://${network}.g.alchemy.com/v2/${alchemyApiKey}`; + return alchemyRpcUrl; +} + +/** + * Mapping of chainID to Alchemy network name for RPC URLs. + * Note: Avax is not supported by Alchemy, nor do we support it. + */ +const alchemyChainNames: Record = { + [mainnet.id]: "eth-mainnet", + [sepolia.id]: "eth-sepolia", + [polygon.id]: "polygon-mainnet", + [arbitrum.id]: "arb-mainnet", + [arbitrumSepolia.id]: "arb-sepolia", + [base.id]: "base-mainnet", + [baseSepolia.id]: "base-sepolia", + [optimism.id]: "opt-mainnet", + [optimismSepolia.id]: "opt-sepolia", +}; +const supportedChainIds = Object.keys(alchemyChainNames).map(Number);