/** * CCIP CLI Send Command * * Sends a cross-chain message via CCIP. Supports data payloads, token transfers, * custom gas limits, and various fee payment options. * * @example * ```bash * # Send a message with data * ccip-cli send -s sepolia -d fuji -r 0xRouter... --to 0xReceiver... --data "hello" * * # Send tokens * ccip-cli send -s sepolia -d fuji -r 0xRouter... -t 0xToken=1.5 * * # Pay fee in LINK * ccip-cli send -s sepolia -d fuji -r 0xRouter... --fee-token LINK * ``` * * @packageDocumentation */ import { type ChainStatic, type MessageInput, CCIPArgumentInvalidError, CCIPDestSimulationUnavailableError, CCIPInsufficientBalanceError, CCIPMethodUnsupportedError, CCIPTokenNotFoundError, ChainFamily, decodeAddress, estimateReceiveExecution, getDataBytes, getRequiredCCVs, jsonParse, jsonStringify, networkInfo, } from '@chainlink/ccip-sdk/src/index.ts' import { type BytesLike, AbiCoder, formatUnits, randomBytes, toUtf8Bytes } from 'ethers' import type { Argv } from 'yargs' import type { GlobalOpts } from '../index.ts' import { fetchChainsFromRpcs, loadChainWallet } from '../providers/index.ts' import { showRequests } from './show.ts' import { type Ctx, Format } from './types.ts' import { formatDisplayAddress, formatDisplayTxHash, getCtx, logParsedError, parseTokenAmounts, } from './utils.ts' export const command = 'send' export const describe = 'Send a CCIP message from source to destination chain' /** * Yargs builder for the send command. * @param yargs - Yargs instance. * @returns Configured yargs instance with command options. */ export const builder = (yargs: Argv) => yargs .option('source', { alias: 's', type: 'string', demandOption: true, describe: 'Source chain: chainId, selector, or name', }) .option('dest', { alias: 'd', type: 'string', demandOption: true, describe: 'Destination chain: chainId, selector, or name', }) .option('router', { alias: 'r', type: 'string', describe: 'Router contract address on source', }) .options({ receiver: { alias: 'to', type: 'string', describe: 'Receiver address on destination; defaults to sender if same chain family', }, data: { type: 'string', describe: 'Data payload to send (0x-bytearrays are used as is; "0x:" prefix will be string abi.encoded, otherwise it\'ll be raw-UTF-8 encoded)', }, 'gas-limit': { alias: ['L', 'compute-units'], type: 'number', describe: 'Gas limit for receiver callback; defaults to ramp config', }, 'estimate-gas-limit': { type: 'number', describe: 'Estimate gas limit with % margin (e.g., 10 for +10%)', conflicts: 'gas-limit', }, 'allow-out-of-order-exec': { alias: 'ooo', type: 'boolean', describe: 'Allow out-of-order execution (v1.5+ lanes)', }, 'tx-gas-limit': { alias: 'G', type: 'number', describe: 'Force send transaction gasLimit/computeUnits (instead of estimating)', }, 'fee-token': { type: 'string', describe: 'Fee token address or symbol (default: native)', }, 'transfer-tokens': { alias: 't', type: 'array', string: true, describe: 'Token amounts to transfer: token=amount', }, wallet: { alias: 'w', type: 'string', describe: 'Wallet: ledger[:index], foundry:, hardhat:, or private key', }, 'token-receiver': { type: 'string', describe: 'Solana token receiver (if different from program receiver)', }, account: { alias: 'receiver-object-id', type: 'array', string: true, describe: 'Solana accounts (append =rw for writable) or Sui object IDs', }, extra: { alias: 'x', type: 'array', string: true, describe: 'Extra args to pass in the message: key=value (value parsed as JSON with bigint support, fallback to string; repeated keys become arrays)', example: '-x ccvs=["0xvalue1","0xvalue2"] --extra=finality=safe', }, 'only-get-fee': { type: 'boolean', describe: 'Print fee and exit', }, 'only-estimate': { type: 'boolean', describe: 'Print gas estimate and exit', implies: 'estimate-gas-limit', }, 'only-ccvs': { type: 'boolean', describe: 'Print the destination-required CCV set (requiredCCVs/optionalCCVs/threshold) and exit. ' + 'A disallowed finality surfaces as an error.', }, 'approve-max': { type: 'boolean', describe: 'Approve max token amount instead of exact', }, wait: { type: 'boolean', default: false, describe: 'Wait for execution on destination', }, }) .check( ({ 'transfer-tokens': transferTokens }) => !transferTokens || transferTokens.every((t) => /^[^=]+=\d+(\.\d+)?$/.test(t)), ) .check(({ extra }) => !extra || extra.every((e) => /^[^=]+=/.test(e))) .example([ [ 'ccip-cli send -s ethereum-testnet-sepolia -d arbitrum-sepolia -r 0x0BF3dE8c5D3e8A2B34D2BEeB17ABfCeBaf363A59 --only-get-fee', 'Get fee estimate', ], [ 'ccip-cli send -s ethereum-testnet-sepolia -d arbitrum-sepolia -r 0x0BF3... --to 0xABC... --data "Hello"', 'Send message with data', ], ]) /** * Handler for the send command. * @param argv - Command line arguments. */ export async function handler(argv: Awaited['argv']> & GlobalOpts) { const [ctx, destroy] = getCtx(argv) return sendMessage(ctx, argv) .catch((err) => { process.exitCode = 1 if (!logParsedError.call(ctx, err)) ctx.logger.error(err) }) .finally(destroy) } /** * Parse --extra=key=value entries into a record. * Values are parsed as JSON with bigint support for integers; fallback to string. * Repeated keys are accumulated into an array. * * @example * `assert.eq(parseExtraArgs(['ccvs=["0xvalue1", "0xvalue2"]', 'finality=safe', 'flag=true']), { ccvs: ["0xvalue1", "0xvalue2"], finality: 'safe', flag: true })` */ function parseExtraArgs(extra: readonly string[] | undefined): Record { if (!extra?.length) return {} const result: Record = {} for (const entry of extra) { const eqIdx = entry.indexOf('=') const key = entry.substring(0, eqIdx) const raw = entry.substring(eqIdx + 1) let value: unknown = raw // Bare 0x literals are hex (addresses, calldata); yaml/json parse would coerce them to bigint. if (!/^0x[0-9a-fA-F]*$/i.test(raw)) { try { value = jsonParse(raw) } catch { // pass } } if (key in result) { const existing = result[key] result[key] = Array.isArray(existing) ? (existing as unknown[]).concat([value]) : ([existing, value] as unknown[]) } else { result[key] = value } } return result } async function sendMessage( ctx: Ctx, argv: Awaited['argv']> & GlobalOpts, ) { const { output, logger } = ctx const sourceNetwork = networkInfo(argv.source) const destNetwork = networkInfo(argv.dest) const getChain = fetchChainsFromRpcs(ctx, argv) const source = await getChain(sourceNetwork.name) const router = argv.router ? argv.router : '' // On Canton, router can be empty if (sourceNetwork.family !== 'CANTON') { decodeAddress(router, sourceNetwork.family) } let data: BytesLike | undefined if (argv.data) { try { // 0x or base64 bytearrays data = getDataBytes(argv.data) } catch (_) { if (argv.data.startsWith('0x:')) { // if data is a non-bytearray string prefixed with "0x:", abi.encode as string data = AbiCoder.defaultAbiCoder().encode(['string'], [argv.data.substring(3)]) } else data = toUtf8Bytes(argv.data) // otherwise, raw string, encode as UTF-8 bytes } } const tokenAmounts: { token: string; amount: bigint }[] = argv.transferTokens?.length ? await parseTokenAmounts(source, argv.transferTokens, router) : [] let receiver = argv.receiver let accounts, accountIsWritableBitmap = 0n if (destNetwork.family === ChainFamily.Solana) { // parse accounts with or without `=rw` suffix if (argv.account?.length) { accounts = argv.account.map((account, i) => { if (account.endsWith('=rw')) { accountIsWritableBitmap |= 1n << BigInt(i) account = account.substring(0, account.length - 3) } return account }) } } let walletAddress, wallet if (!receiver) { try { if (sourceNetwork.family !== destNetwork.family) throw new CCIPArgumentInvalidError('receiver', 'required for cross-family transfers') ;[walletAddress, wallet] = await loadChainWallet(source, argv, logger) } catch (err) { if (!argv.onlyGetFee && !argv.onlyEstimate) throw err // if we can't load wallet for receiver, and it's only for estimation, generate a random one walletAddress = decodeAddress( randomBytes( destNetwork.family === ChainFamily.EVM ? 20 : destNetwork.family === ChainFamily.TON ? 36 : 32, ), destNetwork.family, ) } receiver = walletAddress // send to self if same family } // builds a catch-all extraArgs object, which can be massaged by // [[Chain.buildMessageForDest]] to create suitable extraArgs with defaults if needed // --extra entries are spread last so they take priority over code-generated values const extraArgs = { ...(argv.allowOutOfOrderExec != null && { allowOutOfOrderExecution: !!argv.allowOutOfOrderExec, }), ...(argv.gasLimit == null ? {} : destNetwork.family === ChainFamily.Solana ? { computeUnits: BigInt(argv.gasLimit) } : { gasLimit: BigInt(argv.gasLimit) }), ...(!!argv.tokenReceiver && { tokenReceiver: argv.tokenReceiver }), ...(!!accounts && { accounts, accountIsWritableBitmap }), // accounts also used as Sui receiverObjectIds ...parseExtraArgs(argv.extra), } if (argv.onlyCcvs) { // --only-ccvs: read the destination-required CCV set (and finality verdict) and exit; no send. const dest = await getChain(destNetwork.chainSelector) if (!walletAddress) { try { ;[walletAddress, wallet] = await loadChainWallet(source, argv, logger) } catch { // sender is optional here; omitting it yields the lane-default (not sender-scoped) CCV view } } const ccvs = await getRequiredCCVs({ source, dest, routerOrRamp: router, message: { sender: walletAddress, receiver, data, tokenAmounts, ...extraArgs }, }) if (argv.format === Format.json) { output.write(jsonStringify(ccvs, 2)) } else { output.write('requiredCCVs :', ccvs.requiredCCVs) output.write('optionalCCVs :', ccvs.optionalCCVs) output.write('optionalThreshold :', ccvs.optionalThreshold) } return } if (argv.estimateGasLimit == null || argv.estimateGasLimit > -100) try { const dest = await getChain(destNetwork.chainSelector) if (!walletAddress) { try { ;[walletAddress, wallet] = await loadChainWallet(source, argv, logger) } catch { // pass undefined sender as default } } const estimated = await estimateReceiveExecution({ source, dest, routerOrRamp: router, message: { sender: walletAddress, receiver, data, tokenAmounts, ...extraArgs, }, }) argv.gasLimit = Math.ceil(estimated * (1 + (argv.estimateGasLimit ?? 10) / 100)) if (argv.onlyEstimate) { // --only-estimate: the estimate IS the data output if (argv.format === Format.json) { output.write( jsonStringify( { estimated, bufferPercent: argv.estimateGasLimit ?? 0, withBuffer: argv.gasLimit, }, 2, ), ) } else { output.write( 'Estimated', destNetwork.family === ChainFamily.Solana ? 'computeUnits' : 'gasLimit', 'for sender =', walletAddress && formatDisplayAddress(walletAddress, sourceNetwork.family), ':', estimated, ...(argv.estimateGasLimit ? ['+', argv.estimateGasLimit, '% =', argv.gasLimit] : []), ) } return } // When continuing to send, the estimate is a status message logger.info( 'Estimated gasLimit for sender =', walletAddress && formatDisplayAddress(walletAddress, sourceNetwork.family), ':', estimated, ...(argv.estimateGasLimit ? ['+', argv.estimateGasLimit, '% =', argv.gasLimit] : []), ) } catch (err) { // if user requested estimation explicitly, surface any error if (argv.estimateGasLimit != null || argv.onlyEstimate) throw err if (err instanceof CCIPMethodUnsupportedError) { logger.debug('estimateReceiveExecution not supported for', destNetwork.name, '—', err) } else if (err instanceof CCIPDestSimulationUnavailableError) { // inconclusive, not a verdict (dest RPC unreachable, or an attestation-consuming pool // that fundamentally can't be checked pre-send) — by default warn and continue with // default gasLimit; pass --estimate-gas-limit/--only-estimate to make it fatal logger.warn( 'Destination preflight could not be performed — continuing without it:', err.message, ) } else { // definitive verdicts (e.g. CCIPDestExecutionRevertError, CCIPRateLimitExceededError) // always block the send throw err } } let feeToken, feeTokenInfo if (argv.feeToken) { try { feeToken = (source.constructor as ChainStatic).getAddress(argv.feeToken) feeTokenInfo = await source.getTokenInfo(feeToken) } catch (_) { const feeTokens = await source.getFeeTokens(router) logger.debug('supported feeTokens:', feeTokens) for (const [token, info] of Object.entries(feeTokens)) { if (info.symbol === 'UNKNOWN' || info.symbol !== argv.feeToken) continue feeToken = token feeTokenInfo = info break } if (!feeTokenInfo) throw new CCIPTokenNotFoundError(argv.feeToken) } } else { const nativeToken = await source.getNativeTokenForRouter(router) feeTokenInfo = await source.getTokenInfo(nativeToken) } const message: MessageInput = { receiver, data, extraArgs, feeToken, // feeToken==ZeroAddress means native tokenAmounts, } // calculate fee const fee = await source.getFee({ ...argv, router, destChainSelector: destNetwork.chainSelector, message, }) const displaySymbol = !argv.feeToken && feeTokenInfo.symbol.startsWith('W') ? feeTokenInfo.symbol.substring(1) : feeTokenInfo.symbol if (argv.onlyGetFee) { // --only-get-fee: the fee IS the data output if (argv.format === Format.json) { output.write( jsonStringify( { fee: fee.toString(), feeFormatted: formatUnits(fee, feeTokenInfo.decimals), feeToken: feeToken ?? 'native', feeTokenSymbol: displaySymbol, feeTokenDecimals: feeTokenInfo.decimals, }, 2, ), ) } else { output.write('Fee:', fee, '=', formatUnits(fee, feeTokenInfo.decimals), displaySymbol) } return } // When continuing to send, the fee is a status message logger.info('Fee:', fee, '=', formatUnits(fee, feeTokenInfo.decimals), displaySymbol) if (!walletAddress) [walletAddress, wallet] = await loadChainWallet(source, argv, logger) // Check sender has sufficient balance for fee try { const balance = await source.getBalance({ holder: walletAddress, token: feeToken }) if (balance < fee) { const symbol = feeTokenInfo.symbol.startsWith('W') && !feeToken ? feeTokenInfo.symbol.substring(1) : feeTokenInfo.symbol throw new CCIPInsufficientBalanceError( formatUnits(balance, feeTokenInfo.decimals), formatUnits(fee, feeTokenInfo.decimals), symbol, ) } } catch (e) { // may fail for chains that don't implement getBalance yet; log and continue if (e instanceof CCIPInsufficientBalanceError) throw e logger.debug('Balance check skipped:', e) } const request = await source.sendMessage({ ...argv, router, destChainSelector: destNetwork.chainSelector, message: { ...message, fee }, wallet, }) logger.info( '🚀 Sending message to', receiver && formatDisplayAddress(receiver, destNetwork.family), '@', destNetwork.name, ', tx =>', formatDisplayTxHash(request.tx.hash, sourceNetwork.family), ', messageId =>', request.message.messageId, ) await showRequests( ctx, { ...argv, txHashOrId: request.tx.hash, 'tx-hash-or-id': request.tx.hash, 'log-index': undefined, logIndex: undefined, verifiers: undefined, }, { request, getChain }, ) }