@funkit/fun-relay
Version:
4 lines • 129 kB
Source Map (JSON)
{
"version": 3,
"sources": ["../src/bitcoin.ts", "../src/client.ts", "../src/types.ts", "../src/constants.ts", "../src/execution.ts", "../src/fees.ts", "../src/price.ts", "../src/utils.ts", "../src/currency.ts", "../src/quote.ts", "../src/solana.ts", "../src/tron.ts", "../src/assets.ts", "../src/dynamicRoutes/lighter.ts", "../src/dynamicRoutes/abi.ts", "../src/dynamicRoutes/consts.ts", "../src/dynamicRoutes/utils.ts", "../src/dynamicRoutes/index.ts"],
"sourcesContent": ["import { adaptBitcoinWallet } from '@relayprotocol/relay-bitcoin-wallet-adapter'\nimport type { AdaptedWallet } from '@relayprotocol/relay-sdk'\n\ntype Base16 =\n | '0'\n | '1'\n | '2'\n | '3'\n | '4'\n | '5'\n | '6'\n | '7'\n | '8'\n | '9'\n | 'a'\n | 'b'\n | 'c'\n | 'd'\n | 'e'\n | 'f'\n\nexport type BitcoinAddress =\n | `1${string}`\n | `3${string}`\n | `bc1${string}`\n | `bc1p${string}`\n\nexport type BitcoinTxHash = `${Base16}${string}`\n\nexport type BitcoinWallet = {\n address(): Promise<BitcoinAddress>\n vmType: 'bvm'\n} & AdaptedWallet\n\n/** bitcoinjs-lib Psbt */\nexport type BitcoinPsbt = Parameters<\n Parameters<typeof adaptBitcoinWallet>[1]\n>[1]\n\nexport type BitcoinPsbtDynamicParams = Parameters<\n Parameters<typeof adaptBitcoinWallet>[1]\n>[2]\n\n/** bitcoinjs-lib Signer */\nexport type BitcoinSigner = Parameters<BitcoinPsbt['signAllInputs']>[0]\n\nexport function getBitcoinWallet(\n walletAddress: BitcoinAddress,\n signPsbt: (\n address: BitcoinAddress,\n psbt: BitcoinPsbt,\n dynamicParams: BitcoinPsbtDynamicParams,\n ) => Promise<string>,\n): BitcoinWallet {\n return adaptBitcoinWallet(walletAddress, (address, psbt, dynamicParams) =>\n signPsbt(address as BitcoinAddress, psbt, dynamicParams),\n ) as BitcoinWallet\n}\n\nexport function getBitcoinWalletFromSigner(\n walletAddress: BitcoinAddress,\n signer: BitcoinSigner,\n): BitcoinWallet {\n return getBitcoinWallet(walletAddress, async (_, psbt) =>\n psbt.signAllInputs(signer).toBase64(),\n )\n}\n", "// Reach relay-sdk's runtime exports through a namespace import, not named\n// imports. Some integrator bundlers fail to bind individual named exports from\n// relay-sdk's CJS build (dydx hit `convertViemChainToRelayChain is not a\n// function`); a namespace read resolves off the live module object and is\n// robust to that CJS/ESM interop gap.\nimport * as relaySdk from '@relayprotocol/relay-sdk'\nimport type {\n RelayClient,\n RelayClientOptions,\n log,\n} from '@relayprotocol/relay-sdk'\nimport type { Chain } from 'viem'\nimport {\n RELAY_LIGHTER_CHAIN_ID_NUMBER,\n RELAY_SOLANA_CHAIN_ID_NUMBER,\n} from './constants'\nimport type { Logger } from './types'\n\nexport type InitializeRelayClientParams = Omit<\n RelayClientOptions,\n 'baseApiUrl' | 'chains' | 'logger'\n> & {\n chains: Chain[]\n logger: Logger\n}\n\n/**\n * Initializes a global instance of the RelayClient\n * https://docs.relay.link/references/sdk/createClient\n */\nexport function initializeRelayClient({\n chains,\n logger,\n ...options\n}: InitializeRelayClientParams): RelayClient {\n const relayLogger = (\n message: Parameters<typeof log>[0],\n level: relaySdk.LogLevel,\n ) => {\n const logType: keyof Logger =\n level === relaySdk.LogLevel.Error ? 'error' : 'info'\n const logMessage = message[0] ?? 'Unknown error'\n const logData = message.length > 1 ? message.slice(1) : undefined\n\n logger[logType]('[RelayClient]', {\n message: logMessage,\n relayLogLevel: level,\n ...(logData && { data: logData }),\n })\n }\n\n // relay-sdk v6 accepts the logger in createClient() directly, so the prior\n // post-creation configure() workaround (needed up to v5) is gone.\n return relaySdk.createClient({\n ...options,\n baseApiUrl: relaySdk.MAINNET_RELAY_API,\n logLevel: options.logLevel ?? relaySdk.LogLevel.Verbose,\n logger: relayLogger,\n chains: [\n ...chains.map(relaySdk.convertViemChainToRelayChain),\n {\n id: RELAY_SOLANA_CHAIN_ID_NUMBER,\n name: 'Solana',\n displayName: 'Solana',\n },\n {\n id: RELAY_LIGHTER_CHAIN_ID_NUMBER,\n name: 'Lighter',\n displayName: 'Lighter',\n },\n ],\n })\n}\n\n/**\n * Gets the global instance of the RelayClient\n */\nexport function getRelayClient(): RelayClient {\n const client = relaySdk.getClient()\n\n if (!client) {\n throw new Error('Relay client is not defined')\n }\n\n return client\n}\n", "import { LogLevel } from '@relayprotocol/relay-sdk'\nimport type { Abi, Address, Hex } from 'viem'\n\nexport { LogLevel }\n\n// https://docs.relay.link/references/api/get-intents-status-v2\nexport interface RelayExecutionInfo {\n status: RelayExecutionStatus\n details: string\n /** Incoming transaction hashes */\n inTxHashes: string[]\n /** Outgoing transaction hashes */\n txHashes: string[]\n /** The last timestamp the data was updated in milliseconds */\n time: number\n originChainId: number\n destinationChainId: number\n}\n\n// https://docs.relay.link/references/api/get-token-price\nexport interface RelayTokenPriceInfo {\n price: number\n}\n\n//// The types below are duplicated from @funkit/api-base atm, but this package should be used in BE as well\n//// TODO: Are we fine with BE importing @funkit/api-base and (by extension) @funkit/utils?\n//// See https://linear.app/funxyz/issue/PE-1342/sdk-extract-domainsrelayts-to-a-new-package#comment-d487d533\n\nexport interface Logger {\n error(message: string, data?: object): void\n info(message: string, data?: object): void\n}\n\n// Reference: https://github.com/reservoirprotocol/relay-kit/blob/211c645f9702a3b459ff545aa4e2e9d536c38455/packages/sdk/src/types/Execute.ts#L54-L61\nexport enum RelayExecutionStatus {\n DELAYED = 'delayed',\n FAILURE = 'failure',\n PENDING = 'pending',\n REFUND = 'refund',\n SUCCESS = 'success',\n WAITING = 'waiting',\n UNKNOWN = 'unknown',\n}\n\nexport interface BaseApiFunkitCheckoutActionParams {\n contractAddress: Address\n value?: bigint\n}\n\ninterface ApiFunkitCheckoutActionParamsRawCalldata extends BaseApiFunkitCheckoutActionParams {\n rawCalldata: Hex\n contractAbi?: never\n functionName?: never\n functionArgs?: never\n}\ninterface ApiFunkitCheckoutActionParamsContractAbi extends BaseApiFunkitCheckoutActionParams {\n rawCalldata?: never\n contractAbi: Abi\n functionName: string\n functionArgs: unknown[]\n}\n\nexport type ApiFunkitCheckoutActionParams =\n | ApiFunkitCheckoutActionParamsRawCalldata\n | ApiFunkitCheckoutActionParamsContractAbi\n\nexport enum CheckoutRefundState {\n INITIATED = 'INITIATED',\n ERROR = 'ERROR',\n REFUNDED = 'REFUNDED',\n PROCEEDED = 'PROCEEDED',\n WAITING_FOR_FULFILLMENT = 'WAITING_FOR_FULFILLMENT',\n FULFILLED = 'FULFILLED',\n}\n\n// Reference from api server: https://github.com/fun-xyz/fun-api-server/blob/main/src/tables/FunWalletCheckout.ts#L11C1-L21C2\nexport enum CheckoutState {\n // In-progress States\n FROM_UNFUNDED = 'FROM_UNFUNDED',\n FROM_FUNDED = 'FROM_FUNDED',\n FROM_POOLED = 'FROM_POOLED',\n TO_UNFUNDED = 'TO_UNFUNDED',\n TO_FUNDED = 'TO_FUNDED',\n TO_POOLED = 'TO_POOLED',\n TO_READY = 'TO_READY',\n PENDING_RECEIVAL = 'PENDING_RECEIVAL',\n // Terminal States\n COMPLETED = 'COMPLETED',\n CHECKOUT_ERROR = 'CHECKOUT_ERROR',\n EXPIRED = 'EXPIRED',\n CANCELLED = 'CANCELLED',\n}\n\n// The response of the actual /checkout/quote api\nexport type CheckoutApiQuoteResponse = {\n quoteId: string\n estTotalFromAmountBaseUnit: string\n estSubtotalFromAmountBaseUnit: string\n estFeesFromAmountBaseUnit: string\n fromTokenAddress: Address\n estFeesUsd: number\n estSubtotalUsd: number\n estTotalUsd: number\n estCheckoutTimeMs: number\n estMarketMakerGasUsd: number\n lpFeePercentage: number\n lpFeeUsd: number\n}\n\n// The formatted response quote interface from the core sdk\nexport type CheckoutQuoteResponse = CheckoutApiQuoteResponse & {\n estTotalFromAmount: string\n estSubtotalFromAmount: string\n estFeesFromAmount: string\n\n // Any additional fields purely for frontend use\n metadata?: { [key: string]: unknown }\n}\n", "import type { Address } from 'viem'\nimport type { BitcoinAddress } from './bitcoin'\nimport type { SolanaAddress } from './solana'\nimport { RelayExecutionStatus } from './types'\n\n/**\n * Chain id that Relay uses to identify Bitcoin\n *\n * See https://docs.relay.link/references/sdk/adapters#how-can-i-use-an-adapter%3F\n */\nexport const RELAY_BITCOIN_CHAIN_ID_NUMBER = 8253038 // Why cannot Relay export this themselves... -.-\nexport const RELAY_BITCOIN_CHAIN_ID = `${RELAY_BITCOIN_CHAIN_ID_NUMBER}`\n\n/**\n * Chain id that Relay uses to identify Solana\n *\n * See https://docs.relay.link/references/sdk/adapters#how-can-i-use-an-adapter%3F\n */\nexport const RELAY_SOLANA_CHAIN_ID_NUMBER = 792703809 // Why cannot Relay export this themselves... -.-\nexport const RELAY_SOLANA_CHAIN_ID = `${RELAY_SOLANA_CHAIN_ID_NUMBER}`\n\nexport const FUN_SOLANA_CHAIN_ID_NUMBER = 1151111081099710\nexport const FUN_HYPERCORE_CHAIN_ID_NUMBER = 1337\n\nexport const RELAY_LIGHTER_CHAIN_ID_NUMBER = 3586256\nexport const RELAY_LIGHTER_CHAIN_ID = `${RELAY_LIGHTER_CHAIN_ID_NUMBER}`\n\nexport const RELAY_TRON_CHAIN_ID_NUMBER = 728126428\nexport const RELAY_TRON_CHAIN_ID = `${RELAY_TRON_CHAIN_ID_NUMBER}` as const\n\n/**\n * Fake address for a chain's native currency used by Funkit\n */\nexport const FUNKIT_NATIVE_TOKEN =\n '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' satisfies Address\n\n/**\n * Fake address for a chain's native currency used by Relay\n */\nexport const RELAY_NATIVE_TOKEN =\n '0x0000000000000000000000000000000000000000' satisfies Address\n\n/**\n * Fake address for Hypercore's native currency used by Relay. This is shorter than the default native token...\n */\nexport const RELAY_NATIVE_TOKEN_HYPERCORE =\n '0x00000000000000000000000000000000' satisfies Address\n\n/**\n * Fake address for Solana's native currency used by Relay\n */\nexport const RELAY_NATIVE_TOKEN_SOLANA =\n '11111111111111111111111111111111' satisfies SolanaAddress\n\n/**\n * Fake address for Bitcoin's native currency used by Relay\n */\nexport const RELAY_NATIVE_TOKEN_BITCOIN =\n 'bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8' satisfies BitcoinAddress\n\n/**\n * Fake address for Lighter's native currency used by Relay\n */\nexport const RELAY_LIGHTER_USDC_PERPS = '0'\nexport const RELAY_LIGHTER_USDC_SPOT = '3'\nexport const RELAY_LIGHTER_ETH_SPOT = '1'\n\nexport const RELAY_LIGHTER_FUN_ADDRESS_MAP = {\n '0x0000000000000000000000000000000000000000': RELAY_LIGHTER_USDC_PERPS,\n '0x0000000000000000000000000000000000000001': RELAY_LIGHTER_ETH_SPOT,\n '0x0000000000000000000000000000000000000003': RELAY_LIGHTER_USDC_SPOT,\n}\n\n/**\n * Wallet that receives the app fees collected by Relay\n * Prev: 0xb61562d83aEC43a050A06BED12Ac2bD8f9BFfd5E\n */\nexport const FUN_RELAY_REVENUE_WALLET =\n '0xdfd877679e95c1276c85801805b2c2ab8f4f4cf6' satisfies Address\n\n/**\n * Referred field in Relay quote\n */\nexport const FUN_RELAY_REFERRER = 'funxyz'\n\n/**\n * Buffer added to Relay's time estimate (which sometimes is 0)\n */\nexport const RELAY_QUOTE_CHECKOUT_TIME_BUFFER_MS = 25_000 // 25 seconds\n\nexport const RELAY_TERMINAL_STATUSES: RelayExecutionStatus[] = [\n RelayExecutionStatus.REFUND,\n RelayExecutionStatus.FAILURE,\n RelayExecutionStatus.SUCCESS,\n]\n\nexport const SUSHI_ORG_ID = 'fysix7gj5j'\nexport const HYPERSWAP_ORG_ID = '2ejzdxhfge'\n", "import {\n type AdaptedWallet,\n MAINNET_RELAY_API,\n type ProgressData,\n} from '@relayprotocol/relay-sdk'\nimport type { Address, Hex, WalletClient } from 'viem'\nimport type { BitcoinAddress, BitcoinTxHash, BitcoinWallet } from './bitcoin'\nimport { getRelayClient } from './client'\nimport type {\n RELAY_BITCOIN_CHAIN_ID,\n RELAY_LIGHTER_CHAIN_ID,\n RELAY_SOLANA_CHAIN_ID,\n RELAY_TRON_CHAIN_ID,\n} from './constants'\nimport type { LighterAccountIndex, LighterWallet } from './lighter'\nimport type { RelayQuoteResult } from './quote'\nimport type { SolanaAddress, SolanaTxHash, SolanaWallet } from './solana'\nimport type { TronAddress, TronTxHash, TronWallet } from './tron'\nimport type { Logger, RelayExecutionInfo } from './types'\n\nexport type RelayExecutionStep = ProgressData['currentStep'] & {}\n\nexport const RELAY_VM_TYPES = [\n 'bvm',\n 'evm',\n 'hypevm',\n 'svm',\n 'lvm',\n 'tvm',\n] as const\n\nexport type RelayVmType = (typeof RELAY_VM_TYPES)[number]\n\nexport type RelayAddress<VmType extends RelayVmType = RelayVmType> = {\n bvm: BitcoinAddress\n evm: Address\n hypevm: Address\n svm: SolanaAddress\n lvm: LighterAccountIndex\n tvm: TronAddress\n}[VmType]\n\nexport type RelayChainId<VmType extends RelayVmType = RelayVmType> = {\n bvm: typeof RELAY_BITCOIN_CHAIN_ID\n evm: string\n hypevm: string\n svm: typeof RELAY_SOLANA_CHAIN_ID\n lvm: typeof RELAY_LIGHTER_CHAIN_ID\n tvm: typeof RELAY_TRON_CHAIN_ID\n}[VmType]\n\nexport type RelayTxHash<VmType extends RelayVmType = RelayVmType> = {\n bvm: BitcoinTxHash\n evm: Hex\n hypevm: Hex\n svm: SolanaTxHash\n lvm: Hex\n tvm: TronTxHash\n}[VmType]\n\nexport type RelayWallet<VmType extends RelayVmType = RelayVmType> = {\n bvm: BitcoinWallet\n evm: WalletClient | (AdaptedWallet & { vmType: 'evm' })\n hypevm: AdaptedWallet & { vmType: 'hypevm' }\n svm: SolanaWallet\n lvm: LighterWallet\n tvm: TronWallet\n}[VmType]\n\nexport interface ExecuteRelayQuoteParams<VmType extends RelayVmType> {\n logger: Logger\n onError: (error: Error) => Promise<void>\n onProgress?: (step: RelayExecutionStep | null) => void\n /**\n * Fired when all *input* transactions are confirmed on-chain.\n */\n onTransactionConfirmed?: (txHash: RelayTxHash<VmType>) => Promise<void>\n /**\n * Fired as soon as user has *signed* all input transactions, but before they are confirmed on-chain.\n *\n * After this event, no more action should be needed from the user.\n * However, it is possible that the transactions will be rejected and the execution will NOT continue.\n */\n onUserActionsCompleted?: (txHash: RelayTxHash<VmType>) => Promise<void>\n relayQuote: RelayQuoteResult<VmType>\n walletClient: RelayWallet<VmType>\n\n /**\n * Type of transaction being executed\n *\n * - `'standard'` - regular transaction (default)\n * - `'erc4337'` - ERC-4337 smart wallet transaction\n */\n transactionType?: 'standard' | 'erc4337'\n}\n\ninterface DefaultTxHashParams {\n transactionType: 'standard' | 'erc4337'\n logger: Logger\n\n // This typing is not correct but that's what Relay returns\n // Read Loic's PR #2565 for more details\n txHashes: {\n txHash: string\n }[]\n}\n\n/**\n * Default mode. Supported for all VmTypes.\n * Uses `txHashes[0].txHash` property from onProgress callback to\n * extract the txHash.\n *\n * Used as a fallback for receipt mode\n */\ninterface TxHashesGetTxHashParams extends DefaultTxHashParams {\n transactionType: 'standard'\n steps?: unknown[] // steps is not used in this mode\n}\n\n/**\n * This is solely for ERC-4337 smart wallet transactions\n *\n * Uses `steps[0].items[0].receipt.transactionHash` property from onProgress callback\n * to extract the txHash\n *\n * Only used in smart wallet (account abstraction, ERC-4337) transactions\n */\ninterface ReceiptGetTxHashParams extends DefaultTxHashParams {\n transactionType: 'erc4337'\n steps: {\n items: {\n receipt?: RelayExecutionStep['items'][number]['receipt']\n }[]\n }[]\n}\n\ntype GetTxHashParams = TxHashesGetTxHashParams | ReceiptGetTxHashParams\n\nfunction getTxHash<VmType extends RelayVmType>({\n logger,\n transactionType,\n txHashes,\n steps,\n}: GetTxHashParams): RelayTxHash<VmType> {\n const logPrefix = 'getTxHash'\n const logProps = {\n logger,\n transactionType,\n txHashes,\n steps,\n }\n logger.info(`${logPrefix}:started`, logProps)\n\n const getTxHashFromTxHashes = () => {\n // From PR #2565 by Lo\u00EFc Nicolas\n // Use first txHash as the main txHash in fun DE table\n // Bad surprise from Relay: txHash may be an object, this is not present in their typing...\n const rawTxHashWithUnreliableTyping = txHashes[0]?.txHash as\n | RelayTxHash<VmType>\n | { id: RelayTxHash<VmType> }\n\n // rawTxHashWithUnreliableTyping cannot be null so typeof check is enough\n const txHash =\n typeof rawTxHashWithUnreliableTyping === 'object'\n ? rawTxHashWithUnreliableTyping.id\n : rawTxHashWithUnreliableTyping\n logger.info(`${logPrefix}:txHashesMode`, {\n ...logProps,\n txHash,\n })\n if (!txHash) {\n logger.error(`${logPrefix}:txHashesMode:noTxHash`, {\n ...logProps,\n txHash,\n })\n }\n return txHash\n }\n\n const getTxHashFromReceipt = () => {\n if (transactionType !== 'erc4337') {\n throw new Error(\n `Transaction type ${transactionType} is not supported for receipt mode`,\n )\n }\n\n const receipt = steps?.[0]?.items?.[0]?.receipt\n\n // This one excludes SVM and Sui receipts (which are not supported for this mode)\n const txHash =\n receipt && 'transactionHash' in receipt\n ? receipt.transactionHash\n : undefined\n logger.info(`${logPrefix}:receiptMode`, {\n ...logProps,\n txHash,\n })\n return txHash as RelayTxHash<VmType>\n }\n\n switch (transactionType) {\n // txHashes mode is the default mode\n case 'standard': {\n const txHash = getTxHashFromTxHashes()\n return txHash\n }\n // receipt mode is used for ERC-4337 smart wallet transactions\n // unsupported for Solana Virtual Machine (SVM) or Sui (sui) transactions\n case 'erc4337': {\n const txHash = getTxHashFromReceipt()\n if (!txHash) {\n logger.info(`${logPrefix}:receiptMode:fallbackToTxHashes`, {\n ...logProps,\n txHash,\n })\n return getTxHashFromTxHashes()\n }\n\n return txHash\n }\n default: {\n throw new Error(`Unknown transactionType: ${transactionType}`)\n }\n }\n}\n\nexport async function executeRelayQuote<VmType extends RelayVmType>({\n logger,\n onError,\n onProgress,\n onTransactionConfirmed,\n onUserActionsCompleted,\n relayQuote,\n walletClient,\n transactionType = 'standard',\n}: ExecuteRelayQuoteParams<VmType>): Promise<void> {\n let isUserActionsCompleted = false\n let isTransactionConfirmed = false\n\n await getRelayClient().actions.execute({\n quote: relayQuote,\n wallet: walletClient,\n onProgress: async ({\n steps,\n fees,\n breakdown,\n currentStep,\n currentStepItem,\n txHashes,\n details,\n error,\n }) => {\n const logPrefix = 'onRelayProgress'\n logger.info(`${logPrefix}:params`, {\n steps,\n currentStep,\n fees,\n breakdown,\n currentStepItem,\n txHashes,\n details,\n error,\n })\n\n onProgress?.(currentStep ?? null)\n\n if (error) {\n logger.info(`${logPrefix}:errorDetected`, error)\n await onError(error).catch((e) => {\n logger.error(`${logPrefix}:onErrorFailed`, e)\n })\n } else if (txHashes?.length) {\n const txHash = getTxHash<VmType>({\n transactionType,\n logger,\n txHashes,\n steps,\n })\n\n if (\n // Call onUserActionsCompleted only once\n !isUserActionsCompleted &&\n steps.every((step) =>\n step.items.every(\n // 'completed' - catch-all for items marked completed with no other info\n // - e.g. Batched items will not have txHash but will have their item marked 'complete'\n // 'pending' - for origin chain transactions that have been included on chain\n // - may sometimes be skipped, hence the need for 'submitted' condition below\n // 'submitted' - for destination chain transactions that have been submitted to the network\n // receipt - is present when the transaction has been mined/confirmed\n // Ensure onUserActionsCompleted is always called before onTransactionConfirmed\n (item) =>\n item.status === 'complete' ||\n item.checkStatus === 'pending' ||\n item.checkStatus === 'submitted' ||\n item.receipt !== undefined,\n ),\n )\n ) {\n logger.info(`${logPrefix}:onUserActionsCompleted`, txHashes)\n isUserActionsCompleted = true\n\n try {\n await onUserActionsCompleted?.(txHash)\n } catch (e) {\n logger.error(\n `${logPrefix}:onUserActionsCompletedFailed`,\n e as Error,\n )\n }\n }\n\n if (\n // Call onTransactionConfirmed only once\n !isTransactionConfirmed &&\n steps.every((step) =>\n step.items.every((item) => item.status === 'complete'),\n )\n ) {\n logger.info(`${logPrefix}:onTransactionConfirmed`, txHashes)\n isTransactionConfirmed = true\n\n try {\n await onTransactionConfirmed?.(txHash)\n } catch (e) {\n logger.error(\n `${logPrefix}:onTransactionConfirmedFailed`,\n e as Error,\n )\n }\n }\n }\n },\n })\n}\n\nexport async function getRelayExecutionInfo(\n requestId: string,\n apiKey: string,\n): Promise<RelayExecutionInfo> {\n const url = `${MAINNET_RELAY_API}/intents/status/v2?requestId=${requestId}`\n const response = await fetch(url, {\n headers: { 'x-api-key': apiKey },\n })\n if (!response.ok) {\n throw Error(response.statusText)\n }\n\n const data = await response.json()\n return data as RelayExecutionInfo\n}\n", "import type { CallFees } from '@relayprotocol/relay-sdk'\nimport type { Logger } from './types'\n\nexport interface FunRelayFeeItem {\n b: number\n v: number\n config: {\n options: Record<string, unknown>\n }\n headers: Record<string, string>\n}\n\nexport async function getFunRelayFees({\n clientId,\n estUsdValue,\n fromTokenAddress,\n fromChainId,\n recipientAddress,\n senderAddress,\n toTokenAddress,\n toChainId,\n usePermit,\n}: {\n clientId: string\n estUsdValue: number\n fromTokenAddress: string\n fromChainId: string\n recipientAddress: string | undefined\n senderAddress: string | undefined\n toTokenAddress: string\n toChainId: string\n /**\n * Optional explicit user preference for the source-side authorization\n * step. Forwarded to frog as a query param so its `getUsePermit` can\n * honor the FE toggle's choice. When omitted, frog falls back to its\n * legacy auto-gasless decision based on (client, chain, token, gas).\n */\n usePermit?: boolean\n}): Promise<FunRelayFeeItem> {\n const params = new URLSearchParams({\n clientId,\n estUsdValue: estUsdValue.toString(),\n fromTokenAddress,\n fromChainId,\n toTokenAddress,\n toChainId,\n ...(recipientAddress ? { recipientAddress } : {}),\n ...(senderAddress ? { senderAddress } : {}),\n ...(usePermit !== undefined ? { usePermit: String(usePermit) } : {}),\n })\n const url = `https://frog.fun.xyz/api/fee?${params.toString()}`\n const response = await fetch(url)\n if (!response.ok) {\n throw Error(response.statusText)\n }\n\n const data = await response.json()\n return data\n}\n\nexport function parseRelayFees({\n fees,\n fromChainIdRelay,\n fromTokenAddressRelay,\n logger,\n sourceAssetDecimals,\n sourceUnitPrice,\n}: {\n fees: CallFees | undefined\n fromChainIdRelay: number\n fromTokenAddressRelay: string\n logger: Logger\n sourceAssetDecimals: number\n sourceUnitPrice: number\n}) {\n // Gas fees, denominated in source chain native token\n const relayGasFeesUsd = Number.parseFloat(fees?.gas?.amountUsd || '0')\n\n // App fees, *usually* denominated in source chain token\n const areFunLpFeesInSourceChainToken =\n fees?.app?.currency?.chainId === fromChainIdRelay &&\n fees?.app?.currency?.address?.toLowerCase() ===\n fromTokenAddressRelay.toLowerCase()\n const funLpFeesUsd = Number.parseFloat(fees?.app?.amountUsd || '0')\n const funLpFeesFromAmount = areFunLpFeesInSourceChainToken\n ? Number.parseFloat(fees?.app?.amountFormatted || '0')\n : funLpFeesUsd / sourceUnitPrice || 0\n const funLpFeesFromAmountBaseUnit = areFunLpFeesInSourceChainToken\n ? BigInt(fees?.app?.amount || '0')\n : BigInt(Math.floor(funLpFeesFromAmount * 10 ** sourceAssetDecimals))\n\n // Relay fees, *usually* denominated in source chain token\n const areRelayLpFeesInSourceChainToken =\n fees?.relayer?.currency?.chainId === fromChainIdRelay &&\n fees?.relayer?.currency?.address?.toLowerCase() ===\n fromTokenAddressRelay.toLowerCase()\n const relayLpFeesUsd = Number.parseFloat(fees?.relayer?.amountUsd || '0')\n const relayLpFeesFromAmount = areRelayLpFeesInSourceChainToken\n ? Number.parseFloat(fees?.relayer?.amountFormatted || '0')\n : relayLpFeesUsd / sourceUnitPrice || 0\n const relayLpFeesFromAmountBaseUnit = areRelayLpFeesInSourceChainToken\n ? BigInt(fees?.relayer?.amount || '0')\n : BigInt(Math.floor(relayLpFeesFromAmount * 10 ** sourceAssetDecimals))\n\n const totalLpFeesUsd = funLpFeesUsd + relayLpFeesUsd\n const totalLpFeesFromAmount = funLpFeesFromAmount + relayLpFeesFromAmount\n const totalLpFeesFromAmountBaseUnit =\n funLpFeesFromAmountBaseUnit + relayLpFeesFromAmountBaseUnit\n\n logger.info('parseRelayFees', {\n relayGasFeesUsd,\n funLpFeesUsd,\n funLpFeesFromAmount,\n funLpFeesFromAmountBaseUnit,\n relayLpFeesUsd,\n relayLpFeesFromAmount,\n relayLpFeesFromAmountBaseUnit,\n totalLpFeesUsd,\n totalLpFeesFromAmount,\n totalLpFeesFromAmountBaseUnit,\n })\n\n return {\n relayGasFeesUsd,\n totalLpFeesUsd,\n totalFeesUsd: relayGasFeesUsd + totalLpFeesUsd,\n totalFeesFromAmount: totalLpFeesFromAmount,\n totalFeesFromAmountBaseUnit: totalLpFeesFromAmountBaseUnit,\n }\n}\n", "import { MAINNET_RELAY_API } from '@relayprotocol/relay-sdk'\nimport type { RelayAddress } from './execution'\nimport type { RelayTokenPriceInfo } from './types'\nimport {\n convertFunToRelayChainId,\n convertFunToRelayTokenAddress,\n filterNullishHeaders,\n} from './utils'\n\ninterface GetRelayAssetPriceInfoParams {\n chainId: string\n address: string\n apiKey?: string\n}\n\nexport async function getRelayAssetPriceInfo({\n chainId,\n address,\n apiKey,\n}: GetRelayAssetPriceInfoParams): Promise<RelayTokenPriceInfo> {\n const relayChainId = convertFunToRelayChainId(Number(chainId))\n const relayTokenAddress = convertFunToRelayTokenAddress(\n address as RelayAddress,\n relayChainId,\n )\n\n const url = `${MAINNET_RELAY_API}/currencies/token/price?chainId=${relayChainId}&address=${relayTokenAddress}`\n const headers = filterNullishHeaders({ 'x-api-key': apiKey })\n const response = await fetch(url, { headers })\n\n if (!response.ok) {\n throw Error(response.statusText)\n }\n\n const data = await response.json()\n return data as RelayTokenPriceInfo\n}\n", "import {\n FUNKIT_NATIVE_TOKEN,\n FUN_HYPERCORE_CHAIN_ID_NUMBER,\n FUN_SOLANA_CHAIN_ID_NUMBER,\n RELAY_BITCOIN_CHAIN_ID_NUMBER,\n RELAY_LIGHTER_CHAIN_ID_NUMBER,\n RELAY_LIGHTER_FUN_ADDRESS_MAP,\n RELAY_LIGHTER_USDC_PERPS,\n RELAY_NATIVE_TOKEN,\n RELAY_NATIVE_TOKEN_BITCOIN,\n RELAY_NATIVE_TOKEN_HYPERCORE,\n RELAY_NATIVE_TOKEN_SOLANA,\n RELAY_SOLANA_CHAIN_ID_NUMBER,\n RELAY_TERMINAL_STATUSES,\n} from './constants'\nimport type { RelayAddress, RelayVmType } from './execution'\nimport {\n CheckoutRefundState,\n CheckoutState,\n type RelayExecutionInfo,\n RelayExecutionStatus,\n} from './types'\n\n/**\n * Converts a token address within Funkit to the corresponding Relay token address.\n * TODO: what is the chainId type here? fun chain id or relay chain id?\n */\nexport function convertFunToRelayTokenAddress<T extends RelayVmType>(\n address: RelayAddress<T>,\n chainId: number,\n): RelayAddress<T> {\n // convert Fun's NATIVE_TOKEN representation\n if (address.toLowerCase() === FUNKIT_NATIVE_TOKEN.toLowerCase()) {\n switch (chainId) {\n case FUN_HYPERCORE_CHAIN_ID_NUMBER:\n return RELAY_NATIVE_TOKEN_HYPERCORE as RelayAddress<T>\n\n case RELAY_BITCOIN_CHAIN_ID_NUMBER:\n return RELAY_NATIVE_TOKEN_BITCOIN as RelayAddress<T>\n\n // TODO: is it correct to assume chainId here is relay chain id?\n case RELAY_SOLANA_CHAIN_ID_NUMBER:\n case FUN_SOLANA_CHAIN_ID_NUMBER:\n return RELAY_NATIVE_TOKEN_SOLANA as RelayAddress<T>\n\n case RELAY_LIGHTER_CHAIN_ID_NUMBER:\n // legacy address for Lighter USDC perps\n return RELAY_LIGHTER_USDC_PERPS as RelayAddress<T>\n\n default:\n return RELAY_NATIVE_TOKEN as RelayAddress<T>\n }\n }\n\n if (RELAY_LIGHTER_CHAIN_ID_NUMBER === chainId) {\n const relayAddress =\n RELAY_LIGHTER_FUN_ADDRESS_MAP[\n address.toLowerCase() as keyof typeof RELAY_LIGHTER_FUN_ADDRESS_MAP\n ]\n if (relayAddress) {\n return relayAddress as RelayAddress<T>\n }\n }\n\n return address\n}\n\n/**\n * Converts a chainId within Funkit to the corresponding Relay chainId.\n */\nexport function convertFunToRelayChainId(chainId: number): number {\n if (chainId === FUN_SOLANA_CHAIN_ID_NUMBER) {\n return RELAY_SOLANA_CHAIN_ID_NUMBER\n }\n return chainId\n}\n\nexport function getRelayExecutionRefundState(\n info: RelayExecutionInfo,\n): CheckoutRefundState | undefined {\n switch (info.status) {\n case RelayExecutionStatus.REFUND:\n return CheckoutRefundState.REFUNDED\n default:\n return undefined\n }\n}\n\nexport function getRelayExecutionState(\n info: RelayExecutionInfo,\n): CheckoutState {\n switch (info.status) {\n case RelayExecutionStatus.SUCCESS:\n return CheckoutState.COMPLETED\n case RelayExecutionStatus.FAILURE:\n case RelayExecutionStatus.REFUND:\n return CheckoutState.CHECKOUT_ERROR\n default:\n return CheckoutState.PENDING_RECEIVAL\n }\n}\n\n/**\n * Checks whether the Relay execution has reached a terminal status.\n */\nexport function isRelayExecutionTerminalStatus(\n info: RelayExecutionInfo,\n): boolean {\n return RELAY_TERMINAL_STATUSES.includes(info.status)\n}\n\nexport type Serializable =\n | bigint\n | boolean\n | null\n | number\n | string\n | Date\n | object // Should be '{ [key: string]: Serializable }' but helper gets called with loosely-typed 'object' and interfaces\n | Serializable[]\n\nexport function jsonStringifyWithBigIntSanitization(\n serializable: Serializable,\n): string {\n return JSON.stringify(\n serializable,\n (_, value) =>\n typeof value === 'bigint' ? `0x${value.toString(16)}` : value, // return everything else unchanged\n )\n}\n\nexport function indexBy<Item>(\n items: Item[],\n getKey: (item: Item) => string,\n): Record<string, Item> {\n const indexedItems: Record<string, Item> = {}\n\n for (const item of items) {\n const key = getKey(item)\n\n if (!key) {\n continue\n }\n\n indexedItems[key] = item\n }\n\n return indexedItems\n}\n\nexport function filterNullishHeaders(\n params: Record<string, string | undefined | null>,\n): Record<string, string> {\n const result: Record<string, string> = {}\n for (const [key, value] of Object.entries(params)) {\n if (value != null) {\n result[key] = value\n }\n }\n return result\n}\n", "import { MAINNET_RELAY_API } from '@relayprotocol/relay-sdk'\nimport type { RelayAddress } from './execution'\nimport {\n convertFunToRelayChainId,\n convertFunToRelayTokenAddress,\n filterNullishHeaders,\n} from './utils'\n\nexport interface RelayTokenInfo {\n chainId: number\n address: string\n symbol: string\n name: string\n decimals: number\n vmType: string\n metadata: {\n logoURI: string\n verified: boolean\n isNative: boolean\n }\n}\n\ninterface GetRelayAssetInfoParams {\n chainId: string\n address: string\n useExternalSearch?: boolean\n apiKey?: string\n}\n\nexport async function getRelayAssetInfo({\n chainId,\n address,\n // https://fun-xyz.slack.com/archives/C08MQ85QB2N/p1770674350731879?thread_ts=1770670744.270889&cid=C08MQ85QB2N\n useExternalSearch = true,\n apiKey,\n}: GetRelayAssetInfoParams): Promise<RelayTokenInfo> {\n const relayChainId = convertFunToRelayChainId(Number(chainId))\n const relayTokenAddress = convertFunToRelayTokenAddress(\n address as RelayAddress,\n relayChainId,\n )\n const url = `${MAINNET_RELAY_API}/currencies/v2`\n const headers = filterNullishHeaders({\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n })\n const body = {\n chainIds: [relayChainId],\n address: relayTokenAddress,\n useExternalSearch,\n }\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n })\n if (!response.ok) {\n throw Error(response.statusText)\n }\n\n const data = await response.json()\n return data?.[0] as RelayTokenInfo\n}\n", "import {\n type APIError,\n type Execute,\n type GetQuoteParameters,\n isAPIError,\n} from '@relayprotocol/relay-sdk'\nimport { type Address, encodeFunctionData } from 'viem'\nimport { getRelayClient } from './client'\nimport {\n FUN_RELAY_REFERRER,\n FUN_RELAY_REVENUE_WALLET,\n RELAY_QUOTE_CHECKOUT_TIME_BUFFER_MS,\n} from './constants'\nimport { getRelayAssetInfo } from './currency'\nimport type {\n RelayAddress,\n RelayChainId,\n RelayVmType,\n RelayWallet,\n} from './execution'\nimport { type FunRelayFeeItem, getFunRelayFees, parseRelayFees } from './fees'\nimport { getRelayAssetPriceInfo } from './price'\nimport type { SolanaAddress } from './solana'\nimport type {\n ApiFunkitCheckoutActionParams,\n CheckoutQuoteResponse,\n Logger,\n} from './types'\nimport {\n convertFunToRelayChainId,\n convertFunToRelayTokenAddress,\n} from './utils'\n\ntype RelayQuoteOptions = GetQuoteParameters['options'] & {\n // TODO: Relay does not yet explicitly handle this field in their SDK, nor is it in their typings - but it gets forwarded to API\n depositFeePayer?: SolanaAddress\n}\n\nexport type RelayQuoteResult<VmType extends RelayVmType> = {\n details?: {\n currencyIn?: NonNullable<Execute['details']>['currencyIn']\n currencyOut?: NonNullable<Execute['details']>['currencyOut']\n }\n steps: Execute['steps']\n vmType: VmType\n}\n\nexport type RelayExecute = Execute\n\nexport type GetRelayQuoteParams<\n SourceVmType extends RelayVmType = RelayVmType,\n TargetVmType extends RelayVmType = RelayVmType,\n> = {\n actionParams?: ApiFunkitCheckoutActionParams[]\n clientId: string\n fromChainId: RelayChainId<SourceVmType>\n fromTokenAddress: RelayAddress<SourceVmType>\n logger: Logger\n /**\n * {@link getRelayQuote} already sets {@link RelayQuoteOptions.appFees|appFees} and {@link RelayQuoteOptions.referrer|referrer}.\n * Only include them if you wish to override.\n */\n options?: RelayQuoteOptions\n recipientAddress: RelayAddress<TargetVmType> | undefined\n toChainId: RelayChainId<TargetVmType>\n toTokenAddress: RelayAddress<TargetVmType>\n tradeType: 'EXACT_INPUT' | 'EXACT_OUTPUT' | 'EXPECTED_OUTPUT'\n userAddress: RelayAddress<SourceVmType> | undefined\n walletClient?: RelayWallet<SourceVmType>\n apiKey: string\n /**\n * Optional explicit user preference for the source-side authorization\n * step (\"Sign message\" vs \"Approve transaction\"). Forwarded to frog's\n * `/api/fee` so frog's `getUsePermit` can honor the FE toggle's choice.\n * Only meaningful for FE-driven flows (Wallet checkout); server-driven\n * flows (UDA, etc.) should omit this and let frog's auto-gasless\n * fallback decide.\n */\n usePermit?: boolean\n} & (\n | {\n fromTokenAmountBaseUnit: bigint | string\n tradeType: 'EXACT_INPUT'\n }\n | {\n toTokenAmountBaseUnit: bigint | string\n tradeType: 'EXACT_OUTPUT' | 'EXPECTED_OUTPUT'\n }\n)\n\nexport type RelayQuote<VmType extends RelayVmType = RelayVmType> =\n CheckoutQuoteResponse & {\n /** Required for EXACT_INPUT checkouts */\n finalToAmountBaseUnit: string\n metadata: {\n fromAmountBaseUnit: string\n relayQuote: RelayQuoteResult<VmType>\n toAmountBaseUnit: string\n }\n }\n\n// this quote type is only used by backend, not exposed to FE\n// and can contain additional fields that are not in the FE-facing quote type.\nexport type RelayBackendQuote<VmType extends RelayVmType = RelayVmType> =\n CheckoutQuoteResponse & {\n /** Required for EXACT_INPUT checkouts */\n finalToAmountBaseUnit: string\n metadata: {\n fromAmountBaseUnit: string\n relayQuote: Execute & { vmType: VmType }\n toAmountBaseUnit: string\n }\n }\n\nasync function getQuoteEstUsdValue({\n tokenChainId,\n tokenAddress,\n tokenAmountBaseUnit,\n logger,\n apiKey,\n}: {\n tokenChainId: string\n tokenAddress: string\n tokenAmountBaseUnit: string\n logger: Logger\n apiKey: string\n}) {\n try {\n const normalizedChainId = convertFunToRelayChainId(\n Number(tokenChainId),\n ).toString()\n const normalizedTokenAddress = convertFunToRelayTokenAddress(\n tokenAddress as Address,\n Number(tokenChainId),\n )\n\n const [tokenPriceRes, tokenInfoRes] = await Promise.all([\n getRelayAssetPriceInfo({\n chainId: normalizedChainId,\n address: normalizedTokenAddress,\n apiKey,\n }),\n getRelayAssetInfo({\n chainId: normalizedChainId,\n address: normalizedTokenAddress,\n apiKey,\n }),\n ])\n\n // FIXME: Temp hardcode until relay supports WUSDE on Ethereal\n const isWUsdeEthereal =\n normalizedChainId === '5064014' &&\n normalizedTokenAddress.toLowerCase() ===\n '0xB6fC4B1BFF391e5F6b4a3D2C7Bda1FeE3524692D'.toLowerCase()\n\n const price = tokenPriceRes.price\n const decimals = isWUsdeEthereal ? 18 : tokenInfoRes.decimals\n\n const absoluteAmount = BigInt(tokenAmountBaseUnit) / BigInt(10 ** decimals)\n return Number(price) * Number(absoluteAmount)\n } catch (err) {\n logger.error('getQuoteEstUsdValueError', {\n message: `Failed to get USD value for token ${tokenAddress} on chain ${tokenChainId}: ${getErrorMessage(\n err,\n )}. Falling back to 0 USD.`,\n })\n // If any part fails, just fallback to 0 USD so that we do not block quote\n return 0\n }\n}\n\nexport function getReferrer(clientId: string) {\n return clientId ? `${FUN_RELAY_REFERRER}|${clientId}` : FUN_RELAY_REFERRER\n}\n\nexport class RelayQuoteClientError extends Error {\n public constructor(\n public readonly statusCode: number,\n public readonly relayErrorCode: string,\n message: string,\n requestId: string | undefined = '',\n ) {\n super(\n `An error occurred trying to generate a relay quote: ${relayErrorCode} - ReqId ${requestId || 'NO_REQ_ID'} - ${message}`,\n )\n\n this.name = new.target.name\n Object.setPrototypeOf(this, new.target.prototype)\n }\n}\n\n/**\n * Get the headers for the quote request by the following logic:\n * - If subsidizeFeesSecretKey is provided, and subsidizeFees is true, set it to \"x-api-key\" header\n * - Apply funRelayConfig.headers as overrides if provided\n */\nexport const getHeaders = (funRelayConfig: FunRelayFeeItem, apiKey: string) => {\n const headers = {\n 'x-api-key': apiKey,\n // Remote headers will override passed in headers\n ...(funRelayConfig.headers ? { ...funRelayConfig.headers } : {}),\n }\n return headers\n}\n\nexport async function getRelayQuote<\n SourceVmType extends RelayVmType,\n TargetVmType extends RelayVmType = RelayVmType,\n>({\n logger,\n walletClient,\n ...params\n}: GetRelayQuoteParams<SourceVmType, TargetVmType>): Promise<\n RelayBackendQuote<SourceVmType>\n> {\n const {\n actionParams,\n clientId,\n fromChainId,\n fromTokenAddress,\n options,\n recipientAddress,\n toChainId,\n toTokenAddress,\n tradeType,\n userAddress,\n apiKey,\n usePermit,\n } = params\n\n const vmType = (\n walletClient && 'vmType' in walletClient ? walletClient.vmType : 'evm'\n ) as SourceVmType\n\n try {\n const relayClient = getRelayClient()\n\n // Same chain\n const isSameChainFlow = String(fromChainId) === String(toChainId)\n\n const txs = actionParams?.map((action) => {\n const data =\n action.rawCalldata ??\n encodeFunctionData({\n abi: action.contractAbi,\n args: action.functionArgs,\n functionName: action.functionName,\n })\n\n return {\n data,\n to: action.contractAddress,\n // Relay supports msg.value via 2 fields: `value` and `originalTxValue`\n // Both `value` and `originalTxValue` are required to be set for `erc20` + gas transfers\n // Only `value` is required for native token transfers. // TODO: This flow needs verification.\n // Internally for Relay,\n // - `originalTxValue` is designed to \"bubble up\" the value to the original tx. This only works for user-executed same-chain operations with calls. This does not work / apply to cross chain operations\n // - `value` is the internal multicall value\n ...(isSameChainFlow\n ? { originalTxValue: String(action.value ?? 0n) }\n : {}),\n value: String(action.value ?? 0n),\n }\n })\n\n const isExactIn = params.tradeType === 'EXACT_INPUT'\n const queryTokenAmountBaseUnit = isExactIn\n ? params.fromTokenAmountBaseUnit\n : params.toTokenAmountBaseUnit\n const queryTokenAddress = isExactIn ? fromTokenAddress : toTokenAddress\n const queryTokenChainId = isExactIn ? fromChainId : toChainId\n\n const estUsdValue = await getQuoteEstUsdValue({\n tokenChainId: queryTokenChainId,\n tokenAddress: queryTokenAddress,\n tokenAmountBaseUnit: queryTokenAmountBaseUnit.toString(),\n logger,\n apiKey,\n })\n\n const funRelayConfig = await getFunRelayFees({\n clientId,\n estUsdValue: Number(estUsdValue) || 0,\n fromTokenAddress,\n fromChainId,\n recipientAddress,\n senderAddress: userAddress,\n toTokenAddress,\n toChainId,\n usePermit,\n })\n\n const headers = getHeaders(funRelayConfig, apiKey)\n\n const appFeeBp = funRelayConfig.b + funRelayConfig.v\n\n logger.info('getRelayQuoteParams', {\n ...params,\n appFeeBp,\n estUsdValue,\n funRelayConfig,\n queryTokenAmountBaseUnit,\n txs,\n })\n\n // Get the full quote with fees\n const relayQuote = await relayClient.actions.getQuote(\n {\n amount: queryTokenAmountBaseUnit.toString(),\n chainId: convertFunToRelayChainId(Number(fromChainId)),\n currency: convertFunToRelayTokenAddress(\n fromTokenAddress,\n Number(fromChainId),\n ),\n recipient: recipientAddress,\n toChainId: convertFunToRelayChainId(Number(toChainId)),\n toCurrency: convertFunToRelayTokenAddress(\n toTokenAddress,\n Number(toChainId),\n ),\n tradeType,\n txs,\n user: userAddress,\n wallet: walletClient,\n options: {\n referrer: getReferrer(clientId),\n appFees: [\n {\n fee: appFeeBp.toString(),\n recipient: FUN_RELAY_REVENUE_WALLET,\n },\n ],\n // Passed in options\n ...options,\n // Remote options will always override passed in options\n ...funRelayConfig.config.options,\n },\n },\n undefined,\n headers,\n )\n\n logger.info('relayQuote', relayQuote)\n\n const toAmountUsd = Number(relayQuote.details?.currencyOut?.amountUsd || 0)\n const fromAmountUsd = Number(relayQuote.details?.currencyIn?.amountUsd || 0)\n // Get how much fromAmount is needed for the quote\n const fromAmountString =\n relayQuote.details?.currencyIn?.amountFormatted || '0'\n const fromAmountBaseUnitString =\n relayQuote.details?.currencyIn?.amount || '0'\n const fromAssetAmount = Number(fromAmountString || 0)\n\n // RequestID will be consistent across steps in the quote\n // https://fun-xyz.slack.com/archives/C08MQ85QB2N/p1747774944603209\n const relayRequestId = relayQuote.steps[0]?.requestId\n\n // TODO: Verify with relay team if this is possible?\n if (!relayRequestId) {\n throw new Error('Relay quote does not contain a requestId')\n }\n\n // TODO: Verify with relay team if this is possible?\n if (!relayQuote.details?.currencyIn || !relayQuote.details?.currencyOut) {\n throw new Error('Relay quote does not contain trade details')\n }\n\n const {\n relayGasFeesUsd,\n totalLpFeesUsd,\n totalFeesUsd,\n totalFeesFromAmount,\n totalFeesFromAmountBaseUnit,\n } = parseRelayFees({\n fees: relayQuote.fees,\n fromChainIdRelay: convertFunToRelayChainId(Number(fromChainId)),\n fromTokenAddressRelay: convertFunToRelayTokenAddress(\n fromTokenAddress,\n Number(fromChainId),\n ),\n logger,\n sourceAssetDecimals:\n relayQuote.details.currencyIn.currency?.decimals ?? 18,\n sourceUnitPrice: fromAmountUsd / fromAssetAmount || 1,\n })\n\n const estSubtotalFromAmount = (\n fromAssetAmount - totalFeesFromAmount\n ).toString()\n\n const estSubtotalFromAmountBaseUnit = (\n BigInt(fromAmountBaseUnitString) - totalFeesFromAmountBaseUnit\n ).toString()\n\n return {\n quoteId: relayRequestId,\n estCheckoutTimeMs:\n (relayQuote.details.timeEstimate || 0) * 1000 +\n RELAY_QUOTE_CHECKOUT_TIME_BUFFER_MS,\n estFeesFromAmount: totalFeesFromAmount.toString(),\n estFeesFromAmountBaseUnit: totalFeesFromAmountBaseUnit.toString(),\n estFeesUsd: totalFeesUsd,\n estMarketMakerGasUsd: relayGasFeesUsd,\n estSubtotalFromAmount,\n estSubtotalFromAmountBaseUnit,\n estSubtotalUsd: toAmountUsd,\n estTotalFromAmount: fromAmountString,\n estTotalFromAmountBaseUnit: fromAmountBaseUnitString,\n estTotalUsd: fromAmountUsd,\n finalToAmountBaseUnit: relayQuote.details.currencyOut.amount ?? '0', // TODO: Or do we want 'minimumAmount'?\n fromTokenAddress: fromTokenAddress as Address, // TODO: fromTokenAddress is typed as `0x${string}` why does not accept SolanaAddress\n lpFeePercentage: 0, // TODO: ?\n lpFeeUsd: totalLpFeesUsd,\n metadata: {\n fromAmountBaseUnit: isExactIn\n ? queryTokenAmountBaseUnit.toString()\n : (relayQuote.details.currencyIn.amount ?? '0'),\n relayQuote: {\n ...relayQuote,\n vmType,\n },\n toAmountBaseUnit: isExactIn\n ? (relayQuote.details.currencyOut.amount ?? '0')\n : queryTokenAmountBaseUnit.toString(),\n },\n }\n } catch (err) {\n if (err instanceof Error && isAPIError(err)) {\n const apiError = err as APIError\n // see the Error section in https://docs.relay.link/references/api/get-quote-v2\n const rawError = apiError.rawError as {\n errorCode?: string\n message?: string\n requestId?: string\n }\n\n if (rawError?.errorCode) {\n throw new RelayQuoteClientError(\n apiError.statusCode,\n rawError.errorCode,\n rawError.message ?? apiError.message,\n rawError.requestId,\n )\n }\n }\n\n const message = getErrorMessage(err)\n throw new Error(\n `An error occurred trying to generate a relay quote: ${message}`,\n )\n }\n}\n\nfunction getErrorMessage(err: unknown): string {\n return err instanceof Error\n ? err.message\n : typeof err === 'string'\n ? err\n : JSON.stringify(err)\n}\n", "import type { AdaptedWallet } from '@relayprotocol/relay-sdk'\nimport { adaptSolanaWallet } from '@relayprotocol/relay-svm-wallet-adapter'\nimport {\n type Connection,\n SendTransactionError,\n type VersionedTransaction,\n} from '@solana/web3.js'\nimport { RELAY_SOLANA_CHAIN_ID_NUMBER } from './constants'\n\ntype Base58 =\n | '1'\n | '2'\n | '3'\n | '4'\n | '5'\n | '6'\n | '7'\n | '8'\n | '9'\n | 'A'\n | 'B'\n | 'C'\n | 'D'\n | 'E'\n | 'F'\n | 'G'\n | 'H'\n | 'J'\n | 'K'\n | 'L'\n | 'M'\n | 'N'\n | 'P'\n | 'Q'\n | 'R'\n | 'S'\n | 'T'\n | 'U'\n | 'V'\n | 'W'\n | 'X'\n | 'Y'\n | 'Z'\n | 'a'\n | 'b'\n | 'c'\n | 'd'\n | 'e'\n | 'f'\n | 'g'\n | 'h'\n | 'i'\n | 'j'\n | 'k'\n | 'm'\n | 'n'\n | 'o'\n | 'p'\n | 'q'\n | 'r'\n | 's'\n | 't'\n | 'u'\n | 'v'\n | 'w'\n | 'x'\n | 'y'\n | 'z'\n\nexport type SolanaAddress = `${Base58}${string}`\n\nexport type SolanaTxHash = `${Base58}${string}`\n\nexport type SolanaWallet = {\n address(): Promise<SolanaAddress>\n vmType: 'svm'\n} & AdaptedWallet\n\nexport function getSolanaWallet(\n walletAddress: SolanaAddress,\n connection: Connection,\n signTransaction: (\n transaction: VersionedTransaction,\n ) => Promise<VersionedTransaction>,\n payerKey?: SolanaAddress,\n): SolanaWallet {\n return adaptSolanaWallet(\n walletAddress,\n RELAY_SOLANA_CHAIN_ID_NUMBER,\n connection,\n async (transaction, options) => {\n const signed = await signTransaction(transaction)\n try {\n const signature = await connection.sendTransaction(signed, {\n ...options,\n maxRetries: 5,\n })\n\n return { signature }\n } catch (error) {\n if (error instanceof SendTransactionError) {\n console.error(\n 'Failed transaction logs:',\n error,\n