/** * CCIP CLI Show Command * * Displays detailed information about a CCIP message, including its status, * commit report, and execution receipts across source and destination chains. * * @example * ```bash * # Show message details * ccip-cli show 0xSourceTxHash... * * # Wait for execution * ccip-cli show 0xSourceTxHash... --wait * * # Output as JSON * ccip-cli show 0xSourceTxHash... --format json * ``` * * @packageDocumentation */ import { type CCIPRequest, type Chain, type ChainGetter, type ChainTransaction, CCIPAPIClient, CCIPExecTxRevertedError, CCIPMessageIdNotFoundError, CCIPTransactionNotFoundError, ExecutionState, MessageStatus, discoverOffRamp, isSupportedTxHash, jsonStringify, } from '@chainlink/ccip-sdk/src/index.ts' import { isHexString } from 'ethers' import type { Argv } from 'yargs' import type { GlobalOpts } from '../index.ts' import { fetchChainsFromRpcs, resolveIndexer } from '../providers/index.ts' import { verifiersOption } from '../verifiers/options.ts' import { type Ctx, Format } from './types.ts' import { getCtx, logParsedError, prettyReceipt, prettyRequest, prettyTable, prettyVerifications, selectRequest, withDateTimestamp, } from './utils.ts' export const command = ['show ', '* '] export const describe = 'Show details of a CCIP request' /** * Yargs builder for the show command. * @param yargs - Yargs instance. * @returns Configured yargs instance with command options. */ export const builder = (yargs: Argv) => yargs .positional('tx-hash-or-id', { type: 'string', demandOption: true, describe: 'transaction hash or message ID (32-byte hex) of the CCIP request', }) .check(({ txHashOrId }) => isSupportedTxHash(txHashOrId)) .options({ 'log-index': { type: 'number', describe: 'Pre-select a message request by logIndex, if more than one in tx; by default, a selection menu is shown', }, wait: { type: 'boolean', describe: 'Wait for (first) execution', }, ...verifiersOption, }) /** * Handler for the show command. * @param argv - Command line arguments. */ export async function handler(argv: Awaited['argv']> & GlobalOpts) { const [ctx, destroy] = getCtx(argv) return showRequests(ctx, argv) .catch((err) => { process.exitCode = 1 if (!logParsedError.call(ctx, err)) ctx.logger.error(err) }) .finally(destroy) } /** * Show details of a request. * When `opts.request` is set (e.g. after `send`), skip re-fetching the source tx from RPC. */ export async function showRequests( ctx: Ctx, argv: Parameters[0], opts?: { request?: CCIPRequest; getChain?: ChainGetter }, ) { const { output, logger } = ctx // In JSON mode, accumulate all output into a single envelope so JSON.parse(stdout) works. // Fields are added as they become available; omitted if not applicable. const jsonEnvelope: | { request?: unknown; attestations?: unknown; verifications?: unknown; receipts?: unknown[] } | undefined = argv.format === Format.json ? {} : undefined const emitJsonEnvelope = () => { if (jsonEnvelope) { output.write(jsonStringify(jsonEnvelope, 2)) } } let getChain: ChainGetter let tx$: Promise<[Chain, ChainTransaction]> | undefined if (opts?.request) { getChain = opts.getChain ?? fetchChainsFromRpcs(ctx, argv) } else { const chainsResult = fetchChainsFromRpcs(ctx, argv, argv.txHashOrId) getChain = chainsResult[0] tx$ = chainsResult[1] } let source: Chain | undefined, offRamp // Track if we displayed all messages in non-interactive multi-message path let displayedAllMessages = false as boolean let request$ = opts?.request ? (async () => { try { source = await getChain(opts.request!.lane.sourceChainSelector) } catch (err) { logger.debug('Failed to resolve source chain for prebuilt request:', err) } return opts.request! })() : (async () => { const [source_, tx] = await tx$! source = source_ const messages = await source_.getMessagesInTx(tx) // Non-interactive multi-message path: display all messages and signal early return if (argv.interactive === false && argv.logIndex == null && messages.length > 1) { switch (argv.format) { case Format.log: for (const req of messages) { output.write(`message ${req.log.index} =`, withDateTimestamp(req)) } break case Format.pretty: for (const req of messages) { await prettyRequest.call(ctx, req, source) } break case Format.json: output.write(jsonStringify({ requests: messages }, 2)) break } logger.info('Use --log-index N for full details on a specific message.') displayedAllMessages = true return messages[0]! // return first to satisfy type; caller checks displayedAllMessages } return selectRequest(messages, 'to know more', argv) })() if (argv.api !== false && isHexString(argv.txHashOrId, 32)) { const apiClient = CCIPAPIClient.fromUrl( typeof argv.api === 'string' ? argv.api : undefined, ctx, ) request$ = Promise.any([request$, apiClient.getMessageById(argv.txHashOrId)]) } let request try { request = await request$ if (displayedAllMessages) return // already displayed all messages in non-interactive path if ('offRampAddress' in request.message) { offRamp = request.message.offRampAddress } else { offRamp = request.metadata?.offRamp } } catch (err) { if (err instanceof AggregateError && err.errors.length === 2) { if (!(err.errors[0] instanceof CCIPTransactionNotFoundError)) throw err.errors[0] as Error else if (!(err.errors[1] instanceof CCIPMessageIdNotFoundError)) throw err.errors[1] as Error } throw err } if (!source) { // source isn't strictly needed when fetching messageId from API, but it may be useful to print // more information, e.g. request's token symbols try { source = await getChain(request.lane.sourceChainSelector) } catch (err) { logger.debug( 'Fetched messageId from API, but failed find a source', request.lane.sourceChainSelector, 'RPC endpoint:', err, ) } } switch (argv.format) { case Format.log: { output.write(`message ${request.log.index} =`, withDateTimestamp(request)) break } case Format.pretty: await prettyRequest.call(ctx, request, source) break case Format.json: jsonEnvelope!.request = request break } if (request.tx.error) throw new CCIPExecTxRevertedError(request.log.transactionHash, { context: { error: request.tx.error }, }) if (argv.wait === false) { emitJsonEnvelope() return // `false` used by call at end of `send` command without `--wait` } const pendingAc = new AbortController() const pending = AbortSignal.any([pendingAc.signal, ctx.abort]) const finalizedAc = new AbortController() const finalizedSignal = AbortSignal.any([finalizedAc.signal, pending]) const cancelPending = () => pendingAc.abort() const isStopped = () => pending.aborted let commitFound = false as boolean // Stop late background output even when an RPC does not support cancellation. const pendingCtx: Ctx = { ...ctx, output: { write: (...args) => { if (!isStopped()) output.write(...args) }, table: (...args) => { if (!isStopped()) output.table(...args) }, }, } const finality$ = (async () => { if (argv.wait) { logger.info(`[${MessageStatus.Sent}] Waiting for source chain finalization...`) if (!source) return const finalized = await source.waitFinalized({ log: request.log, abort: finalizedSignal, }) if (isStopped()) return // A commit can cancel finality without cancelling the independent attestation wait. if (finalized && !finalizedSignal.aborted) logger.info(`[${MessageStatus.SourceFinalized}] Source chain finalized`) if (!commitFound) logger.info(`[${MessageStatus.SourceFinalized}] Waiting for commit on destination chain...`) } })().catch((err) => { if (!finalizedSignal.aborted) logger.warn( 'Source finalization unavailable', err instanceof Error && !argv.verbose ? err.message : err, ) }) // Issuer APIs can become ready while a source-finality RPC is still in flight. const attestations$ = (async () => { if (isStopped()) return const offchainTokenData = await source?.getOffchainTokenData(request, { watch: argv.wait ? pending : undefined, }) if (isStopped()) return if (offchainTokenData?.length && offchainTokenData.some((d) => !!d)) { switch (argv.format) { case Format.log: { output.write('attestations =', offchainTokenData) break } case Format.pretty: output.write('Attestations:') for (const attestation of offchainTokenData) { if (!attestation) continue const { _tag: type, ...rest } = attestation prettyTable.call(ctx, { type, ...rest }) } break case Format.json: jsonEnvelope!.attestations = offchainTokenData break } } if ( !argv.wait && !request.metadata?.receiptTransactionHash && argv.format !== Format.json && !ctx.abort.aborted ) output.write('Commit (dest):') })().catch((err) => { if (!isStopped()) logger.warn( 'Attestations unavailable', err instanceof Error && !argv.verbose ? err.message : err, ) }) const finalized$ = Promise.all([finality$, attestations$]) // Stop the background waits on every exit path, errors included. try { let dest!: Chain try { dest = await getChain(request.lane.destChainSelector) } catch (err) { logger.debug( 'No dest RPC available for', request.lane.destChainSelector, '— emitting partial result:', err, ) emitJsonEnvelope() throw err } let execs$, verifications$ let receiptsHeaderPrinted = false const printReceiptsHeader = () => { if (!receiptsHeaderPrinted && argv.format !== Format.json) { output.write('Receipts (dest):') receiptsHeaderPrinted = true } } if (request.metadata?.receiptTransactionHash) { // if we got last receipt metadata from api, just fetch it instead of scanning (faster) execs$ = await dest.getExecutionReceiptsInTx(request.metadata.receiptTransactionHash, { offRamp, messageId: request.message.messageId, sourceChainSelector: request.message.sourceChainSelector, sequenceNumber: request.message.sequenceNumber, }) if (!argv.wait) await finalized$ } else { offRamp ??= await discoverOffRamp(source!, dest, request.lane, source) const watch = argv.wait ? pending : undefined verifications$ = (async () => { const indexer = resolveIndexer(argv, dest, logger, source) const verifications = await dest.getVerifications({ offRamp, request, ...argv, indexer, watch, }) if (isStopped()) return commitFound = true if (argv.wait) finalizedAc.abort() else await finalized$ if (isStopped()) return if (argv.wait) logger.info(`[${MessageStatus.Committed}] Commit report accepted on destination chain`) switch (argv.format) { case Format.log: output.write('commit =', verifications) break case Format.pretty: await prettyVerifications.call(pendingCtx, dest, verifications, request) break case Format.json: jsonEnvelope!.verifications = verifications break } if (isStopped()) return if (argv.wait) logger.info(`[${MessageStatus.Blessed}] Waiting for execution on destination chain...`) else printReceiptsHeader() return verifications })().catch((err) => { if (isStopped()) return logger.warn( 'Verifications unavailable', err instanceof Error && !argv.verbose ? err.message : err, ) if (!argv.wait) printReceiptsHeader() return undefined }) execs$ = dest.getExecutionReceipts({ ...argv, offRamp, messageId: request.message.messageId, sourceChainSelector: request.message.sourceChainSelector, sequenceNumber: request.message.sequenceNumber, startTime: request.log.blockTimestamp, verifications: !argv.wait ? await verifications$ : undefined, watch: argv.wait && pending, }) } let found = false for await (const exec of execs$) { let origin = exec.log.tx?.from const origin$ = origin == null && argv.format === Format.pretty ? (async () => { origin = (await dest.getTransaction(exec.log.transactionHash)).from })().catch(() => {}) : undefined if (argv.wait) { // An execution is authoritative. Give data that is ready (e.g. for a message that was // executed before the wait started) a short grace, then cancel the slower waits. await withGrace(Promise.all([finalized$, verifications$, origin$]), EXEC_GRACE_MS) cancelPending() } else await Promise.all([verifications$, origin$]) const status = exec.receipt.state === ExecutionState.Success ? MessageStatus.Success : MessageStatus.Failed const statusMessage = exec.receipt.state === ExecutionState.Success ? 'Message executed on destination chain' : 'Message execution failed on destination chain' logger.info(`[${status}] ${statusMessage}`) switch (argv.format) { case Format.log: output.write('receipt =', withDateTimestamp(exec)) break case Format.pretty: prettyReceipt.call(ctx, exec, request, origin) break case Format.json: jsonEnvelope!.receipts ??= [] jsonEnvelope!.receipts.push(exec) break } found = true if (argv.wait) break } if (!found) { cancelPending() if (!ctx.abort.aborted) logger.warn(`No execution receipt found for request`) } emitJsonEnvelope() } finally { cancelPending() } } /** Longest time a found execution waits for commit, attestation and origin data in `--wait`. */ const EXEC_GRACE_MS = 5_000 /** Wait for `work` to settle, but not longer than `ms`. */ async function withGrace(work: Promise, ms: number) { let timer: ReturnType | undefined try { await Promise.race([work, new Promise((resolve) => (timer = setTimeout(resolve, ms)))]) } finally { clearTimeout(timer) } }