import { Console } from 'node:console' import util from 'node:util' import { type CCIPExecution, type CCIPRequest, type CCIPVerifications, type Chain, type ChainStatic, type Lane, type TokenInfo, type TokenUIMultiplier, CCIPError, CCIPErrorCode, CCIPInteractiveRequiredError, CCIPLocalTokenRequiredError, CCIPTokenDecimalsUnavailableError, ChainFamily, ExecutionState, getCCIPExplorerUrl, getDataBytes, getSourceTokenFromExtraData, networkInfo, resolveTokenDecimals, supportedChains, toUIAmount, } from '@chainlink/ccip-sdk/src/index.ts' import { select } from '@inquirer/prompts' import { formatUnits, hexlify, isBytesLike, isHexString, parseUnits, toBigInt, toUtf8String, } from 'ethers' import type { PickDeep } from 'type-fest' import { grpcVerifierTransport } from '../verifiers/grpc-transport.ts' import type { Ctx } from './types.ts' /** * Prompts user to select a CCIP request from a list. * @param requests - List of CCIP requests to choose from. * @param promptSuffix - Optional suffix for the prompt message. * @param hints - Optional hints for pre-filtering requests. * @returns Selected CCIP request. */ export async function selectRequest( requests: readonly CCIPRequest[], promptSuffix?: string, hints?: { logIndex?: number; interactive?: boolean }, ): Promise { if (hints?.logIndex != null) requests = requests.filter((req) => req.log.index === hints.logIndex) if (requests.length === 1) return requests[0]! if (hints?.interactive === false) { throw new CCIPInteractiveRequiredError( `Multiple messages found (${requests.length}). Use --log-index to select one`, { context: { count: requests.length, logIndices: requests.map((r) => r.log.index), messageIds: requests.map((r) => r.message.messageId), }, }, ) } const answer = await select({ message: `${requests.length} messageIds found; select one${promptSuffix ? ' ' + promptSuffix : ''}`, choices: [ ...requests.map((req, i) => { const srcFam = networkInfo(req.lane.sourceChainSelector).family const dstFam = networkInfo(req.lane.destChainSelector).family return { value: i, name: `${req.log.index} => ${req.message.messageId}`, description: `sender =\t\t${formatDisplayAddress(req.message.sender, srcFam)} receiver =\t\t${formatDisplayAddress(req.message.receiver, dstFam)} gasLimit =\t\t${(req.message as { gasLimit: bigint }).gasLimit} tokenTransfers =\t[${req.message.tokenAmounts.map((ta) => ('token' in ta ? formatDisplayAddress(ta.token, srcFam) : formatDisplayAddress(ta.destTokenAddress, dstFam))).join(',')}]` + ('lane' in req ? `\ndestination =\t\t${networkInfo(req.lane.destChainSelector).name} [${networkInfo(req.lane.destChainSelector).chainId}]` : ''), } }), { value: -1, name: 'Exit', description: 'Quit the application', }, ], }) if (answer < 0) throw new CCIPError(CCIPErrorCode.UNKNOWN, 'User requested exit') return requests[answer]! } /** * Converts a Unix timestamp to a Date object. * @param obj - Object with timestamp property. * @returns Object with Date timestamp. */ export function withDateTimestamp< T extends | { readonly timestamp: number } | { readonly blockTimestamp: number } | { readonly log: { readonly blockTimestamp: number } } | { readonly tx: { readonly timestamp: number } }, >(obj: T): Omit & { timestamp: Date } { return { ...obj, timestamp: new Date( ('timestamp' in obj ? obj.timestamp : 'blockTimestamp' in obj ? obj.blockTimestamp : 'log' in obj ? obj.log.blockTimestamp : obj.tx.timestamp) * 1e3, ), } } /** * Prints lane information in a human-readable format. * @param lane - Lane configuration. */ export function prettyLane(this: Ctx, lane: Lane) { this.output.write('Lane:') const source = networkInfo(lane.sourceChainSelector), dest = networkInfo(lane.destChainSelector) this.output.table({ name: { source: source.name, dest: dest.name }, chainId: { source: source.chainId, dest: dest.chainId }, chainSelector: { source: source.chainSelector, dest: dest.chainSelector }, 'onRamp/version': { source: formatDisplayAddress(lane.onRamp, source.family), dest: lane.version, }, }) } /** * Format an address for display using chain-specific formatting. * @param address - Address string * @param family - Chain family for formatting * @returns Formatted address for display */ export function formatDisplayAddress(address: string, family: ChainFamily): string { return supportedChains[family]?.formatAddress?.(address) ?? address } /** * Format a transaction hash for display using chain-specific formatting. * @param hash - Transaction hash string * @param family - Chain family for formatting * @returns Formatted hash for display */ export function formatDisplayTxHash(hash: string, family: ChainFamily): string { return supportedChains[family]?.formatTxHash?.(hash) ?? hash } /** String keys whose values are chain addresses; see {@link prettyFormat}. */ const ADDRESS_KEYS = new Set([ 'router', 'feeQuoter', 'feeAggregator', 'allowlistAdmin', 'linkToken', 'tokenPool', 'tokenAdminRegistry', 'administrator', 'contract', 'origin', 'address', 'sender', 'receiver', 'onRamp', 'offRamp', 'onRamps', 'offRamps', 'offRampAddress', 'sourcePoolAddress', 'destTokenAddress', 'tokenReceiver', 'requiredCCVs', 'optionalCCVs', ]) /** String keys whose values are transaction hashes; see {@link prettyFormat}. */ const TX_HASH_KEYS = new Set([ 'transactionHash', 'receiptTransactionHash', 'sendTransactionHash', 'txHash', ]) /** * Recursively formats a record for pretty printing: values under known * address/tx-hash keys go through {@link formatDisplayAddress}/ * {@link formatDisplayTxHash}, so TON (and future) user-facing formats are * always friendly addresses and bare tx hashes in pretty output. * * `sameFamily` formats values owned by the printing chain. `familyFor` * overrides the family for specific keys holding *remote*-chain values — e.g. * an EVM OffRampConfig's `onRamps` list, which contains source-chain * addresses and must be formatted with the source family. Only affects pretty * output: json/log formats must keep raw values. */ export function prettyFormat( value: unknown, sameFamily: ChainFamily, familyFor: Readonly> = {}, ): unknown { const format = (val: unknown, key?: string): unknown => { if (typeof val === 'string' && key) { const family = key in familyFor ? familyFor[key]! : sameFamily if (ADDRESS_KEYS.has(key)) return formatDisplayAddress(val, family) if (TX_HASH_KEYS.has(key)) return formatDisplayTxHash(val, family) } if (Array.isArray(val)) return val.map((v) => format(v, key)) if (val && typeof val === 'object') { return Object.fromEntries( Object.entries(val as Record).map(([k, v]) => [k, format(v, k)]), ) } return val } return format(value) } /** * Formats a token amount for display, with its symbol and decimals when they resolve. * @internal */ export async function formatToken( source: Chain | undefined, ta: { amount: bigint } & ( | { token: string } | { sourceTokenAddress?: string; sourcePoolAddress: string; extraData?: string } ), family?: ChainFamily, ): Promise { if ('token' in ta && !ta.token) { return ta.amount === 0n ? '0 (paid on-ledger)' : `${ta.amount} (on-ledger)` } if (!source) { const addr = 'sourcePoolAddress' in ta ? ta.sourcePoolAddress : ta.token return `${ta.amount} ${formatDisplayAddress(addr, family ?? ChainFamily.EVM)}` } let token if ('token' in ta) token = ta.token else if (ta.sourceTokenAddress) token = ta.sourceTokenAddress else { // a multi-token source pool sends the source token in its pool data; a pool address alone // does not select one of its tokens token = getSourceTokenFromExtraData(ta.extraData, source.network.family) try { token ??= await source.getTokenForTokenPool(ta.sourcePoolAddress) } catch (err) { if (!(err instanceof CCIPLocalTokenRequiredError)) throw err return `${ta.amount} (raw units) ${formatDisplayAddress(ta.sourcePoolAddress, family ?? ChainFamily.EVM)}` } } try { return formatTokenAmount(ta.amount, await source.getTokenInfo(token)) } catch (err) { // tokens without the optional ERC-20 decimals() view (or unreachable metadata) still // display: raw units with the address, so a successful send is never unprintable if (err instanceof CCIPTokenDecimalsUnavailableError) return `${ta.amount} (raw units) ${formatDisplayAddress(token, family ?? ChainFamily.EVM)}` throw err } } /** * Formats an array into a record with indexed keys. * @param name - Base name for the keys. * @param values - Array values to format. * @returns Record with indexed keys. */ export function formatArray( name: string, values: readonly T[], edges = '[]', ): Record { if (values.length <= 1) return { [name]: values[0]! } return Object.fromEntries(values.map((v, i) => [`${name}${edges[0]}${i}${edges[1]}`, v] as const)) } // join truthy property names, separated by a dot function j(...args: (string | number)[]): string { return args.reduce( (acc: string, v): string => v === '' ? acc : acc ? acc + (typeof v === 'number' ? `[${v}]` : (v.match(/^\w/) ? '.' : '') + v) : v.toString(), '', ) } function formatData(name: string, data: string): Record { if (!isHexString(data)) return { [name]: data } const split = [] if (data.length <= 66) split.push(data) else for (let i = data.length; i > 2; i -= 64) { split.unshift(data.substring(Math.max(i - 64, 0), i)) } return formatArray(name, split, '{}') } function formatDate(timestamp: number) { return new Date(timestamp * 1e3).toISOString().substring(0, 19).replace('T', ' ') } /** * Formats an ERC-8056 UI multiplier for display, e.g. `2x`, with a scheduled change, e.g. * `2x (3x from 2026-12-07 14:30:00)`. * @param multiplier - The token's UI multiplier. * @returns The formatted multiplier. */ export function formatUIMultiplier({ uiMultiplier, next }: TokenUIMultiplier): string { const times = (m: bigint) => `${formatUnits(m, 18).replace(/\.0$/, '')}x` return next ? `${times(uiMultiplier)} (${times(next.uiMultiplier)} from ${formatDate(next.effectiveAt)})` : times(uiMultiplier) } /** * Formats a raw token amount with its symbol and, for an ERC-8056 token, its UI amount at the * current multiplier, e.g. `1.5 TSLA (3 UI @ 2x)`. * @param amount - Raw amount. * @param info - The token's info. * @returns The formatted amount. */ export function formatTokenAmount(amount: bigint, info: TokenInfo): string { const formatted = `${formatUnits(amount, info.decimals)} ${info.symbol}` if (!info.uiMultiplier) return formatted const uiAmount = toUIAmount(amount, info.uiMultiplier.uiMultiplier) return `${formatted} (${formatUnits(uiAmount, info.decimals)} UI @ ${formatUIMultiplier({ uiMultiplier: info.uiMultiplier.uiMultiplier })})` } /** * Formats duration in seconds to human-readable string. * @param secs - Duration in seconds. * @returns Formatted duration string (e.g., "2d 1h30m"). */ export function formatDuration(secs: number) { if (secs < 0) secs = -secs if (secs >= 3540 && Math.floor(secs) % 60 >= 50) secs += 60 - (secs % 60) // round up 50+s else if (secs >= 118 && Math.floor(secs) % 60 >= 58) secs += 60 - (secs % 60) // round up 58+s const time = { d: Math.floor(secs / 86400), h: Math.floor(secs / 3600) % 24, m: Math.floor(secs / 60) % 60, s: Math.floor(secs) % 60, } return Object.entries(time) .filter((val) => val[1] !== 0) .map(([key, val], i, arr) => `${val}${key}${key === 'd' && i < arr.length - 1 ? ' ' : ''}`) .join('') } /** * Omit specified keys from an object and return a new object. */ export function omit, K extends string>( obj: T, ...keys: K[] ): Omit { const result = { ...obj } for (const key of keys) { delete result[key] } return result } // while formatData just breaks 0x bytes into 32B chunks for readability, this function first // tests if the data looks like a UTF-8 string (with length prefix) and decode that before function formatDataString(data: string): Record { const bytes = getDataBytes(data) const isPrintableChars = (bytes_: Uint8Array) => bytes_.every((b) => 32 <= b && b <= 126) if (bytes.length > 64 && toBigInt(bytes.subarray(0, 32)) === 32n) { const len = toBigInt(bytes.subarray(32, 64)) if ( len < 512 && bytes.length - 64 === Math.ceil(Number(len) / 32) * 32 && isPrintableChars(bytes.subarray(64, 64 + Number(len))) && bytes.subarray(64 + Number(len)).every((b) => b === 0) ) { return { data: toUtf8String(bytes.subarray(64, 64 + Number(len))) } } } if (bytes.length > 0 && isPrintableChars(bytes)) return { data: toUtf8String(bytes) } return formatData('data', data) } /** * Prints a CCIP request in a human-readable format. * @param request - CCIP request to print. * @param source - Source chain instance. */ export async function prettyRequest(this: Ctx, request: CCIPRequest, source?: Chain) { prettyLane.call(this, request.lane) this.output.write('Request (source):') let finalized try { if (source) finalized = await source.getBlockTimestamp('finalized') } catch { // no finalized tag support } let nonce if ('nonce' in request.message) nonce = Number(request.message.nonce) const sourceFamily = networkInfo(request.lane.sourceChainSelector).family const destFamily = networkInfo(request.lane.destChainSelector).family // Normalize receiver to destination chain format for display const displaySender = formatDisplayAddress(request.message.sender, sourceFamily) const displayReceiver = formatDisplayAddress(request.message.receiver, destFamily) const displayOrigin = request.tx.from ? formatDisplayAddress(request.tx.from, sourceFamily) : undefined const displayTxHash = formatDisplayTxHash(request.log.transactionHash, sourceFamily) const rest = omit( request.message, 'messageId', 'sequenceNumber', 'nonce', 'sender', 'receiver', 'tokenAmounts', 'data', 'feeToken', 'feeTokenAmount', 'sourceTokenData', 'sourceChainSelector', 'destChainSelector', 'extraArgs', 'accounts', 'receipts', 'encodedMessage', ) prettyTable.call(this, { messageId: request.message.messageId, ...(displayOrigin ? { origin: displayOrigin } : {}), sender: displaySender, receiver: displayReceiver, sequenceNumber: Number(request.message.sequenceNumber), ...(nonce != null && { nonce: nonce === 0 ? '0 => allow out-of-order exec' : nonce }), ...('gasLimit' in request.message ? { gasLimit: Number(request.message.gasLimit) } : 'computeUnits' in request.message ? { computeUnits: Number(request.message.computeUnits) } : {}), transactionHash: displayTxHash, logIndex: request.log.index, blockNumber: request.log.blockNumber, timestamp: `${formatDate(request.log.blockTimestamp)} (${formatDuration(Date.now() / 1e3 - request.log.blockTimestamp)} ago)`, finalized: finalized && (finalized < request.log.blockTimestamp ? formatDuration(request.log.blockTimestamp - finalized) + ' left' : true), fee: await formatToken( source, { token: request.message.feeToken, amount: request.message.feeTokenAmount, }, sourceFamily, ), ...formatArray( 'tokens', await Promise.all( request.message.tokenAmounts.map((ta) => formatToken(source, ta, sourceFamily)), ), ), ...formatDataString(request.message.data), ...('accounts' in request.message ? formatArray( 'accounts', request.message.accounts.map((a) => formatDisplayAddress(a, sourceFamily)), ) : {}), ...('receipts' in request.message ? formatArray('receipts', request.message.receipts) : {}), ...(prettyFormat(rest, sourceFamily, { offRampAddress: destFamily }) as Record< string, unknown >), ...(request.metadata ? (prettyFormat( omit(request.metadata, 'sourceNetworkInfo', 'destNetworkInfo'), destFamily, ) as Record) : {}), }) this.output.write('CCIP Explorer:', getCCIPExplorerUrl('msg', request.message.messageId)) } /** * Prints CCIP Verifications in a human-readable format. * @param dest - Destination chain instance. * @param verifications - CCIP verifications to print. * @param request - CCIP request for timestamp comparison. */ export async function prettyVerifications( this: Ctx, dest: Chain, verifications: CCIPVerifications, request: PickDeep< CCIPRequest, 'log.blockTimestamp' | 'lane.destChainSelector' | 'lane.sourceChainSelector' >, ) { const destFamily = networkInfo(request.lane.destChainSelector).family const sourceFamily = networkInfo(request.lane.sourceChainSelector).family if ('report' in verifications) { // The log carries its block's timestamp; read the block only when it doesn't (an old // block may be past what the dest RPC keeps, e.g. TON's public v2 endpoint). const timestamp = verifications.log.blockTimestamp || (await dest.getBlockInfo(verifications.log.blockNumber)).timestamp const origin = verifications.log.tx?.from ?? (await dest.getTransaction(verifications.log.transactionHash)).from prettyTable.call(this, { merkleRoot: verifications.report.merkleRoot, min: Number(verifications.report.minSeqNr), max: Number(verifications.report.maxSeqNr), origin: formatDisplayAddress(origin, destFamily), contract: formatDisplayAddress(verifications.log.address, destFamily), transactionHash: formatDisplayTxHash(verifications.log.transactionHash, destFamily), blockNumber: verifications.log.blockNumber, timestamp: `${formatDate(timestamp)} (${formatDuration(timestamp - request.log.blockTimestamp)} after request)`, }) } else { let ts = 0 for (const { timestamp } of verifications.verifications) if (timestamp && timestamp > ts) ts = timestamp prettyTable.call(this, { // sourceAddress lives on the source chain, destAddress/CCVs on dest ...(prettyFormat( { verifications: verifications.verifications.map((v) => ({ ccvData: v.ccvData, sourceAddress: formatDisplayAddress(v.sourceAddress, sourceFamily), destAddress: formatDisplayAddress(v.destAddress, destFamily), ...(v.timestamp != null && { timestamp: v.timestamp }), })), verificationPolicy: verifications.verificationPolicy, }, destFamily, ) as Record), ...(ts && { timestamp: `${formatDate(ts)} (${formatDuration(ts - request.log.blockTimestamp)} after request)`, }), }) } } /** * Add line breaks to a string to fit within a specified column width * @param text - The input string to wrap * @param maxWidth - Maximum column width before wrapping * @param threshold - Percentage of maxWidth to look back for spaces (default 0.1 = 10%) * @returns The wrapped string with line breaks inserted */ function wrapText(text: string, maxWidth: number, threshold: number = 0.1): string[] { const lines: string[] = [] // First split by existing line breaks const existingLines = text.split('\n') for (const line of existingLines) { const words = line.split(' ') let currentLine = '' for (const word of words) { const testLine = currentLine ? `${currentLine} ${word}` : word if (testLine.length <= maxWidth) { currentLine = testLine } else { if (currentLine) { lines.push(currentLine) currentLine = word } else { // Word is longer than maxWidth, break it const thresholdDistance = Math.floor(maxWidth * threshold) let remaining = word while (remaining.length > maxWidth) { let breakPoint = maxWidth // Look for a good break point within threshold distance for (let i = maxWidth - thresholdDistance; i < maxWidth; i++) { if (remaining[i] === '-' || remaining[i] === '_') { breakPoint = i + 1 break } } lines.push(remaining.substring(0, breakPoint)) remaining = remaining.substring(breakPoint) } currentLine = remaining } } } if (currentLine) { lines.push(currentLine) } } return lines } function flatten(val: unknown, path: (string | number)[] = []): [(string | number)[], unknown][] { if (Array.isArray(val)) { if (val.length) return val.map((v: unknown, i: number) => flatten(v, [...path, i])).flat(1) } else if (val && typeof val === 'object') { if (Object.keys(val).length === 0) return [[path, val]] return Object.entries(val) .map(([k, v]) => flatten(v, [...path, k])) .flat(1) } return [[path, val]] } /** * Prints a formatted table of key-value pairs. * @param args - Key-value pairs to print. * @param opts - Formatting options. */ export function prettyTable(this: Ctx, args: Record, opts = { spcount: 0 }) { const out: (readonly [string, unknown])[] = [] for (const [path, value] of flatten(args)) { const last = path[path.length - 1] const key = j(...path) if (isBytesLike(value)) { out.push( ...Object.entries(formatData(key, typeof value !== 'string' ? hexlify(value) : value)), ) } else if (typeof value === 'string') { out.push( ...wrapText(value, Math.max(100, +(process.env.COLUMNS || 80) * 0.9)).map( (l, i) => [!i ? key : ' '.repeat(opts.spcount++), l] as const, ), ) } else if ( typeof last === 'string' && last.toLowerCase().includes('timestamp') && typeof value === 'number' ) { out.push([key, formatDate(value)]) } else if (last?.toString().match(/\berr$/) && value === '0x') { out.push([key, '0x [possibly out-of-gas or abi.decode error]']) } else if (typeof value === 'bigint' && last?.toString().match(/[Ss]el(ector)?$/)) { try { const val = `${value} [${networkInfo(value).name}]` out.push([key, val]) } catch { out.push([key, value]) } } else out.push([key, value]) } return this.output.table(Object.fromEntries(out)) } /** * Prints a CCIP execution receipt in a human-readable format. * @param receipt - CCIP execution receipt to print. * @param request - CCIP request for timestamp comparison. * @param origin - Optional transaction origin address. */ export function prettyReceipt( this: Ctx, receipt: CCIPExecution, request: PickDeep, origin?: string, ) { const destFamily = networkInfo(request.lane.destChainSelector).family prettyTable.call(this, { state: receipt.receipt.state === ExecutionState.Success ? '✅ success' : '❌ failed', ...(!!( receipt.receipt.state !== ExecutionState.Success || (receipt.receipt.returnData && receipt.receipt.returnData !== '0x') ) && { returnData: receipt.error || receipt.receipt.returnData }), ...(!!receipt.receipt.gasUsed && { gasUsed: Number(receipt.receipt.gasUsed) }), ...(!!origin && { origin: formatDisplayAddress(origin, destFamily) }), contract: formatDisplayAddress(receipt.log.address, destFamily), transactionHash: formatDisplayTxHash(receipt.log.transactionHash, destFamily), logIndex: receipt.log.index, blockNumber: receipt.log.blockNumber, timestamp: `${formatDate(receipt.log.blockTimestamp)} (${formatDuration(receipt.log.blockTimestamp - request.log.blockTimestamp)} after request)`, }) } /** * Format a CCIPError with recovery hints for user-friendly display. * @param err - Error to format. * @param verbose - If true, include stack trace for debugging. * @returns Formatted error string if CCIPError, null otherwise. */ export function formatCCIPError(err: unknown, verbose = false): string | null { if (!CCIPError.isCCIPError(err)) return null const lines: string[] = [] lines.push(`error[${err.code}]: ${err.message}`) if (Object.keys(err.context).length > 0) { lines.push(' context:') for (const [key, value] of Object.entries(err.context)) { lines.push(` ${key}: ${util.inspect(value)}`) } } if (err.recovery) { lines.push(` help: ${err.recovery}`) } if (err.isTransient) { let note = 'this error may resolve on retry' if (err.retryAfterMs) { note += ` (wait ${Math.round(err.retryAfterMs / 1000)}s)` } lines.push(` note: ${note}`) } if (verbose && err.stack) { lines.push('') lines.push(' Stack trace:') const stackLines = err.stack.split('\n').slice(1) for (const line of stackLines) { lines.push(` ${line}`) } } return lines.join('\n') } /** * Logs a parsed error message if the error can be decoded. * @param err - Error to parse and log. * @returns True if error was successfully parsed and logged. */ export function logParsedError(this: Ctx, err: unknown): boolean { // First check if it's a CCIPError with recovery hints const formatted = formatCCIPError(err, this.verbose) if (formatted) { this.logger.error(formatted) return true } // Then try chain-specific parsing for revert data for (const chain of Object.values(supportedChains)) { const parsed = chain.parse?.(err) if (!parsed) continue const { method, Instruction: instruction, ...rest } = parsed if (method || instruction) { this.logger.error( `error: Failed to call "${(method || instruction) as string}"`, ...Object.entries(rest) .map(([k, e]) => [`\n${k.substring(0, 1).toUpperCase()}${k.substring(1)} =`, e]) .flat(1), ) } else { this.logger.error('error:', parsed) } return true } return false } /** * Parse `--transfer-tokens token1=amount1 token2=amount2 ...` into `{ token, amount }[]`. * * Decimals resolve internally, with the standard fallback chain (see `resolveTokenDecimals`): * the token's own on-chain `decimals()` view, else its pool's declared decimals * (`TokenPoolConfig.decimals`, pool v1.5.1+ — the authoritative source, since the pool uses * exactly these decimals for its own conversion). The family default does NOT apply here: * these decimals determine the actual transfer amount, so a lookup failure must surface * rather than silently parse the amount at a guessed precision. **/ export async function parseTokenAmounts( source: Chain, transferTokens: readonly string[], router?: string, ): Promise<{ token: string; amount: bigint }[]> { return Promise.all( transferTokens.map(async (tokenAmount) => { const [token, amount_] = tokenAmount.split('=') as [string, string] // the pool is resolved from the TokenAdminRegistry behind the `router` (an OnRamp also // works); a lookup failure propagates — it must not fall through to a guessed default const decimals = await resolveTokenDecimals( source, token, async () => { if (!router) return undefined const registry = await source.getTokenAdminRegistryFor(router) return (await source.getRegistryTokenConfig(registry, token)).tokenPool }, { familyDefault: false }, ) return { token, amount: parseUnits(amount_, decimals) } }), ) } /** * Yield resolved promises (like Promise.all), but as they resolve. * Throws as soon as any promise rejects. * * @param promises - Promises to resolve (can be an array or a generator) * @returns Resolved values as they resolve **/ export async function* yieldResolved(promises: Iterable>): AsyncGenerator { const queue: ({ ok: true; value: T } | { ok: false; err: unknown })[] = [] let resolve: (() => void) | null = null let remaining = 0 let done = false try { for (const p of promises) { remaining++ p.then( (value) => { if (done) return queue.push({ ok: true, value }) resolve?.() resolve = null }, (err) => { if (done) return queue.push({ ok: false, err }) resolve?.() resolve = null }, ) } while (remaining > 0) { if (queue.length === 0) { await new Promise((res) => { resolve = res }) resolve = null } while (queue.length > 0) { const result = queue.shift()! remaining-- if (!result.ok) throw result.err yield result.value } } } finally { done = true resolve = null queue.length = 0 } } /** * Create context for command execution. * * Output architecture (following Vercel CLI / gws / gh patterns): * - `output.write/table` → stdout (data only) * - `logger.info/warn/error/debug` → stderr (status/diagnostics) * * @param argv - yargs argv containing verbose flag * @returns context object with abort signal, output, and logger */ export function getCtx(argv: { verbose?: boolean }): [ctx: Ctx, destroy: (reason?: unknown) => void] { const ac = new AbortController() // Logger: always stderr const stderrConsole = new Console(process.stderr, process.stderr, true) const logger: Ctx['logger'] = { info: stderrConsole.info.bind(stderrConsole), warn: stderrConsole.warn.bind(stderrConsole), error: stderrConsole.error.bind(stderrConsole), debug: argv.verbose ? stderrConsole.debug.bind(stderrConsole) : () => {}, } // Output: always stdout const stdoutConsole = new Console(process.stdout, process.stderr, true) const output: Ctx['output'] = { write: stdoutConsole.log.bind(stdoutConsole), table: stdoutConsole.table.bind(stdoutConsole), } if (argv.verbose) logger.debug('Verbose mode enabled') return [ { abort: ac.signal, output, logger, verbose: argv.verbose, verifierTransport: grpcVerifierTransport(), }, ac.abort.bind(ac), ] }