@circle-fin/app-kit 1.12.0 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bridge.mjs CHANGED
@@ -8323,6 +8323,7 @@ const swapTokenEnumSchema = z.enum([
8323
8323
  [Blockchain.Arbitrum_Sepolia]: '0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d',
8324
8324
  [Blockchain.Avalanche_Fuji]: '0x5425890298aed601595a70AB815c96711a31Bc65',
8325
8325
  [Blockchain.Base_Sepolia]: '0x036CbD53842c5426634e7929541eC2318f3dCF7e',
8326
+ [Blockchain.Celo_Alfajores_Testnet]: '0x2F25deB3848C207fc8E0c34035B3Ba7fC157602B',
8326
8327
  [Blockchain.Codex_Testnet]: '0x6d7f141b6819C2c9CC2f818e6ad549E7Ca090F8f',
8327
8328
  [Blockchain.Cronos_Testnet]: '0xEb33dc5fac03833e132593659e1dE7256aB59794',
8328
8329
  [Blockchain.Edge_Testnet]: '0x2d9F7CAD728051AA35Ecdc472a14cf8cDF5CFD6B',
@@ -9910,6 +9911,44 @@ function assertBridgeParams(params, schema) {
9910
9911
  }
9911
9912
  }
9912
9913
 
9914
+ /**
9915
+ * Canonical list of actions that do not prepare or submit transactions.
9916
+ *
9917
+ * @internal
9918
+ */ const READ_ACTION_KEYS = [
9919
+ 'token.allowance',
9920
+ 'token.balanceOf',
9921
+ 'token.name',
9922
+ 'native.balanceOf',
9923
+ 'usdc.allowance',
9924
+ 'usdc.balanceOf',
9925
+ 'usdc.name',
9926
+ 'gateway.v1.isDelegate',
9927
+ 'gateway.v1.withdrawingBalance',
9928
+ 'gateway.v1.withdrawalBlock',
9929
+ 'gateway.v1.signBurnIntents'
9930
+ ];
9931
+ const READ_ACTION_KEY_SET = new Set(READ_ACTION_KEYS);
9932
+ /**
9933
+ * Check whether a runtime value identifies a read action.
9934
+ *
9935
+ * @param action - The value to classify.
9936
+ * @returns Whether the value is a registered read-action key.
9937
+ *
9938
+ * @example
9939
+ * ```typescript
9940
+ * import { isReadActionKey } from '@core/adapter'
9941
+ *
9942
+ * if (isReadActionKey(value)) {
9943
+ * await adapter.readAction(value, params, context)
9944
+ * }
9945
+ * ```
9946
+ *
9947
+ * @internal
9948
+ */ function isReadActionKey(action) {
9949
+ return READ_ACTION_KEY_SET.has(action);
9950
+ }
9951
+
9913
9952
  /**
9914
9953
  * Resolves an operation context into concrete chain and address values.
9915
9954
  *
@@ -9989,6 +10028,72 @@ function assertBridgeParams(params, schema) {
9989
10028
  };
9990
10029
  }
9991
10030
 
10031
+ /**
10032
+ * Create the standard error for a missing or non-read action.
10033
+ *
10034
+ * @param action - The unsupported action value.
10035
+ * @returns A fatal unsupported-action error.
10036
+ *
10037
+ * @internal
10038
+ */ function createUnsupportedReadActionError(action) {
10039
+ return new KitError({
10040
+ ...InputError.UNSUPPORTED_ACTION,
10041
+ recoverability: 'FATAL',
10042
+ message: `Read action "${String(action)}" is not registered in this adapter.`
10043
+ });
10044
+ }
10045
+ /**
10046
+ * Execute a read through the adapter's dedicated read seam when available.
10047
+ *
10048
+ * @remarks
10049
+ * Fall back to the legacy `prepareAction().execute()` contract so providers
10050
+ * remain runtime-compatible with adapter versions released before `readAction`.
10051
+ * Consumers must upgrade their adapter package for reads to bypass custom
10052
+ * `prepareAction` wrappers.
10053
+ *
10054
+ * @typeParam TAdapterCapabilities - The adapter capabilities type.
10055
+ * @typeParam TActionKey - The read action key.
10056
+ * @param adapter - The adapter that owns the read action.
10057
+ * @param action - The read action to execute.
10058
+ * @param params - The parameters for the read action.
10059
+ * @param ctx - The operation context.
10060
+ * @returns The raw read-action result.
10061
+ * @throws {KitError} When `action` is not a supported read-action key.
10062
+ *
10063
+ * @example
10064
+ * ```typescript
10065
+ * import { executeAdapterReadAction } from '@core/adapter'
10066
+ * import { Ethereum } from '@core/chains'
10067
+ *
10068
+ * const allowance = await executeAdapterReadAction(
10069
+ * adapter,
10070
+ * 'token.allowance',
10071
+ * { tokenAddress, delegate },
10072
+ * { chain: Ethereum },
10073
+ * )
10074
+ * ```
10075
+ *
10076
+ * @internal
10077
+ */ async function executeAdapterReadAction(adapter, action, params, ctx) {
10078
+ if (!isReadActionKey(action)) {
10079
+ throw createUnsupportedReadActionError(action);
10080
+ }
10081
+ const runtimeAdapter = adapter;
10082
+ if (typeof runtimeAdapter.readAction === 'function') {
10083
+ return runtimeAdapter.readAction(action, params, ctx);
10084
+ }
10085
+ let request;
10086
+ try {
10087
+ request = await adapter.prepareAction(action, params, ctx);
10088
+ } catch (error) {
10089
+ if (error instanceof Error && error.message === `Action ${action} is not supported`) {
10090
+ throw createUnsupportedReadActionError(action);
10091
+ }
10092
+ throw error;
10093
+ }
10094
+ return request.execute();
10095
+ }
10096
+
9992
10097
  /**
9993
10098
  * Schema for validating hexadecimal strings with '0x' prefix.
9994
10099
  *
@@ -10198,16 +10303,15 @@ function assertBridgeParams(params, schema) {
10198
10303
  * ```
10199
10304
  */ const validateBalanceForTransaction = async (params)=>{
10200
10305
  const { amount, adapter, token, tokenAddress, operationContext } = params;
10201
- const balancePrepared = await adapter.prepareAction('usdc.balanceOf', {
10306
+ const balance = await executeAdapterReadAction(adapter, 'usdc.balanceOf', {
10202
10307
  walletAddress: operationContext.address
10203
10308
  }, operationContext);
10204
- const balance = await balancePrepared.execute();
10205
- if (BigInt(balance) < BigInt(amount)) {
10309
+ if (BigInt(String(balance)) < BigInt(amount)) {
10206
10310
  // Extract chain name from operationContext
10207
10311
  const chainName = extractChainInfo(operationContext.chain).name;
10208
10312
  // Create KitError with rich context in trace
10209
10313
  throw createInsufficientTokenBalanceError(chainName, token, {
10210
- balance: balance.toString(),
10314
+ balance: String(balance),
10211
10315
  amount,
10212
10316
  tokenAddress,
10213
10317
  walletAddress: operationContext.address
@@ -12600,6 +12704,25 @@ const DEPOSIT_FOR_BURN_GAS_LIMIT_EVM = 500_000n // buffered worst 474_078 (Sei 3
12600
12704
  ;
12601
12705
  const RECEIVE_MESSAGE_GAS_LIMIT_EVM = 400_000n // observed max 310_839; clears Cronos' calldata floor ~10x
12602
12706
  ;
12707
+ /**
12708
+ * The gas floor for each bridge step, keyed by step name.
12709
+ *
12710
+ * Two places need these and they must agree: each step module passes its floor
12711
+ * to `executePreparedChainRequest` for submission, and
12712
+ * `CCTPV2BridgingProvider.estimate()` quotes the resulting limit so a caller
12713
+ * can fund a wallet. A transaction is only admitted when the sender holds
12714
+ * `gasLimit * maxFeePerGas`, so a quote taken from anything other than the
12715
+ * submitted limit under-reports what the wallet actually needs — historically
12716
+ * the quote sat ~2.5x below the reserved limit.
12717
+ *
12718
+ * Both sides read this map so the two cannot drift apart. Change a floor here
12719
+ * and the quote moves with it; point one side at a different value and the
12720
+ * divergence is visible in review rather than silent at runtime.
12721
+ */ const BRIDGE_STEP_GAS_FLOORS_EVM = {
12722
+ approve: APPROVE_GAS_LIMIT_EVM,
12723
+ burn: DEPOSIT_FOR_BURN_GAS_LIMIT_EVM,
12724
+ mint: RECEIVE_MESSAGE_GAS_LIMIT_EVM
12725
+ };
12603
12726
  /**
12604
12727
  * The minimum finality threshold for CCTPv2 transfers.
12605
12728
  *
@@ -12618,1595 +12741,1595 @@ const RECEIVE_MESSAGE_GAS_LIMIT_EVM = 400_000n // observed max 310_839; clears C
12618
12741
  };
12619
12742
 
12620
12743
  /**
12621
- * Default configuration values for the attestation fetcher.
12622
- * @internal
12623
- */ const DEFAULT_CONFIG = {
12624
- timeout: 2_000,
12625
- maxRetries: 30 * 20,
12626
- retryDelay: 2_000,
12627
- headers: {
12628
- 'Content-Type': 'application/json'
12629
- }
12630
- };
12631
- /**
12632
- * Merges caller-provided polling overrides on top of {@link DEFAULT_CONFIG}.
12633
- *
12634
- * Headers are merged independently so caller-supplied headers augment the
12635
- * defaults (such as `Content-Type`) rather than replacing them wholesale.
12636
- *
12637
- * @param config - Caller-provided polling configuration overrides
12638
- * @param internalDefaults - Internal defaults applied before `config` (for example a
12639
- * reduced `maxRetries` for one-shot requests); `config` still wins on conflict
12640
- * @returns The effective polling configuration
12641
- * @internal
12642
- */ const mergeAttestationConfig = (config, internalDefaults = {})=>({
12643
- ...DEFAULT_CONFIG,
12644
- ...internalDefaults,
12645
- ...config,
12646
- headers: {
12647
- ...DEFAULT_CONFIG.headers,
12648
- ...internalDefaults.headers,
12649
- ...config.headers
12650
- }
12651
- });
12652
- /**
12653
- * Type guard that verifies if an unknown value matches the AttestationMessage shape
12654
- * and has all required properties.
12744
+ * CCTP bridge step names that can occur in the bridging flow.
12655
12745
  *
12656
- * @param obj - The value to check, typically an element from the messages array
12657
- * @returns True if the object matches the AttestationMessage shape, false otherwise
12658
- * @internal
12659
- */ const isValidAttestationMessage = (obj)=>{
12660
- return typeof obj === 'object' && obj !== null && 'message' in obj && 'eventNonce' in obj && 'attestation' in obj && 'decodedMessage' in obj && 'cctpVersion' in obj && 'status' in obj && typeof obj.status === 'string';
12746
+ * This object provides type safety for step names and represents all possible
12747
+ * steps that can be executed during a CCTP bridge operation. Using const assertions
12748
+ * makes this tree-shakable and follows modern TypeScript best practices.
12749
+ */ const CCTPv2StepName = {
12750
+ approve: 'approve',
12751
+ burn: 'burn',
12752
+ fetchAttestation: 'fetchAttestation',
12753
+ mint: 'mint',
12754
+ reAttest: 'reAttest'
12661
12755
  };
12662
12756
  /**
12663
- * Type guard that verifies if an attestation message is complete.
12757
+ * Conditional step transition rules for CCTP bridge flow.
12664
12758
  *
12665
- * @param message - The attestation message to check
12666
- * @returns True if the message status is 'complete', false otherwise
12667
- * @internal
12668
- */ const isCompleteAttestation = (message)=>{
12669
- return message.status === 'complete';
12759
+ * Rules are evaluated in order - the first matching condition determines the next step.
12760
+ * This approach supports flexible flow logic and makes it easy to extend with new patterns.
12761
+ */ const STEP_TRANSITION_RULES = {
12762
+ // Starting state - no steps executed yet
12763
+ '': [
12764
+ {
12765
+ condition: ()=>true,
12766
+ nextStep: CCTPv2StepName.approve,
12767
+ reason: 'Start with approval step',
12768
+ isActionable: true
12769
+ }
12770
+ ],
12771
+ // After Approve step
12772
+ [CCTPv2StepName.approve]: [
12773
+ {
12774
+ condition: (ctx)=>ctx.lastStep?.state === 'success',
12775
+ nextStep: CCTPv2StepName.burn,
12776
+ reason: 'Approval successful, proceed to burn',
12777
+ isActionable: true
12778
+ },
12779
+ {
12780
+ condition: (ctx)=>ctx.lastStep?.state === 'error',
12781
+ nextStep: CCTPv2StepName.approve,
12782
+ reason: 'Retry failed approval',
12783
+ isActionable: true
12784
+ },
12785
+ {
12786
+ condition: (ctx)=>ctx.lastStep?.state === 'noop',
12787
+ nextStep: CCTPv2StepName.burn,
12788
+ reason: 'No approval needed, proceed to burn',
12789
+ isActionable: true
12790
+ },
12791
+ {
12792
+ condition: (ctx)=>ctx.lastStep?.state === 'pending',
12793
+ nextStep: CCTPv2StepName.approve,
12794
+ reason: 'Continue pending approval',
12795
+ isActionable: false
12796
+ }
12797
+ ],
12798
+ // After Burn step
12799
+ [CCTPv2StepName.burn]: [
12800
+ {
12801
+ condition: (ctx)=>ctx.lastStep?.state === 'success',
12802
+ nextStep: CCTPv2StepName.fetchAttestation,
12803
+ reason: 'Burn successful, fetch attestation',
12804
+ isActionable: true
12805
+ },
12806
+ {
12807
+ condition: (ctx)=>ctx.lastStep?.state === 'error',
12808
+ nextStep: CCTPv2StepName.burn,
12809
+ reason: 'Retry failed burn',
12810
+ isActionable: true
12811
+ },
12812
+ {
12813
+ condition: (ctx)=>ctx.lastStep?.state === 'pending',
12814
+ nextStep: CCTPv2StepName.burn,
12815
+ reason: 'Continue pending burn',
12816
+ isActionable: false
12817
+ }
12818
+ ],
12819
+ // After FetchAttestation step
12820
+ [CCTPv2StepName.fetchAttestation]: [
12821
+ {
12822
+ condition: (ctx)=>ctx.lastStep?.state === 'success',
12823
+ nextStep: CCTPv2StepName.mint,
12824
+ reason: 'Attestation fetched, proceed to mint',
12825
+ isActionable: true
12826
+ },
12827
+ {
12828
+ condition: (ctx)=>ctx.lastStep?.state === 'error',
12829
+ nextStep: CCTPv2StepName.fetchAttestation,
12830
+ reason: 'Retry fetching attestation',
12831
+ isActionable: true
12832
+ },
12833
+ {
12834
+ condition: (ctx)=>ctx.lastStep?.state === 'pending',
12835
+ nextStep: CCTPv2StepName.fetchAttestation,
12836
+ reason: 'Continue pending attestation fetch',
12837
+ isActionable: false
12838
+ }
12839
+ ],
12840
+ // After Mint step
12841
+ [CCTPv2StepName.mint]: [
12842
+ {
12843
+ condition: (ctx)=>ctx.lastStep?.state === 'success',
12844
+ nextStep: null,
12845
+ reason: 'Bridge completed successfully',
12846
+ isActionable: false
12847
+ },
12848
+ {
12849
+ condition: (ctx)=>ctx.lastStep?.state === 'error',
12850
+ nextStep: CCTPv2StepName.mint,
12851
+ reason: 'Retry failed mint',
12852
+ isActionable: true
12853
+ },
12854
+ {
12855
+ condition: (ctx)=>ctx.lastStep?.state === 'pending',
12856
+ nextStep: CCTPv2StepName.mint,
12857
+ reason: 'Continue pending mint',
12858
+ isActionable: false
12859
+ }
12860
+ ],
12861
+ // After ReAttest step
12862
+ [CCTPv2StepName.reAttest]: [
12863
+ {
12864
+ condition: (ctx)=>ctx.lastStep?.state === 'success',
12865
+ nextStep: CCTPv2StepName.mint,
12866
+ reason: 'Re-attestation successful, proceed to mint',
12867
+ isActionable: true
12868
+ },
12869
+ {
12870
+ condition: (ctx)=>ctx.lastStep?.state === 'error',
12871
+ nextStep: CCTPv2StepName.mint,
12872
+ reason: 'Re-attestation failed, retry mint to re-initiate recovery',
12873
+ isActionable: true
12874
+ },
12875
+ {
12876
+ condition: (ctx)=>ctx.lastStep?.state === 'pending',
12877
+ nextStep: CCTPv2StepName.mint,
12878
+ reason: 'Re-attestation pending, retry mint to re-initiate recovery',
12879
+ isActionable: true
12880
+ }
12881
+ ]
12670
12882
  };
12671
12883
  /**
12672
- * Type guard that verifies if an unknown value has the correct structure
12673
- * for an AttestationResponse, regardless of attestation completion status.
12884
+ * Analyze bridge steps to determine retry feasibility and continuation point.
12674
12885
  *
12675
- * @param obj - The value to check, typically a parsed JSON response
12676
- * @returns True if the object matches the AttestationResponse shape
12677
- * @internal
12678
- */ const hasValidAttestationStructure = (obj)=>{
12679
- if (typeof obj !== 'object' || obj === null || !('messages' in obj) || !Array.isArray(obj.messages)) {
12680
- return false;
12681
- }
12682
- const messages = obj.messages;
12683
- // Validate all messages have the correct shape
12684
- return messages.every(isValidAttestationMessage);
12685
- };
12686
- /**
12687
- * Type guard that verifies if an unknown value matches the AttestationResponse shape
12688
- * and contains a complete attestation.
12886
+ * This function examines the current state of bridge steps to determine the optimal
12887
+ * continuation strategy. It uses a rule-based approach that makes it easy to extend
12888
+ * with new flow patterns and step types in the future.
12689
12889
  *
12690
- * This function performs runtime validation to ensure that the provided value
12691
- * conforms to the expected structure of an AttestationResponse and has at least
12692
- * one complete attestation. It checks that:
12693
- * 1. The value has valid AttestationResponse structure
12694
- * 2. At least one message has status 'complete'
12890
+ * The current analysis supports the standard CCTP flow:
12891
+ * **Traditional flow**: Approve Burn FetchAttestation Mint
12695
12892
  *
12696
- * @remarks
12697
- * This type guard is used internally by the attestation fetcher to validate
12698
- * responses from the IRIS API before processing them. It provides runtime
12699
- * type safety for data coming from the network and ensures we have a complete
12700
- * attestation before proceeding.
12701
- *
12702
- * If the response has valid structure but no complete attestation yet,
12703
- * it throws a retryable error. If the response structure is invalid,
12704
- * it throws a non-retryable validation error.
12893
+ * Key features:
12894
+ * - Rule-based transitions: Easy to extend with new step types and logic
12895
+ * - Context-aware decisions: Considers execution history and step states
12896
+ * - Actionable logic: Distinguishes between steps requiring user action vs waiting
12897
+ * - Terminal states: Properly handles completion and non-actionable states
12705
12898
  *
12706
- * @param obj - The value to check, typically a parsed JSON response
12707
- * @returns True if the object matches the AttestationResponse shape and has a complete attestation
12708
- * @throws {Error} With "Invalid attestation response structure" if structure is invalid (non-retryable)
12709
- * @throws {Error} With "Attestation not ready" if no complete attestation yet (retryable)
12899
+ * @param bridgeResult - The bridge result containing step execution history.
12900
+ * @returns Analysis result with continuation step and actionability information.
12901
+ * @throws Error when bridgeResult is invalid or contains no steps array.
12710
12902
  *
12711
12903
  * @example
12712
12904
  * ```typescript
12713
- * const response = await fetch('https://iris-api.circle.com/...')
12714
- * const data = await response.json()
12905
+ * import { analyzeSteps } from './analyzeSteps'
12715
12906
  *
12716
- * if (isAttestationResponse(data)) {
12717
- * // TypeScript now knows data is AttestationResponse with at least one complete attestation
12718
- * const completeMessage = data.messages.find(msg => msg.status === 'complete')
12719
- * console.log('Found complete attestation:', completeMessage.attestation)
12907
+ * // Failed approval step (requires user action)
12908
+ * const bridgeResult = {
12909
+ * steps: [
12910
+ * { name: 'Approve', state: 'error', errorMessage: 'User rejected' }
12911
+ * ]
12720
12912
  * }
12721
- * ```
12722
- */ const isAttestationResponse = (obj)=>{
12723
- // First check if the structure is valid
12724
- if (!hasValidAttestationStructure(obj)) {
12725
- // If structure is invalid, this is a permanent failure - don't retry
12726
- throw new Error('Invalid attestation response structure');
12727
- }
12728
- // Then check if at least one message is complete
12729
- if (!obj.messages.some(isCompleteAttestation)) {
12730
- // If no complete message, this is a temporary state - allow retry
12731
- throw new Error('Attestation not ready');
12732
- }
12733
- return true;
12734
- };
12735
- /**
12736
- * Builds the IRIS API URL for fetching attestation data from Circle's CCTP service.
12737
12913
  *
12738
- * Constructs a properly formatted URL for the IRIS API v2 endpoint that provides
12739
- * attestation messages for cross-chain transfers. The URL includes both the source
12740
- * domain identifier and the transaction hash as query parameters. The base URL
12741
- * is selected based on whether the operation is for testnet or mainnet.
12742
- *
12743
- * @param sourceDomainId - The CCTP domain ID of the source chain (numeric or string)
12744
- * @param transactionHash - The transaction hash of the burn operation to fetch attestation for
12745
- * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
12746
- * @returns A fully qualified URL string for the IRIS API endpoint
12914
+ * const analysis = analyzeSteps(bridgeResult)
12915
+ * // Result: { continuationStep: 'Approve', isRetryable: true,
12916
+ * // reason: 'Retry failed approval' }
12917
+ * ```
12747
12918
  *
12748
12919
  * @example
12749
12920
  * ```typescript
12750
- * // Mainnet URL
12751
- * const mainnetUrl = buildIrisUrl(1, '0xabc...', false)
12752
- * // => 'https://iris-api.circle.com/v2/messages/1?transactionHash=0xabc...'
12921
+ * // Pending transaction (requires waiting, not actionable)
12922
+ * const bridgeResult = {
12923
+ * steps: [
12924
+ * { name: 'Approve', state: 'pending' }
12925
+ * ]
12926
+ * }
12753
12927
  *
12754
- * // Testnet URL
12755
- * const testnetUrl = buildIrisUrl(1, '0xdef...', true)
12756
- * // => 'https://iris-api-sandbox.circle.com/v2/messages/1?transactionHash=0xdef...'
12928
+ * const analysis = analyzeSteps(bridgeResult)
12929
+ * // Result: { continuationStep: 'Approve', isRetryable: false,
12930
+ * // reason: 'Continue pending approval' }
12757
12931
  * ```
12758
- */ const buildIrisUrl = (sourceDomainId, transactionHash, isTestnet)=>{
12759
- const baseUrl = isTestnet ? IRIS_API_SANDBOX_BASE_URL : IRIS_API_BASE_URL;
12760
- const url = new URL(`${baseUrl}/v2/messages/${String(sourceDomainId)}`);
12761
- url.searchParams.set('transactionHash', transactionHash);
12762
- return url.toString();
12763
- };
12764
- /**
12765
- * Fetches attestation data from the IRIS API with retry and timeout handling.
12766
- *
12767
- * Polls the IRIS API until a complete attestation is available. The default
12768
- * window is sized for slow source chains where finality may take many
12769
- * confirmations.
12770
- *
12771
- * Defaults (see `DEFAULT_CONFIG`):
12772
- * - Per-attempt timeout: 2 000 ms (each HTTP request aborts after 2 s)
12773
- * - Retry delay: 2 000 ms between attempts
12774
- * - Max retries: 600 (30 × 20)
12775
- * - Total worst-case polling window: 600 × (2 000 ms + 2 000 ms) ≈ 40 minutes
12776
- *
12777
- * @param sourceDomainId - The CCTP domain ID.
12778
- * @param transactionHash - The transaction hash to fetch attestation for.
12779
- * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
12780
- * @param config - Optional configuration overrides for the attestation fetcher
12781
- * @returns The attestation response data.
12782
- * @throws If the request fails, times out, or returns invalid data.
12783
12932
  *
12784
12933
  * @example
12785
12934
  * ```typescript
12786
- * // Fetch attestation for mainnet transaction
12787
- * const response = await fetchAttestation(1, '0xabc...', false)
12788
- * console.log(`Found ${response.messages.length} attestation messages`)
12935
+ * // Completed bridge (nothing to do)
12936
+ * const bridgeResult = {
12937
+ * steps: [
12938
+ * { name: 'Approve', state: 'success' },
12939
+ * { name: 'Burn', state: 'success' },
12940
+ * { name: 'FetchAttestation', state: 'success' },
12941
+ * { name: 'Mint', state: 'success' }
12942
+ * ]
12943
+ * }
12789
12944
  *
12790
- * // Fetch with custom timeout
12791
- * const response2 = await fetchAttestation(1, '0xdef...', true, {
12792
- * timeout: 5000,
12793
- * maxRetries: 5
12794
- * })
12945
+ * const analysis = analyzeSteps(bridgeResult)
12946
+ * // Result: { continuationStep: null, isRetryable: false,
12947
+ * // reason: 'Bridge completed successfully' }
12795
12948
  * ```
12796
- */ const fetchAttestation = async (sourceDomainId, transactionHash, isTestnet, config = {})=>{
12797
- const url = buildIrisUrl(sourceDomainId, transactionHash, isTestnet);
12798
- const effectiveConfig = mergeAttestationConfig(config);
12799
- return await pollApiGet(url, isAttestationResponse, effectiveConfig);
12949
+ */ const analyzeSteps = (bridgeResult)=>{
12950
+ // Input validation
12951
+ if (!bridgeResult || !Array.isArray(bridgeResult.steps)) {
12952
+ throw new Error('Invalid bridgeResult: must contain a steps array');
12953
+ }
12954
+ const { steps } = bridgeResult;
12955
+ // Build execution context from step history
12956
+ const context = buildFlowContext(steps);
12957
+ // Determine continuation logic using rule engine
12958
+ const continuation = determineContinuationFromRules(context);
12959
+ return {
12960
+ continuationStep: continuation.nextStep,
12961
+ isActionable: continuation.isActionable,
12962
+ completedSteps: Array.from(context.completedSteps),
12963
+ failedSteps: Array.from(context.failedSteps),
12964
+ reason: continuation.reason
12965
+ };
12800
12966
  };
12801
12967
  /**
12802
- * Type guard that validates attestation response structure without requiring completion status.
12803
- *
12804
- * This is used by `fetchAttestationWithoutStatusCheck` to extract the nonce from an existing
12805
- * attestation, even if the attestation is expired or pending. Unlike `isAttestationResponse`,
12806
- * this function does not throw if no complete attestation is found.
12968
+ * Build flow context from the execution history.
12807
12969
  *
12808
- * @param obj - The value to check, typically a parsed JSON response
12809
- * @returns True if the object has valid attestation structure
12810
- * @throws {Error} With "Invalid attestation response structure" if structure is invalid
12811
- * @internal
12812
- */ const isAttestationResponseWithoutStatusCheck = (obj)=>{
12813
- if (!hasValidAttestationStructure(obj)) {
12814
- throw new Error('Invalid attestation response structure');
12970
+ * @param steps - Array of executed bridge steps.
12971
+ * @returns Flow context with execution state and history.
12972
+ */ function buildFlowContext(steps) {
12973
+ const completedSteps = new Set();
12974
+ const failedSteps = new Set();
12975
+ let lastStep;
12976
+ // Process step history to build context
12977
+ for (const step of steps){
12978
+ if (step.state === 'success' || step.state === 'noop') {
12979
+ completedSteps.add(step.name);
12980
+ } else if (step.state === 'error') {
12981
+ failedSteps.add(step.name);
12982
+ }
12983
+ // Track the last step for continuation logic
12984
+ lastStep = {
12985
+ name: step.name,
12986
+ state: step.state
12987
+ };
12815
12988
  }
12816
- return true;
12817
- };
12989
+ return {
12990
+ completedSteps,
12991
+ failedSteps,
12992
+ ...lastStep && {
12993
+ lastStep
12994
+ }
12995
+ };
12996
+ }
12818
12997
  /**
12819
- * Fetches attestation data without requiring the attestation to be complete.
12998
+ * Determine continuation step using the rule engine.
12820
12999
  *
12821
- * This function is useful for retrieving attestation data (particularly the nonce)
12822
- * from an existing transaction, even if the attestation has expired or is pending.
12823
- * It uses minimal retries since we're fetching existing data, not waiting for completion.
13000
+ * @param context - The flow context with execution history.
13001
+ * @returns Continuation decision with next step and actionability information.
13002
+ */ function determineContinuationFromRules(context) {
13003
+ const lastStepName = context.lastStep?.name;
13004
+ // Handle initial state when no steps have been executed
13005
+ if (lastStepName === undefined) {
13006
+ const rules = STEP_TRANSITION_RULES[''];
13007
+ const matchingRule = rules?.find((rule)=>rule.condition(context));
13008
+ if (!matchingRule) {
13009
+ return {
13010
+ nextStep: null,
13011
+ isActionable: false,
13012
+ reason: 'No initial state rule found'
13013
+ };
13014
+ }
13015
+ return {
13016
+ nextStep: matchingRule.nextStep,
13017
+ isActionable: matchingRule.isActionable,
13018
+ reason: matchingRule.reason
13019
+ };
13020
+ }
13021
+ // A step with an empty name is ambiguous and should be treated as an unrecoverable state.
13022
+ if (lastStepName === '') {
13023
+ return {
13024
+ nextStep: null,
13025
+ isActionable: false,
13026
+ reason: 'No transition rules defined for step with empty name'
13027
+ };
13028
+ }
13029
+ const rules = STEP_TRANSITION_RULES[lastStepName];
13030
+ if (!rules) {
13031
+ return {
13032
+ nextStep: null,
13033
+ isActionable: false,
13034
+ reason: `No transition rules defined for step: ${lastStepName}`
13035
+ };
13036
+ }
13037
+ // Find the first matching rule
13038
+ const matchingRule = rules.find((rule)=>rule.condition(context));
13039
+ if (!matchingRule) {
13040
+ return {
13041
+ nextStep: null,
13042
+ isActionable: false,
13043
+ reason: `No matching transition rule for current context`
13044
+ };
13045
+ }
13046
+ return {
13047
+ nextStep: matchingRule.nextStep,
13048
+ isActionable: matchingRule.isActionable,
13049
+ reason: matchingRule.reason
13050
+ };
13051
+ }
13052
+
13053
+ /**
13054
+ * Find a step by name in the bridge result.
12824
13055
  *
12825
- * @param sourceDomainId - The CCTP domain ID of the source chain
12826
- * @param transactionHash - The transaction hash to fetch attestation for
12827
- * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
12828
- * @param config - Optional configuration overrides
12829
- * @returns The attestation response data (may contain incomplete/expired attestations)
12830
- * @throws If the request fails, times out, or returns invalid data
13056
+ * @param result - The bridge result to search.
13057
+ * @param stepName - The name of the step to find.
13058
+ * @returns The step if found, undefined otherwise.
12831
13059
  *
12832
13060
  * @example
12833
13061
  * ```typescript
12834
- * // Fetch existing attestation to extract nonce for re-attestation
12835
- * const response = await fetchAttestationWithoutStatusCheck(1, '0xabc...', true)
12836
- * const nonce = response.messages[0]?.eventNonce
12837
- * ```
12838
- */ const fetchAttestationWithoutStatusCheck = async (sourceDomainId, transactionHash, isTestnet, config = {})=>{
12839
- const url = buildIrisUrl(sourceDomainId, transactionHash, isTestnet);
12840
- // Use minimal retries since we're just fetching existing data
12841
- const effectiveConfig = mergeAttestationConfig(config, {
12842
- maxRetries: 3
12843
- });
12844
- return await pollApiGet(url, isAttestationResponseWithoutStatusCheck, effectiveConfig);
12845
- };
13062
+ * import { findStepByName } from './findStep'
13063
+ *
13064
+ * const burnStep = findStepByName(result, 'burn')
13065
+ * if (burnStep) {
13066
+ * console.log('Burn tx:', burnStep.txHash)
13067
+ * }
13068
+ * ```
13069
+ */ function findStepByName(result, stepName) {
13070
+ return result.steps.find((step)=>step.name === stepName);
13071
+ }
12846
13072
  /**
12847
- * Type guard that validates attestation response has expirationBlock === '0'.
13073
+ * Find a pending step by name and return it with its index.
12848
13074
  *
12849
- * This is used after requestReAttestation() to poll until the attestation
12850
- * is fully re-processed and has a zero expiration block (never expires).
12851
- * The expiration block transitions from non-zero to zero when Circle
12852
- * completes processing the re-attestation request.
13075
+ * Searches for a step that matches both the step name and has a pending state.
12853
13076
  *
12854
- * @param obj - The value to check, typically a parsed JSON response
12855
- * @returns True if the attestation has expirationBlock === '0'
12856
- * @throws {Error} With "Re-attestation not yet complete" if expirationBlock is not '0'
13077
+ * @param result - The bridge result containing steps to search through.
13078
+ * @param stepName - The step name to find (e.g., 'burn', 'mint', 'fetchAttestation').
13079
+ * @returns An object containing the step and its index in the steps array.
13080
+ * @throws KitError if the specified pending step is not found.
12857
13081
  *
12858
13082
  * @example
12859
13083
  * ```typescript
12860
- * // After requesting re-attestation, use this to validate the response
12861
- * const response = await pollApiGet(url, isReAttestedAttestationResponse, config)
12862
- * // response.messages[0].decodedMessage.decodedMessageBody.expirationBlock === '0'
12863
- * ```
13084
+ * import { findPendingStep } from './findStep'
12864
13085
  *
12865
- * @internal
12866
- */ const isReAttestedAttestationResponse = (obj)=>{
12867
- // First validate the basic structure and completion status
12868
- // This will throw appropriate errors for invalid structure or incomplete attestation
12869
- if (!isAttestationResponse(obj)) ;
12870
- // Check if the first message has expirationBlock === '0'
12871
- const expirationBlock = obj.messages[0]?.decodedMessage?.decodedMessageBody?.expirationBlock;
12872
- if (expirationBlock !== '0') {
12873
- // Re-attestation not yet complete - allow retry via polling
12874
- throw new Error('Re-attestation not yet complete: waiting for expirationBlock to become 0');
13086
+ * const { step, index } = findPendingStep(result, 'burn')
13087
+ * console.log('Pending step:', step.name, 'at index:', index)
13088
+ * ```
13089
+ */ function findPendingStep(result, stepName) {
13090
+ const index = result.steps.findIndex((step)=>step.name === stepName && step.state === 'pending');
13091
+ if (index === -1) {
13092
+ throw new KitError({
13093
+ ...InputError.VALIDATION_FAILED,
13094
+ recoverability: 'FATAL',
13095
+ message: `Pending step "${stepName}" not found in result`
13096
+ });
12875
13097
  }
12876
- return true;
12877
- };
13098
+ const step = result.steps[index];
13099
+ if (!step) {
13100
+ throw new KitError({
13101
+ ...InputError.VALIDATION_FAILED,
13102
+ recoverability: 'FATAL',
13103
+ message: 'Pending step is undefined'
13104
+ });
13105
+ }
13106
+ return {
13107
+ step,
13108
+ index
13109
+ };
13110
+ }
12878
13111
  /**
12879
- * Fetches attestation data and polls until expirationBlock === '0'.
13112
+ * Get the burn transaction hash from bridge result.
12880
13113
  *
12881
- * This function is used after calling requestReAttestation() to wait until
12882
- * the attestation is fully re-processed. The expirationBlock transitions
12883
- * from non-zero to zero when Circle completes the re-attestation.
13114
+ * @param result - The bridge result.
13115
+ * @returns The burn transaction hash, or undefined if not found.
12884
13116
  *
12885
- * @param sourceDomainId - The CCTP domain ID of the source chain
12886
- * @param transactionHash - The transaction hash to fetch attestation for
12887
- * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
12888
- * @param config - Optional configuration overrides
12889
- * @returns The re-attested attestation response with expirationBlock === '0'
12890
- * @throws If the request fails, times out, or expirationBlock never becomes 0
13117
+ * @example
13118
+ * ```typescript
13119
+ * import { getBurnTxHash } from './findStep'
13120
+ *
13121
+ * const burnTxHash = getBurnTxHash(result)
13122
+ * if (burnTxHash) {
13123
+ * console.log('Burn tx hash:', burnTxHash)
13124
+ * }
13125
+ * ```
13126
+ */ function getBurnTxHash(result) {
13127
+ return findStepByName(result, CCTPv2StepName.burn)?.txHash;
13128
+ }
13129
+ /**
13130
+ * Get the attestation data from bridge result.
13131
+ *
13132
+ * @param result - The bridge result.
13133
+ * @returns The attestation data, or undefined if not found.
12891
13134
  *
12892
13135
  * @example
12893
13136
  * ```typescript
12894
- * // After requesting re-attestation
12895
- * await requestReAttestation(nonce, isTestnet)
13137
+ * import { getAttestationData } from './findStep'
12896
13138
  *
12897
- * // Poll until expirationBlock becomes 0
12898
- * const response = await fetchReAttestedAttestation(domainId, txHash, isTestnet)
12899
- * // response.messages[0].decodedMessage.decodedMessageBody.expirationBlock === '0'
13139
+ * const attestation = getAttestationData(result)
13140
+ * if (attestation) {
13141
+ * console.log('Attestation:', attestation.message)
13142
+ * }
12900
13143
  * ```
12901
- */ const fetchReAttestedAttestation = async (sourceDomainId, transactionHash, isTestnet, config = {})=>{
12902
- const url = buildIrisUrl(sourceDomainId, transactionHash, isTestnet);
12903
- const effectiveConfig = mergeAttestationConfig(config);
12904
- return await pollApiGet(url, isReAttestedAttestationResponse, effectiveConfig);
12905
- };
13144
+ */ function getAttestationData(result) {
13145
+ // Prefer reAttest data (most recent attestation after expiry)
13146
+ const reAttestStep = findStepByName(result, CCTPv2StepName.reAttest);
13147
+ if (reAttestStep?.state === 'success' && reAttestStep.data) {
13148
+ return reAttestStep.data;
13149
+ }
13150
+ // Fall back to fetchAttestation step
13151
+ const fetchStep = findStepByName(result, CCTPv2StepName.fetchAttestation);
13152
+ return fetchStep?.data;
13153
+ }
13154
+
12906
13155
  /**
12907
- * Builds the IRIS API URL for re-attestation requests.
13156
+ * Check if the analysis indicates a non-actionable pending state.
12908
13157
  *
12909
- * Constructs the URL for Circle's re-attestation endpoint that allows
12910
- * requesting a fresh attestation for an expired nonce.
13158
+ * A pending state is non-actionable when there's a continuation step but
13159
+ * the analysis marks it as not actionable, typically because we need to
13160
+ * wait for an ongoing operation to complete.
12911
13161
  *
12912
- * @param nonce - The nonce from the original attestation
12913
- * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
12914
- * @returns A fully qualified URL string for the re-attestation endpoint
13162
+ * @param analysis - The step analysis result from analyzeSteps.
13163
+ * @param result - The bridge result to check for pending steps.
13164
+ * @returns True if there is a pending step that we should wait for.
12915
13165
  *
12916
13166
  * @example
12917
13167
  * ```typescript
12918
- * // Mainnet URL
12919
- * const mainnetUrl = buildReAttestUrl('0xabc', false)
12920
- * // => 'https://iris-api.circle.com/v2/reattest/0xabc'
13168
+ * import { hasPendingState } from './stepUtils'
13169
+ * import { analyzeSteps } from '../analyzeSteps'
12921
13170
  *
12922
- * // Testnet URL
12923
- * const testnetUrl = buildReAttestUrl('0xabc', true)
12924
- * // => 'https://iris-api-sandbox.circle.com/v2/reattest/0xabc'
13171
+ * const analysis = analyzeSteps(bridgeResult)
13172
+ * if (hasPendingState(analysis, bridgeResult)) {
13173
+ * // Wait for the pending operation to complete
13174
+ * }
12925
13175
  * ```
12926
- */ const buildReAttestUrl = (nonce, isTestnet)=>{
12927
- const baseUrl = isTestnet ? IRIS_API_SANDBOX_BASE_URL : IRIS_API_BASE_URL;
12928
- const url = new URL(`${baseUrl}/v2/reattest/${nonce}`);
12929
- return url.toString();
12930
- };
12931
- /**
12932
- * Type guard that validates the re-attestation API response structure.
13176
+ */ /**
13177
+ * Evaluate a transaction receipt and return the corresponding step state
13178
+ * and error message. Centralises the success/revert/unconfirmed logic so
13179
+ * every call-site behaves identically.
12933
13180
  *
12934
- * @param obj - The value to check, typically a parsed JSON response
12935
- * @returns True if the object matches the ReAttestationResponse shape
12936
- * @throws {Error} With "Invalid re-attestation response structure" if structure is invalid
12937
- * @internal
12938
- */ const isReAttestationResponse = (obj)=>{
12939
- if (typeof obj !== 'object' || obj === null || !('message' in obj) || !('nonce' in obj) || typeof obj.message !== 'string' || typeof obj.nonce !== 'string') {
12940
- throw new Error('Invalid re-attestation response structure');
13181
+ * @param receipt - The transaction receipt containing status and block info.
13182
+ * @param txHash - The transaction hash used in error messages.
13183
+ * @returns An object with `state` and an optional `errorMessage`.
13184
+ *
13185
+ * @example
13186
+ * ```typescript
13187
+ * const outcome = evaluateTransactionOutcome(receipt, '0xabc...')
13188
+ * step.state = outcome.state
13189
+ * if (outcome.errorMessage) step.errorMessage = outcome.errorMessage
13190
+ * ```
13191
+ */ function evaluateTransactionOutcome(receipt, txHash) {
13192
+ if (receipt.status === 'success' && receipt.blockNumber) {
13193
+ return {
13194
+ state: 'success'
13195
+ };
12941
13196
  }
12942
- return true;
12943
- };
13197
+ return {
13198
+ state: 'error',
13199
+ errorMessage: receipt.status === 'reverted' ? `Transaction ${txHash} was reverted` : 'Transaction was not confirmed on-chain'
13200
+ };
13201
+ }
13202
+ function hasPendingState(analysis, result) {
13203
+ // Check if there's a continuation step that's marked as non-actionable
13204
+ if (analysis.continuationStep === null || analysis.isActionable) {
13205
+ return false;
13206
+ }
13207
+ // Verify that the continuation step actually exists and is in pending state
13208
+ const pendingStep = result.steps.find((step)=>step.name === analysis.continuationStep && step.state === 'pending');
13209
+ return pendingStep !== undefined;
13210
+ }
12944
13211
  /**
12945
- * Requests re-attestation for an expired attestation nonce.
12946
- *
12947
- * This function calls Circle's re-attestation API endpoint to request a fresh
12948
- * attestation for a previously issued nonce. After calling this function,
12949
- * you should poll `fetchAttestation` to retrieve the new attestation.
13212
+ * Check if the step is the last one in the execution flow.
12950
13213
  *
12951
- * @param nonce - The nonce from the original (expired) attestation
12952
- * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
12953
- * @param config - Optional configuration overrides for the request
12954
- * @returns The re-attestation response confirming the request was accepted
12955
- * @throws If the request fails, times out, or returns invalid data
13214
+ * @param step - The step object to check.
13215
+ * @param stepNames - The ordered list of step names in the execution flow.
13216
+ * @returns True if this is the last step in the flow.
12956
13217
  *
12957
13218
  * @example
12958
13219
  * ```typescript
12959
- * // Request re-attestation for an expired nonce
12960
- * const response = await requestReAttestation('0xabc', true)
12961
- * console.log(response.message) // "Re-attestation successfully requested for nonce."
13220
+ * import { isLastStep } from './stepUtils'
12962
13221
  *
12963
- * // After requesting re-attestation, poll for the new attestation
12964
- * const attestation = await fetchAttestation(domainId, txHash, true)
13222
+ * const stepNames = ['approve', 'burn', 'fetchAttestation', 'mint']
13223
+ * isLastStep({ name: 'mint' }, stepNames) // true
13224
+ * isLastStep({ name: 'burn' }, stepNames) // false
12965
13225
  * ```
12966
- */ const requestReAttestation = async (nonce, isTestnet, config = {})=>{
12967
- const url = buildReAttestUrl(nonce, isTestnet);
12968
- // Use minimal retries since we're just submitting a request, not polling for state
12969
- const effectiveConfig = mergeAttestationConfig(config, {
12970
- maxRetries: 3
12971
- });
12972
- return await pollApiPost(url, {}, isReAttestationResponse, effectiveConfig);
12973
- };
12974
-
13226
+ */ function isLastStep(step, stepNames) {
13227
+ const stepIndex = stepNames.indexOf(step.name);
13228
+ return stepIndex === -1 || stepIndex >= stepNames.length - 1;
13229
+ }
12975
13230
  /**
12976
- * Type guard that checks if the relayer has confirmed the mint transaction.
13231
+ * Wait for a pending transaction to complete.
12977
13232
  *
12978
- * This function validates that:
12979
- * 1. The response has valid AttestationResponse structure
12980
- * 2. At least one message has forwardState === 'CONFIRMED' (or 'COMPLETE') and a valid forwardTxHash
13233
+ * Poll the adapter until the transaction is confirmed on-chain and return
13234
+ * the updated step with success or error state based on the receipt.
12981
13235
  *
12982
- * If forwardState is 'FAILED', throws a non-retryable KitError.
12983
- * If forwardState is 'PENDING' or not present, throws a RETRYABLE KitError to continue polling.
13236
+ * @param pendingStep - The full step object containing the transaction hash.
13237
+ * @param adapter - The adapter to use for waiting.
13238
+ * @param chain - The chain where the transaction was submitted.
13239
+ * @returns The updated step object with success or error state.
12984
13240
  *
12985
- * @param obj - The value to check, typically a parsed JSON response
12986
- * @returns True if the relayer has confirmed the mint
12987
- * @throws {KitError} With FATAL recoverability if structure is invalid
12988
- * @throws {KitError} With RESUMABLE recoverability if forwardState is 'FAILED'
12989
- * @throws {KitError} With RETRYABLE recoverability if still pending
12990
- * @internal
12991
- */ const isRelayerMintConfirmed = (obj)=>{
12992
- // First check if the structure is valid
12993
- if (!hasValidAttestationStructure(obj)) {
12994
- throw new KitError({
12995
- ...InputError.VALIDATION_FAILED,
12996
- recoverability: 'FATAL',
12997
- message: 'Invalid attestation response structure from IRIS API.'
12998
- });
12999
- }
13000
- // Find the first message (typically there's only one)
13001
- const message = obj.messages[0];
13002
- if (!message) {
13241
+ * @throws KitError when the pending step has no transaction hash.
13242
+ *
13243
+ * @example
13244
+ * ```typescript
13245
+ * import { waitForPendingTransaction } from './bridgeStepUtils'
13246
+ *
13247
+ * const pendingStep = { name: 'burn', state: 'pending', txHash: '0x123...' }
13248
+ * const updatedStep = await waitForPendingTransaction(pendingStep, adapter, chain)
13249
+ * // updatedStep.state is now 'success' or 'error'
13250
+ * ```
13251
+ */ async function waitForPendingTransaction(pendingStep, adapter, chain) {
13252
+ if (!pendingStep.txHash) {
13003
13253
  throw new KitError({
13004
13254
  ...InputError.VALIDATION_FAILED,
13005
13255
  recoverability: 'FATAL',
13006
- message: 'No attestation messages found in IRIS API response.'
13007
- });
13008
- }
13009
- // Check for FAILED state - this is a permanent failure
13010
- if (message.forwardState === 'FAILED') {
13011
- throw new KitError({
13012
- ...NetworkError.RELAYER_FORWARD_FAILED,
13013
- recoverability: 'RESUMABLE',
13014
- message: 'Circle relayer failed to forward the mint transaction. The mint may still have succeeded if another party submitted it. Check the recipient wallet balance before retrying. If the mint did not occur, you can manually submit it using the attestation data in the error cause.',
13015
- cause: {
13016
- trace: {
13017
- eventNonce: message.eventNonce,
13018
- attestation: message.attestation,
13019
- message: message.message
13020
- }
13021
- }
13256
+ message: `Cannot wait for pending ${pendingStep.name}: no transaction hash available`
13022
13257
  });
13023
13258
  }
13024
- // Check if mint is confirmed (or complete) with a valid transaction hash
13025
- // We accept both CONFIRMED and COMPLETE since COMPLETE implies CONFIRMED
13026
- if ((message.forwardState === 'CONFIRMED' || message.forwardState === 'COMPLETE') && typeof message.forwardTxHash === 'string' && message.forwardTxHash.trim().length > 0) {
13027
- return true;
13028
- }
13029
- // Still pending or not yet processed - throw RETRYABLE error to continue polling
13030
- throw new KitError({
13031
- ...NetworkError.RELAYER_PENDING,
13032
- recoverability: 'RETRYABLE',
13033
- message: 'Relayer mint not ready. Waiting for confirmation.'
13259
+ const txHash = pendingStep.txHash;
13260
+ const txReceipt = await retryAsync(async ()=>adapter.waitForTransaction(txHash, undefined, chain), {
13261
+ isRetryable: (err)=>isRetryableError$1(parseBlockchainError(err, {
13262
+ chain: chain.name,
13263
+ txHash
13264
+ }))
13034
13265
  });
13035
- };
13266
+ const outcome = evaluateTransactionOutcome(txReceipt, txHash);
13267
+ return {
13268
+ ...pendingStep,
13269
+ state: outcome.state,
13270
+ data: txReceipt,
13271
+ explorerUrl: buildExplorerUrl(chain, txHash),
13272
+ ...outcome.errorMessage ? {
13273
+ errorMessage: outcome.errorMessage
13274
+ } : {}
13275
+ };
13276
+ }
13036
13277
  /**
13037
- * Polls the attestation API until the relayer's mint transaction is confirmed.
13278
+ * Wait for a pending step to complete.
13038
13279
  *
13039
- * This function is used when `useForwarder` is enabled. Instead of the user
13040
- * submitting the mint transaction, Circle's Orbit relayer handles it automatically.
13041
- * This function polls until the relayer has submitted and confirmed the mint transaction.
13280
+ * For transaction steps: waits for the transaction to be confirmed.
13281
+ * For attestation: re-executes the attestation fetch.
13042
13282
  *
13043
- * @remarks
13044
- * - Uses a 20-minute timeout by default (600 retries × 2 seconds)
13045
- * - Throws immediately if `forwardState` is 'FAILED'
13046
- * - Waits for `forwardState` to be 'CONFIRMED' or 'COMPLETE' (COMPLETE implies CONFIRMED)
13047
- * - Returns the attestation message with `forwardTxHash` populated
13283
+ * @typeParam TFromAdapterCapabilities - The capabilities of the source adapter.
13284
+ * @typeParam TToAdapterCapabilities - The capabilities of the destination adapter.
13285
+ * @param pendingStep - The full step object (with name, state, txHash, data, etc.) to resolve.
13286
+ * @param adapter - The adapter to use.
13287
+ * @param chain - The chain where the step is executing.
13288
+ * @param context - The retry context.
13289
+ * @param result - The bridge result.
13290
+ * @param provider - The CCTP v2 bridging provider.
13291
+ * @returns The resolved step object with updated state.
13048
13292
  *
13049
- * @param sourceDomainId - The CCTP domain ID of the source chain
13050
- * @param transactionHash - The transaction hash of the burn operation
13051
- * @param isTestnet - Whether this is for a testnet chain (true) or mainnet (false)
13052
- * @param config - Optional configuration overrides for polling behavior
13053
- * @returns The attestation message with confirmed forwardTxHash
13054
- * @throws {KitError} With code 'NETWORK_RELAYER_FORWARD_FAILED' if relayer failed
13055
- * @throws {KitError} If timeout is reached while still pending
13293
+ * @throws KitError when fetching attestation but burn transaction hash is not found.
13056
13294
  *
13057
13295
  * @example
13058
13296
  * ```typescript
13059
- * const attestation = await fetchRelayerMint(0, '0xabc...', false)
13060
- * console.log('Relayer mint tx:', attestation.forwardTxHash)
13297
+ * import { waitForStepToComplete } from './bridgeStepUtils'
13298
+ *
13299
+ * const pendingStep = { name: 'burn', state: 'pending', txHash: '0x123...' }
13300
+ * const updatedStep = await waitForStepToComplete(
13301
+ * pendingStep,
13302
+ * adapter,
13303
+ * chain,
13304
+ * context,
13305
+ * result,
13306
+ * provider,
13307
+ * )
13308
+ * // updatedStep.state is now 'success' or 'error'
13061
13309
  * ```
13062
- */ const fetchRelayerMint = async (sourceDomainId, transactionHash, isTestnet, config = {})=>{
13063
- const url = buildIrisUrl(sourceDomainId, transactionHash, isTestnet);
13064
- const effectiveConfig = mergeAttestationConfig(config);
13065
- let response;
13066
- try {
13067
- response = await pollApiGet(url, isRelayerMintConfirmed, effectiveConfig);
13068
- } catch (error) {
13069
- // Enrich RELAYER_FORWARD_FAILED errors with the burn transaction hash
13070
- if (error instanceof KitError && error.name === 'NETWORK_RELAYER_FORWARD_FAILED') {
13310
+ */ async function waitForStepToComplete(pendingStep, adapter, chain, context, result, provider) {
13311
+ if (pendingStep.name === CCTPv2StepName.fetchAttestation) {
13312
+ // For attestation, re-run the fetch (it has built-in polling)
13313
+ const burnTxHash = getBurnTxHash(result);
13314
+ if (!burnTxHash) {
13071
13315
  throw new KitError({
13072
- ...NetworkError.RELAYER_FORWARD_FAILED,
13073
- recoverability: error.recoverability,
13074
- message: error.message,
13075
- cause: {
13076
- ...error.cause,
13077
- trace: {
13078
- ...error.cause?.trace,
13079
- burnTxHash: transactionHash
13080
- }
13081
- }
13316
+ ...InputError.VALIDATION_FAILED,
13317
+ recoverability: 'FATAL',
13318
+ message: 'Cannot fetch attestation: burn transaction hash not found'
13082
13319
  });
13083
13320
  }
13084
- throw error;
13085
- }
13086
- // Return the first message (which should have forwardTxHash)
13087
- // Note: This check is needed for TypeScript type safety even though
13088
- // isRelayerMintConfirmed validates messages[0] exists. The type guard
13089
- // narrows the type at the call site, but TypeScript can't infer that
13090
- // the array still has elements after pollApiGet returns.
13091
- const message = response.messages[0];
13092
- if (!message) {
13093
- throw new KitError({
13094
- ...InputError.VALIDATION_FAILED,
13095
- recoverability: 'FATAL',
13096
- message: 'No attestation messages found in response after polling.'
13097
- });
13321
+ const sourceAddress = result.source.address;
13322
+ const attestation = await provider.fetchAttestation({
13323
+ chain: result.source.chain,
13324
+ adapter: context.from,
13325
+ address: sourceAddress
13326
+ }, burnTxHash);
13327
+ return {
13328
+ ...pendingStep,
13329
+ state: 'success',
13330
+ data: attestation
13331
+ };
13098
13332
  }
13099
- return message;
13100
- };
13333
+ // For transaction steps, wait for the transaction to complete
13334
+ return waitForPendingTransaction(pendingStep, adapter, chain);
13335
+ }
13101
13336
 
13102
- const assertCCTPv2WalletContextSymbol = Symbol('assertCCTPv2WalletContext');
13103
13337
  /**
13104
- * Asserts that the provided parameters match the CCTPv2 wallet context interface.
13105
- * The validation includes:
13106
- * - Basic wallet context validation (adapter, address, chain)
13107
- * - CCTPv2-specific chain validation (must be an EVM chain)
13338
+ * Multiplier applied to a successful gas estimate before it is submitted.
13108
13339
  *
13109
- * @param params - The parameters to validate
13110
- * @throws {KitError} If validation fails with INPUT_VALIDATION_FAILED code (1098), with details about which properties failed
13340
+ * Estimates are exact, not padded: Sei returns 109_739 for an approve that
13341
+ * consumes 107_717 (1.9% headroom). Chains that price storage in large steps
13342
+ * can exceed the estimate if state changes between estimation and inclusion,
13343
+ * so the estimate is padded before use.
13111
13344
  *
13112
- * @example
13113
- * ```typescript
13114
- * import { assertCCTPv2WalletContext } from '@circle-fin/provider-cctp-v2'
13115
- * import { Ethereum } from '@core/chains'
13345
+ * @remarks
13346
+ * This buffer alone does NOT cover Sei's ~51_500 per-new-slot step at approve
13347
+ * scale (25% of ~110_000 is only ~27_500). For approve, the FLOOR is what
13348
+ * covers a slot that exists at estimation time and is consumed before
13349
+ * inclusion — so do not lower `APPROVE_GAS_LIMIT_EVM` on the reasoning that
13350
+ * the estimate covers it. For burn the buffer does cover a step (25% of
13351
+ * ~300_000 exceeds 51_500).
13352
+ */ const GAS_ESTIMATE_BUFFER_PERCENT = 125n;
13353
+ /**
13354
+ * Resolve the gas limit for an EVM request as `max(estimate * buffer, floor)`.
13116
13355
  *
13117
- * // Prepare wallet context
13118
- * const context = {
13119
- * adapter: {
13120
- * prepare: async () => ({ data: 'prepared transaction' }),
13121
- * waitForTransaction: async () => ({ status: 'confirmed' })
13122
- * },
13123
- * address: '0x1234567890123456789012345678901234567890',
13124
- * chain: {
13125
- * ...Ethereum,
13126
- * usdcAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
13127
- * cctp: {
13128
- * domain: 1,
13129
- * contracts: {
13130
- * v2: {
13131
- * tokenMessenger: '0xTokenMessenger',
13132
- * messageTransmitter: '0xMessageTransmitter'
13133
- * }
13134
- * }
13135
- * }
13136
- * }
13137
- * }
13356
+ * Estimates first so chains whose real cost exceeds the floor are covered by
13357
+ * their own measurement, and falls back to the floor whenever estimation is
13358
+ * unavailable or under-reports. Estimation failure is never fatal here: before
13359
+ * floors existed these requests were submitted with a pinned limit and no
13360
+ * estimate at all, so degrading to the floor is never worse than the previous
13361
+ * behaviour.
13138
13362
  *
13139
- * // This will throw if validation fails
13140
- * assertCCTPv2WalletContext(context)
13363
+ * @param request - The prepared EVM request to size a gas limit for
13364
+ * @param gasFloor - The minimum gas limit to submit, in gas units
13365
+ * @returns The gas limit to submit, in gas units
13366
+ * @throws Never — estimation failures degrade to `gasFloor`
13141
13367
  *
13142
- * // If we get here, context is guaranteed to be valid
13143
- * console.log('CCTPv2 wallet context is valid')
13368
+ * @example
13369
+ * ```typescript
13370
+ * const gasLimit = await resolveGasLimit(request, 150_000)
13144
13371
  * ```
13145
- */ function assertCCTPv2WalletContext(params) {
13146
- // First validate basic wallet context
13147
- validateWithStateTracking(params, walletContextSchema, 'CCTPv2 wallet context', assertCCTPv2WalletContextSymbol);
13148
- // After validation, we know params is WalletContext
13149
- const context = params;
13150
- // Validate USDC support
13151
- if (context.chain.usdcAddress === null) {
13152
- throw createInvalidChainError(context.chain.name, 'Does not have USDC configured');
13153
- }
13154
- // Validate CCTPv2 support
13155
- if (!isCCTPV2Supported(context.chain)) {
13156
- throw createInvalidChainError(context.chain.name, 'Does not support CCTPv2');
13157
- }
13158
- }
13159
-
13160
- const assertCCTPv2BridgeParamsSymbol = Symbol('assertCCTPv2BridgeParams');
13161
- /**
13162
- * Asserts that the provided parameters match the CCTPv2 bridge parameters interface.
13163
- * The validation includes:
13164
- * - Basic parameter structure and types
13165
- * - Amount validation (non-empty numeric string \> 0)
13166
- * - Wallet address format validation (must be valid Ethereum address)
13167
- * - Chain definition validation (must be a valid chain with required properties)
13168
- * - Adapter validation (must implement required methods)
13169
- * - Optional config validation (transfer speed and max fee)
13170
- * - Network compatibility (source and destination chains must both be testnet or both mainnet)
13171
- * - CCTPv2-specific wallet context validations
13372
+ */ const resolveGasLimit = async (request, gasFloor)=>{
13373
+ try {
13374
+ // Deliberately called without a `fallback`: both the viem and ethers
13375
+ // adapters *return* the supplied fallback object when estimation reverts
13376
+ // rather than throwing, which would set the estimate to the floor and then
13377
+ // multiply it by the buffer below. Omitting it routes reverts through the
13378
+ // catch, so a failed estimate degrades to exactly the floor.
13379
+ const estimate = await request.estimate();
13380
+ // The arithmetic stays inside the try on purpose. `EstimatedGas.gas` is
13381
+ // typed `bigint`, but adapters are a public extension point and may be
13382
+ // implemented in plain JS, so a non-bigint `gas` would throw here
13383
+ // ("Cannot mix BigInt and other types"). Guarding it keeps the documented
13384
+ // contract — estimation never aborts a step, it degrades to the floor.
13385
+ const buffered = estimate.gas * GAS_ESTIMATE_BUFFER_PERCENT / 100n;
13386
+ // Convert before comparing: Math.max throws on BigInt operands, and gas
13387
+ // units are far below Number.MAX_SAFE_INTEGER so the narrowing is lossless.
13388
+ return Math.max(Number(buffered), gasFloor);
13389
+ } catch {
13390
+ // Estimation is best-effort; the floor is the known-safe value.
13391
+ return gasFloor;
13392
+ }
13393
+ };
13394
+ /**
13395
+ * Executes a prepared chain request and returns the result as a bridge step.
13172
13396
  *
13173
- * @param params - The parameters to validate
13174
- * @throws {KitError} If validation fails, with details about which properties failed
13397
+ * This function takes a prepared chain request (containing transaction data) and executes
13398
+ * it using the appropriate adapter. It handles the execution details and formats
13399
+ * the result as a standardized bridge step with transaction details and explorer URLs.
13400
+ *
13401
+ * @param params - The execution parameters containing:
13402
+ * - `name`: The name of the step
13403
+ * - `request`: The prepared chain request containing transaction data
13404
+ * - `adapter`: The adapter that will execute the transaction
13405
+ * - `confirmations`: The number of confirmations to wait for (defaults to 1)
13406
+ * - `timeout`: The timeout for the request in milliseconds
13407
+ * - `gasFloor`: Optional minimum gas limit (number); the request is submitted
13408
+ * with `max(estimate * 1.25, gasFloor)`. Ignored for non-EVM requests
13409
+ * @returns The bridge step with the transaction details and explorer URL
13410
+ * @throws If the transaction execution fails
13175
13411
  *
13176
13412
  * @example
13177
13413
  * ```typescript
13178
- * import { assertCCTPv2BridgeParams } from '@circle-fin/provider-cctp-v2'
13179
- * import { Ethereum, Base } from '@core/chains'
13180
- *
13181
- * // Prepare transfer parameters
13182
- * const params = {
13183
- * amount: '100.50',
13184
- * source: {
13185
- * adapter: sourceAdapter,
13186
- * address: '0xSourceAddress',
13187
- * chain: {
13188
- * ...Ethereum,
13189
- * cctp: {
13190
- * domain: 1,
13191
- * contracts: {
13192
- * v2: {
13193
- * tokenMessenger: '0xTokenMessenger',
13194
- * messageTransmitter: '0xMessageTransmitter'
13195
- * }
13196
- * }
13197
- * }
13198
- * }
13199
- * },
13200
- * destination: {
13201
- * adapter: destAdapter,
13202
- * address: '0xDestAddress',
13203
- * chain: {
13204
- * ...Base,
13205
- * cctp: {
13206
- * domain: 2,
13207
- * contracts: {
13208
- * v2: {
13209
- * tokenMessenger: '0xTokenMessenger',
13210
- * messageTransmitter: '0xMessageTransmitter'
13211
- * }
13212
- * }
13213
- * }
13214
- * }
13215
- * },
13216
- * token: 'USDC',
13217
- * config: {
13218
- * transferSpeed: 'FAST',
13219
- * maxFee: '1000000'
13220
- * }
13221
- * }
13222
- *
13223
- * // This will throw if validation fails
13224
- * assertCCTPv2BridgeParams(params)
13225
- *
13226
- * // If we get here, params is guaranteed to be valid
13227
- * console.log('CCTPv2 transfer parameters are valid')
13414
+ * const step = await executePreparedChainRequest({
13415
+ * name: 'approve',
13416
+ * request: preparedRequest,
13417
+ * adapter: adapter,
13418
+ * confirmations: 2,
13419
+ * timeout: 30000
13420
+ * })
13421
+ * console.log('Transaction hash:', step.txHash)
13228
13422
  * ```
13229
- */ function assertCCTPv2BridgeParams(params) {
13230
- // First validate basic bridge params
13231
- validateWithStateTracking(params, bridgeParamsSchema, 'CCTPv2 bridge parameters', assertCCTPv2BridgeParamsSymbol);
13232
- // After validation, we know params is CCTPV2BridgeParams
13233
- const bridgeParams = params;
13234
- // Enforce that source and destination chains are either testnet or mainnet
13235
- if (bridgeParams.source.chain.isTestnet !== bridgeParams.destination.chain.isTestnet) {
13236
- throw createNetworkMismatchError(bridgeParams.source.chain, bridgeParams.destination.chain);
13237
- }
13238
- assertCCTPV2Support(bridgeParams.source.chain, bridgeParams.destination.chain);
13239
- // Validate that the destination chain supports forwarding when forwarder is enabled
13240
- assertForwarderRouteSupport(bridgeParams.source.chain, bridgeParams.destination.chain, bridgeParams.destination.useForwarder);
13241
- /**
13242
- * Enforce that if fee is defined then feeRecipient must be defined.
13243
- * We do not do this in the validation function itself because we want to allow
13244
- * optional properties when calling `provider.bridge()` due to the custom fee
13245
- * configuration being possible at the kit level as well.
13246
- */ if (bridgeParams.config?.customFee?.value !== undefined && bridgeParams.config?.customFee?.recipientAddress === undefined) {
13247
- throw createValidationFailedError$1('recipientAddress', bridgeParams.config.customFee.value, 'Custom fee is defined but fee recipient is not. Please provide a fee recipient.');
13248
- }
13249
- // Check if this is a forwarder-only destination (no adapter, requires useForwarder: true)
13250
- const isForwarderOnly = bridgeParams.destination.useForwarder === true && !('adapter' in bridgeParams.destination && bridgeParams.destination.adapter);
13251
- // Forwarder-only destinations require recipientAddress
13252
- if (isForwarderOnly) {
13253
- if (!bridgeParams.destination.recipientAddress?.trim()) {
13254
- throw createValidationFailedError$1('recipientAddress', bridgeParams.destination.recipientAddress, 'recipientAddress is required when using forwarder without a destination adapter.');
13423
+ */ async function executePreparedChainRequest({ name, request, adapter, chain, confirmations = 1, timeout, gasFloor }) {
13424
+ const step = {
13425
+ name,
13426
+ state: 'pending'
13427
+ };
13428
+ try {
13429
+ /**
13430
+ * No-op requests are not executed.
13431
+ * We return a noop step instead.
13432
+ */ if (request.type === 'noop') {
13433
+ step.state = 'noop';
13434
+ return step;
13435
+ }
13436
+ const txHash = request.type === 'evm' && gasFloor !== undefined ? await request.execute({
13437
+ gasLimit: await resolveGasLimit(request, gasFloor)
13438
+ }) : await request.execute();
13439
+ step.txHash = txHash;
13440
+ const retryOptions = {
13441
+ isRetryable: (err)=>isRetryableError$1(parseBlockchainError(err, {
13442
+ chain: chain.name,
13443
+ txHash
13444
+ }))
13445
+ };
13446
+ if (timeout !== undefined) {
13447
+ retryOptions.deadlineMs = Date.now() + timeout;
13448
+ }
13449
+ const transaction = await retryAsync(async ()=>adapter.waitForTransaction(txHash, {
13450
+ confirmations,
13451
+ timeout
13452
+ }, chain), retryOptions);
13453
+ const outcome = evaluateTransactionOutcome(transaction, txHash);
13454
+ step.state = outcome.state;
13455
+ step.data = transaction;
13456
+ // Generate explorer URL for the step
13457
+ step.explorerUrl = buildExplorerUrl(chain, txHash);
13458
+ if (outcome.errorMessage) {
13459
+ step.errorMessage = outcome.errorMessage;
13460
+ // Transaction was mined but reverted on-chain.
13461
+ step.errorCategory = 'chain_revert';
13462
+ }
13463
+ } catch (err) {
13464
+ step.state = 'error';
13465
+ step.error = err;
13466
+ // Sequential path does not yet attempt fine-grained classification of
13467
+ // pre-submission errors (user_rejected, capability errors, etc.). Mark
13468
+ // as `unknown` so consumers can at least detect the category is
13469
+ // populated uniformly across batched and sequential flows.
13470
+ step.errorCategory = 'unknown';
13471
+ // Optionally parse for common blockchain error formats
13472
+ if (err instanceof Error) {
13473
+ step.errorMessage = err.message;
13474
+ } else if (typeof err === 'object' && err != null && 'message' in err) {
13475
+ step.errorMessage = String(err.message);
13476
+ } else {
13477
+ step.errorMessage = `Unknown error occurred during ${name} step.`;
13255
13478
  }
13256
13479
  }
13257
- // Validate CCTP v2 specific requirements for source wallet
13258
- assertCCTPv2WalletContext(bridgeParams.source);
13259
- // Validate that source adapter supports the chain (defense-in-depth)
13260
- bridgeParams.source.adapter.validateChainSupport(bridgeParams.source.chain);
13261
- // Only validate destination wallet context and adapter if not forwarder-only
13262
- if (!isForwarderOnly) {
13263
- assertCCTPv2WalletContext(bridgeParams.destination);
13264
- // Validate that destination adapter supports the chain (defense-in-depth)
13265
- bridgeParams.destination.adapter.validateChainSupport(bridgeParams.destination.chain);
13266
- }
13480
+ return step;
13267
13481
  }
13482
+
13268
13483
  /**
13269
- * Validate CCTP v2 support on both chains
13270
- */ /**
13271
- * Throws a KitError if the given chain does not support CCTP v2.
13272
- *
13273
- * @param chain - The chain to check for CCTP v2 support
13274
- * @param otherChain - The other chain in the route (for error context)
13275
- * @param isSource - Whether this is the source chain (for error context)
13276
- */ function assertCCTPV2Support(source, destination) {
13277
- if (!isCCTPV2Supported(source) || !isCCTPV2Supported(destination)) {
13278
- throw createUnsupportedRouteError(source.name, destination.name);
13484
+ * Default configuration values for the attestation fetcher.
13485
+ * @internal
13486
+ */ const DEFAULT_CONFIG = {
13487
+ timeout: 2_000,
13488
+ maxRetries: 30 * 20,
13489
+ retryDelay: 2_000,
13490
+ headers: {
13491
+ 'Content-Type': 'application/json'
13279
13492
  }
13280
- }
13493
+ };
13281
13494
  /**
13282
- * Validates that the forwarder (relaying) feature is compatible with the route.
13283
- *
13284
- * Checks the destination chain's `cctp.forwarderSupported.destination` property
13285
- * to determine whether the chain supports receiving forwarded transfers.
13495
+ * Merges caller-provided polling overrides on top of {@link DEFAULT_CONFIG}.
13286
13496
  *
13287
- * @param source - The source chain definition
13288
- * @param destination - The destination chain definition
13289
- * @param useForwarder - Whether the forwarder is enabled on the destination
13290
- * @throws {KitError} If the forwarder is enabled and the destination chain does not support forwarding
13291
- */ function assertForwarderRouteSupport(source, destination, useForwarder) {
13292
- if (useForwarder === true && !destination.cctp?.forwarderSupported.destination) {
13293
- throw new KitError({
13294
- ...InputError.UNSUPPORTED_ROUTE,
13295
- recoverability: 'FATAL',
13296
- message: `Route from ${source.name} to ${destination.name} with forwarder is not supported (destination chain does not support forwarding).`,
13297
- cause: {
13298
- trace: {
13299
- source: source.name,
13300
- destination: destination.name
13301
- }
13302
- }
13303
- });
13304
- }
13305
- }
13306
-
13307
- /**
13308
- * Checks if a decoded attestation field matches the corresponding transfer parameter.
13309
- * If the values do not match, appends a descriptive error message to the errors array.
13497
+ * Headers are merged independently so caller-supplied headers augment the
13498
+ * defaults (such as `Content-Type`) rather than replacing them wholesale.
13310
13499
  *
13311
- * @param field - The name of the field being compared (for error reporting)
13312
- * @param decoded - The value decoded from the attestation message
13313
- * @param param - The expected value from the transfer parameters
13314
- * @param errors - The array to which error messages will be appended if a mismatch is found
13315
- */ function checkFieldMismatch(field, decoded, param, errors) {
13316
- if (decoded !== param) {
13317
- errors.push(`${field} mismatch: decoded=${String(decoded)}, params=${String(param)}`);
13318
- }
13319
- }
13500
+ * @param config - Caller-provided polling configuration overrides
13501
+ * @param internalDefaults - Internal defaults applied before `config` (for example a
13502
+ * reduced `maxRetries` for one-shot requests); `config` still wins on conflict
13503
+ * @returns The effective polling configuration
13504
+ * @internal
13505
+ */ const mergeAttestationConfig = (config, internalDefaults = {})=>({
13506
+ ...DEFAULT_CONFIG,
13507
+ ...internalDefaults,
13508
+ ...config,
13509
+ headers: {
13510
+ ...DEFAULT_CONFIG.headers,
13511
+ ...internalDefaults.headers,
13512
+ ...config.headers
13513
+ }
13514
+ });
13320
13515
  /**
13321
- * Asserts that the decoded message from attestation matches the provided transfer params.
13322
- * Throws KitError if any field mismatches, with clear error messages.
13516
+ * Type guard that verifies if an unknown value matches the AttestationMessage shape
13517
+ * and has all required properties.
13323
13518
  *
13324
- * @param attestation - The attestation message containing the decoded message
13325
- * @param params - The transfer parameters to validate against
13326
- * @throws {@link KitError} If any field mismatches
13327
- */ async function assertCCTPv2AttestationParams(attestation, params) {
13328
- const errors = [];
13329
- const message = attestation.decodedMessage;
13330
- const messageBody = message.decodedMessageBody;
13331
- // Use recipientAddress if provided, otherwise use destination.address
13332
- const destinationAddressForMint = params.destination.recipientAddress ?? params.destination.address;
13333
- const mintRecipient = await getMintRecipientAccount(params.destination.chain.type, destinationAddressForMint, params.destination.chain.usdcAddress);
13334
- let sender;
13335
- if (hasCustomContractSupport(params.source.chain, 'bridge')) {
13336
- if (params.source.chain.type === 'solana') {
13337
- // Solana: User → Bridge contract → CCTP (user remains sender)
13338
- sender = params.source.address;
13339
- } else {
13340
- // Other chains (like EVM): Bridge contract CCTP (bridge contract becomes sender)
13341
- sender = params.source.chain.kitContracts?.bridge;
13342
- }
13343
- } else {
13344
- sender = params.source.address;
13345
- }
13346
- checkFieldMismatch('sourceDomain', message.sourceDomain, params.source.chain.cctp.domain.toString(), errors);
13347
- checkFieldMismatch('destinationDomain', message.destinationDomain, params.destination.chain.cctp.domain.toString(), errors);
13348
- checkFieldMismatch('minFinalityThreshold', message.minFinalityThreshold, CCTPv2MinFinalityThreshold[params.config.transferSpeed ?? 'FAST'].toString(), errors);
13349
- checkFieldMismatch('sender', params.source.chain.type === 'evm' ? messageBody.messageSender.toLowerCase() : messageBody.messageSender, params.source.chain.type === 'evm' ? sender?.toLowerCase() : sender, errors);
13350
- checkFieldMismatch('recipient', params.destination.chain.type === 'evm' ? messageBody.mintRecipient.toLowerCase() : messageBody.mintRecipient, params.destination.chain.type === 'evm' ? mintRecipient.toLowerCase() : mintRecipient, errors);
13351
- checkFieldMismatch('amount', messageBody.amount, params.amount.toString(), errors);
13352
- checkFieldMismatch('burnToken', messageBody.burnToken.toLowerCase(), params.source.chain.usdcAddress.toLowerCase(), errors);
13353
- if (errors.length > 0) {
13354
- const errorMessage = 'Attestation validation failed: received attestation does not match expected transfer parameters';
13355
- const firstError = errors[0] ?? '';
13356
- throw new KitError({
13357
- ...InputError.VALIDATION_FAILED,
13358
- recoverability: 'FATAL',
13359
- message: `${errorMessage}: ${firstError}`,
13360
- cause: {
13361
- trace: {
13362
- validationErrors: errors
13363
- }
13364
- }
13365
- });
13519
+ * @param obj - The value to check, typically an element from the messages array
13520
+ * @returns True if the object matches the AttestationMessage shape, false otherwise
13521
+ * @internal
13522
+ */ const isValidAttestationMessage = (obj)=>{
13523
+ return typeof obj === 'object' && obj !== null && 'message' in obj && 'eventNonce' in obj && 'attestation' in obj && 'decodedMessage' in obj && 'cctpVersion' in obj && 'status' in obj && typeof obj.status === 'string';
13524
+ };
13525
+ /**
13526
+ * Type guard that verifies if an attestation message is complete.
13527
+ *
13528
+ * @param message - The attestation message to check
13529
+ * @returns True if the message status is 'complete', false otherwise
13530
+ * @internal
13531
+ */ const isCompleteAttestation = (message)=>{
13532
+ return message.status === 'complete';
13533
+ };
13534
+ /**
13535
+ * Type guard that verifies if an unknown value has the correct structure
13536
+ * for an AttestationResponse, regardless of attestation completion status.
13537
+ *
13538
+ * @param obj - The value to check, typically a parsed JSON response
13539
+ * @returns True if the object matches the AttestationResponse shape
13540
+ * @internal
13541
+ */ const hasValidAttestationStructure = (obj)=>{
13542
+ if (typeof obj !== 'object' || obj === null || !('messages' in obj) || !Array.isArray(obj.messages)) {
13543
+ return false;
13366
13544
  }
13367
- }
13368
-
13545
+ const messages = obj.messages;
13546
+ // Validate all messages have the correct shape
13547
+ return messages.every(isValidAttestationMessage);
13548
+ };
13369
13549
  /**
13370
- * Assert that `params` is a well-formed {@link BurnWithFeesParams} object.
13550
+ * Type guard that verifies if an unknown value matches the AttestationResponse shape
13551
+ * and contains a complete attestation.
13371
13552
  *
13372
- * Validates the full public-boundary input before any field destructuring,
13373
- * `BigInt()` coercion, or adapter preparation runs, so malformed JS-caller
13374
- * inputs always produce typed `KitError` validation failures.
13553
+ * This function performs runtime validation to ensure that the provided value
13554
+ * conforms to the expected structure of an AttestationResponse and has at least
13555
+ * one complete attestation. It checks that:
13556
+ * 1. The value has valid AttestationResponse structure
13557
+ * 2. At least one message has status 'complete'
13375
13558
  *
13376
- * Checks performed (in order):
13377
- * - `params` must be a non-null plain object
13378
- * - `source` valid CCTP v2 wallet context (via `assertCCTPv2WalletContext`)
13379
- * - `destinationChain` present and supports CCTP v2
13380
- * - source and destination chains must both be testnet or both mainnet
13381
- * - source and destination chains must differ
13382
- * - `executor` — non-empty string
13383
- * - `amount` — bigint or non-empty string coercible to bigint
13384
- * - `feeTotalAmount` — bigint or non-empty string coercible to bigint
13385
- * - `feeToken` — valid EVM address (`0x` + 40 hex chars)
13386
- * - `claim.signedQuote` — valid `0x`-prefixed hex string
13387
- * - `claim.refundAddress` — valid EVM address
13388
- * - `hookData` — valid `0x`-prefixed hex string when present
13559
+ * @remarks
13560
+ * This type guard is used internally by the attestation fetcher to validate
13561
+ * responses from the IRIS API before processing them. It provides runtime
13562
+ * type safety for data coming from the network and ensures we have a complete
13563
+ * attestation before proceeding.
13389
13564
  *
13390
- * @param params - The value to validate.
13391
- * @throws {KitError} If any field is missing or invalid.
13565
+ * If the response has valid structure but no complete attestation yet,
13566
+ * it throws a retryable error. If the response structure is invalid,
13567
+ * it throws a non-retryable validation error.
13568
+ *
13569
+ * @param obj - The value to check, typically a parsed JSON response
13570
+ * @returns True if the object matches the AttestationResponse shape and has a complete attestation
13571
+ * @throws {Error} With "Invalid attestation response structure" if structure is invalid (non-retryable)
13572
+ * @throws {Error} With "Attestation not ready" if no complete attestation yet (retryable)
13392
13573
  *
13393
13574
  * @example
13394
13575
  * ```typescript
13395
- * assertBurnWithFeesParams(params)
13396
- * // params is now typed as BurnWithFeesParams and safe to use
13397
- * const { source, destinationChain, amount } = params
13576
+ * const response = await fetch('https://iris-api.circle.com/...')
13577
+ * const data = await response.json()
13578
+ *
13579
+ * if (isAttestationResponse(data)) {
13580
+ * // TypeScript now knows data is AttestationResponse with at least one complete attestation
13581
+ * const completeMessage = data.messages.find(msg => msg.status === 'complete')
13582
+ * console.log('Found complete attestation:', completeMessage.attestation)
13583
+ * }
13398
13584
  * ```
13399
- */ function assertBurnWithFeesParams(params) {
13400
- if (params === null || typeof params !== 'object' || Array.isArray(params)) {
13401
- throw createValidationFailedError$1('params', params, 'Must be a non-null plain object');
13402
- }
13403
- const p = params;
13404
- // Source wallet context
13405
- assertCCTPv2WalletContext(p['source']);
13406
- const source = p['source'];
13407
- // destinationChain
13408
- const destinationChain = p['destinationChain'];
13409
- if (destinationChain === null || destinationChain === undefined || typeof destinationChain !== 'object') {
13410
- throw createValidationFailedError$1('destinationChain', destinationChain, 'Must be a chain definition object');
13411
- }
13412
- if (!isCCTPV2Supported(destinationChain)) {
13413
- throw createValidationFailedError$1('destinationChain', destinationChain, 'destinationChain must support CCTP v2');
13414
- }
13415
- const dest = destinationChain;
13416
- // Testnet / mainnet mismatch
13417
- if (source.chain.isTestnet !== dest.isTestnet) {
13418
- throw createNetworkMismatchError(source.chain, dest);
13419
- }
13420
- // Same-chain guard
13421
- if (source.chain.name === dest.name) {
13422
- throw createUnsupportedRouteError(source.chain.name, dest.name);
13423
- }
13424
- // executor
13425
- const executor = p['executor'];
13426
- if (typeof executor !== 'string' || executor === '') {
13427
- throw createValidationFailedError$1('executor', executor, 'A GenericExecutor address is required (used for both mintRecipient and destinationCaller)');
13428
- }
13429
- // amount
13430
- const rawAmount = p['amount'];
13431
- if (typeof rawAmount !== 'bigint' && typeof rawAmount !== 'string' || rawAmount === '') {
13432
- throw createValidationFailedError$1('amount', rawAmount, 'Must be a bigint or a numeric string');
13433
- }
13434
- try {
13435
- BigInt(rawAmount);
13436
- } catch {
13437
- throw createValidationFailedError$1('amount', rawAmount, 'Must be a valid integer value coercible to bigint');
13438
- }
13439
- // feeTotalAmount
13440
- const rawFee = p['feeTotalAmount'];
13441
- if (typeof rawFee !== 'bigint' && typeof rawFee !== 'string' || rawFee === '') {
13442
- throw createValidationFailedError$1('feeTotalAmount', rawFee, 'Must be a bigint or a numeric string');
13443
- }
13444
- try {
13445
- BigInt(rawFee);
13446
- } catch {
13447
- throw createValidationFailedError$1('feeTotalAmount', rawFee, 'Must be a valid integer value coercible to bigint');
13448
- }
13449
- // feeToken
13450
- if (!evmAddressSchema.safeParse(p['feeToken']).success) {
13451
- throw createValidationFailedError$1('feeToken', p['feeToken'], 'Must be a valid EVM address (use the zero address for a native fee)');
13452
- }
13453
- // claim
13454
- const rawClaim = p['claim'];
13455
- if (rawClaim === null || typeof rawClaim !== 'object' || Array.isArray(rawClaim)) {
13456
- throw createValidationFailedError$1('claim', rawClaim, 'Must be an object with signedQuote and refundAddress');
13457
- }
13458
- const claim = rawClaim;
13459
- if (!hexStringSchema.safeParse(claim['signedQuote']).success) {
13460
- throw createValidationFailedError$1('claim.signedQuote', claim['signedQuote'], 'Must be a valid hex string starting with 0x');
13461
- }
13462
- if (!evmAddressSchema.safeParse(claim['refundAddress']).success) {
13463
- throw createValidationFailedError$1('claim.refundAddress', claim['refundAddress'], 'Must be a valid EVM address');
13585
+ */ const isAttestationResponse = (obj)=>{
13586
+ // First check if the structure is valid
13587
+ if (!hasValidAttestationStructure(obj)) {
13588
+ // If structure is invalid, this is a permanent failure - don't retry
13589
+ throw new Error('Invalid attestation response structure');
13464
13590
  }
13465
- // hookData (optional)
13466
- const hookData = p['hookData'];
13467
- if (hookData !== undefined && hookData !== '' && !hexStringSchema.safeParse(hookData).success) {
13468
- throw createValidationFailedError$1('hookData', hookData, 'Must be a valid hex string starting with 0x');
13591
+ // Then check if at least one message is complete
13592
+ if (!obj.messages.some(isCompleteAttestation)) {
13593
+ // If no complete message, this is a temporary state - allow retry
13594
+ throw new Error('Attestation not ready');
13469
13595
  }
13470
- }
13471
-
13596
+ return true;
13597
+ };
13472
13598
  /**
13473
- * CCTP bridge step names that can occur in the bridging flow.
13599
+ * Builds the IRIS API URL for fetching attestation data from Circle's CCTP service.
13474
13600
  *
13475
- * This object provides type safety for step names and represents all possible
13476
- * steps that can be executed during a CCTP bridge operation. Using const assertions
13477
- * makes this tree-shakable and follows modern TypeScript best practices.
13478
- */ const CCTPv2StepName = {
13479
- approve: 'approve',
13480
- burn: 'burn',
13481
- fetchAttestation: 'fetchAttestation',
13482
- mint: 'mint',
13483
- reAttest: 'reAttest'
13601
+ * Constructs a properly formatted URL for the IRIS API v2 endpoint that provides
13602
+ * attestation messages for cross-chain transfers. The URL includes both the source
13603
+ * domain identifier and the transaction hash as query parameters. The base URL
13604
+ * is selected based on whether the operation is for testnet or mainnet.
13605
+ *
13606
+ * @param sourceDomainId - The CCTP domain ID of the source chain (numeric or string)
13607
+ * @param transactionHash - The transaction hash of the burn operation to fetch attestation for
13608
+ * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
13609
+ * @returns A fully qualified URL string for the IRIS API endpoint
13610
+ *
13611
+ * @example
13612
+ * ```typescript
13613
+ * // Mainnet URL
13614
+ * const mainnetUrl = buildIrisUrl(1, '0xabc...', false)
13615
+ * // => 'https://iris-api.circle.com/v2/messages/1?transactionHash=0xabc...'
13616
+ *
13617
+ * // Testnet URL
13618
+ * const testnetUrl = buildIrisUrl(1, '0xdef...', true)
13619
+ * // => 'https://iris-api-sandbox.circle.com/v2/messages/1?transactionHash=0xdef...'
13620
+ * ```
13621
+ */ const buildIrisUrl = (sourceDomainId, transactionHash, isTestnet)=>{
13622
+ const baseUrl = isTestnet ? IRIS_API_SANDBOX_BASE_URL : IRIS_API_BASE_URL;
13623
+ const url = new URL(`${baseUrl}/v2/messages/${String(sourceDomainId)}`);
13624
+ url.searchParams.set('transactionHash', transactionHash);
13625
+ return url.toString();
13484
13626
  };
13485
13627
  /**
13486
- * Conditional step transition rules for CCTP bridge flow.
13628
+ * Fetches attestation data from the IRIS API with retry and timeout handling.
13487
13629
  *
13488
- * Rules are evaluated in order - the first matching condition determines the next step.
13489
- * This approach supports flexible flow logic and makes it easy to extend with new patterns.
13490
- */ const STEP_TRANSITION_RULES = {
13491
- // Starting state - no steps executed yet
13492
- '': [
13493
- {
13494
- condition: ()=>true,
13495
- nextStep: CCTPv2StepName.approve,
13496
- reason: 'Start with approval step',
13497
- isActionable: true
13498
- }
13499
- ],
13500
- // After Approve step
13501
- [CCTPv2StepName.approve]: [
13502
- {
13503
- condition: (ctx)=>ctx.lastStep?.state === 'success',
13504
- nextStep: CCTPv2StepName.burn,
13505
- reason: 'Approval successful, proceed to burn',
13506
- isActionable: true
13507
- },
13508
- {
13509
- condition: (ctx)=>ctx.lastStep?.state === 'error',
13510
- nextStep: CCTPv2StepName.approve,
13511
- reason: 'Retry failed approval',
13512
- isActionable: true
13513
- },
13514
- {
13515
- condition: (ctx)=>ctx.lastStep?.state === 'noop',
13516
- nextStep: CCTPv2StepName.burn,
13517
- reason: 'No approval needed, proceed to burn',
13518
- isActionable: true
13519
- },
13520
- {
13521
- condition: (ctx)=>ctx.lastStep?.state === 'pending',
13522
- nextStep: CCTPv2StepName.approve,
13523
- reason: 'Continue pending approval',
13524
- isActionable: false
13525
- }
13526
- ],
13527
- // After Burn step
13528
- [CCTPv2StepName.burn]: [
13529
- {
13530
- condition: (ctx)=>ctx.lastStep?.state === 'success',
13531
- nextStep: CCTPv2StepName.fetchAttestation,
13532
- reason: 'Burn successful, fetch attestation',
13533
- isActionable: true
13534
- },
13535
- {
13536
- condition: (ctx)=>ctx.lastStep?.state === 'error',
13537
- nextStep: CCTPv2StepName.burn,
13538
- reason: 'Retry failed burn',
13539
- isActionable: true
13540
- },
13541
- {
13542
- condition: (ctx)=>ctx.lastStep?.state === 'pending',
13543
- nextStep: CCTPv2StepName.burn,
13544
- reason: 'Continue pending burn',
13545
- isActionable: false
13546
- }
13547
- ],
13548
- // After FetchAttestation step
13549
- [CCTPv2StepName.fetchAttestation]: [
13550
- {
13551
- condition: (ctx)=>ctx.lastStep?.state === 'success',
13552
- nextStep: CCTPv2StepName.mint,
13553
- reason: 'Attestation fetched, proceed to mint',
13554
- isActionable: true
13555
- },
13556
- {
13557
- condition: (ctx)=>ctx.lastStep?.state === 'error',
13558
- nextStep: CCTPv2StepName.fetchAttestation,
13559
- reason: 'Retry fetching attestation',
13560
- isActionable: true
13561
- },
13562
- {
13563
- condition: (ctx)=>ctx.lastStep?.state === 'pending',
13564
- nextStep: CCTPv2StepName.fetchAttestation,
13565
- reason: 'Continue pending attestation fetch',
13566
- isActionable: false
13567
- }
13568
- ],
13569
- // After Mint step
13570
- [CCTPv2StepName.mint]: [
13571
- {
13572
- condition: (ctx)=>ctx.lastStep?.state === 'success',
13573
- nextStep: null,
13574
- reason: 'Bridge completed successfully',
13575
- isActionable: false
13576
- },
13577
- {
13578
- condition: (ctx)=>ctx.lastStep?.state === 'error',
13579
- nextStep: CCTPv2StepName.mint,
13580
- reason: 'Retry failed mint',
13581
- isActionable: true
13582
- },
13583
- {
13584
- condition: (ctx)=>ctx.lastStep?.state === 'pending',
13585
- nextStep: CCTPv2StepName.mint,
13586
- reason: 'Continue pending mint',
13587
- isActionable: false
13588
- }
13589
- ],
13590
- // After ReAttest step
13591
- [CCTPv2StepName.reAttest]: [
13592
- {
13593
- condition: (ctx)=>ctx.lastStep?.state === 'success',
13594
- nextStep: CCTPv2StepName.mint,
13595
- reason: 'Re-attestation successful, proceed to mint',
13596
- isActionable: true
13597
- },
13598
- {
13599
- condition: (ctx)=>ctx.lastStep?.state === 'error',
13600
- nextStep: CCTPv2StepName.mint,
13601
- reason: 'Re-attestation failed, retry mint to re-initiate recovery',
13602
- isActionable: true
13603
- },
13604
- {
13605
- condition: (ctx)=>ctx.lastStep?.state === 'pending',
13606
- nextStep: CCTPv2StepName.mint,
13607
- reason: 'Re-attestation pending, retry mint to re-initiate recovery',
13608
- isActionable: true
13609
- }
13610
- ]
13630
+ * Polls the IRIS API until a complete attestation is available. The default
13631
+ * window is sized for slow source chains where finality may take many
13632
+ * confirmations.
13633
+ *
13634
+ * Defaults (see `DEFAULT_CONFIG`):
13635
+ * - Per-attempt timeout: 2 000 ms (each HTTP request aborts after 2 s)
13636
+ * - Retry delay: 2 000 ms between attempts
13637
+ * - Max retries: 600 (30 × 20)
13638
+ * - Total worst-case polling window: 600 × (2 000 ms + 2 000 ms) ≈ 40 minutes
13639
+ *
13640
+ * @param sourceDomainId - The CCTP domain ID.
13641
+ * @param transactionHash - The transaction hash to fetch attestation for.
13642
+ * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
13643
+ * @param config - Optional configuration overrides for the attestation fetcher
13644
+ * @returns The attestation response data.
13645
+ * @throws If the request fails, times out, or returns invalid data.
13646
+ *
13647
+ * @example
13648
+ * ```typescript
13649
+ * // Fetch attestation for mainnet transaction
13650
+ * const response = await fetchAttestation(1, '0xabc...', false)
13651
+ * console.log(`Found ${response.messages.length} attestation messages`)
13652
+ *
13653
+ * // Fetch with custom timeout
13654
+ * const response2 = await fetchAttestation(1, '0xdef...', true, {
13655
+ * timeout: 5000,
13656
+ * maxRetries: 5
13657
+ * })
13658
+ * ```
13659
+ */ const fetchAttestation = async (sourceDomainId, transactionHash, isTestnet, config = {})=>{
13660
+ const url = buildIrisUrl(sourceDomainId, transactionHash, isTestnet);
13661
+ const effectiveConfig = mergeAttestationConfig(config);
13662
+ return await pollApiGet(url, isAttestationResponse, effectiveConfig);
13663
+ };
13664
+ /**
13665
+ * Type guard that validates attestation response structure without requiring completion status.
13666
+ *
13667
+ * This is used by `fetchAttestationWithoutStatusCheck` to extract the nonce from an existing
13668
+ * attestation, even if the attestation is expired or pending. Unlike `isAttestationResponse`,
13669
+ * this function does not throw if no complete attestation is found.
13670
+ *
13671
+ * @param obj - The value to check, typically a parsed JSON response
13672
+ * @returns True if the object has valid attestation structure
13673
+ * @throws {Error} With "Invalid attestation response structure" if structure is invalid
13674
+ * @internal
13675
+ */ const isAttestationResponseWithoutStatusCheck = (obj)=>{
13676
+ if (!hasValidAttestationStructure(obj)) {
13677
+ throw new Error('Invalid attestation response structure');
13678
+ }
13679
+ return true;
13680
+ };
13681
+ /**
13682
+ * Fetches attestation data without requiring the attestation to be complete.
13683
+ *
13684
+ * This function is useful for retrieving attestation data (particularly the nonce)
13685
+ * from an existing transaction, even if the attestation has expired or is pending.
13686
+ * It uses minimal retries since we're fetching existing data, not waiting for completion.
13687
+ *
13688
+ * @param sourceDomainId - The CCTP domain ID of the source chain
13689
+ * @param transactionHash - The transaction hash to fetch attestation for
13690
+ * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
13691
+ * @param config - Optional configuration overrides
13692
+ * @returns The attestation response data (may contain incomplete/expired attestations)
13693
+ * @throws If the request fails, times out, or returns invalid data
13694
+ *
13695
+ * @example
13696
+ * ```typescript
13697
+ * // Fetch existing attestation to extract nonce for re-attestation
13698
+ * const response = await fetchAttestationWithoutStatusCheck(1, '0xabc...', true)
13699
+ * const nonce = response.messages[0]?.eventNonce
13700
+ * ```
13701
+ */ const fetchAttestationWithoutStatusCheck = async (sourceDomainId, transactionHash, isTestnet, config = {})=>{
13702
+ const url = buildIrisUrl(sourceDomainId, transactionHash, isTestnet);
13703
+ // Use minimal retries since we're just fetching existing data
13704
+ const effectiveConfig = mergeAttestationConfig(config, {
13705
+ maxRetries: 3
13706
+ });
13707
+ return await pollApiGet(url, isAttestationResponseWithoutStatusCheck, effectiveConfig);
13611
13708
  };
13612
13709
  /**
13613
- * Analyze bridge steps to determine retry feasibility and continuation point.
13614
- *
13615
- * This function examines the current state of bridge steps to determine the optimal
13616
- * continuation strategy. It uses a rule-based approach that makes it easy to extend
13617
- * with new flow patterns and step types in the future.
13618
- *
13619
- * The current analysis supports the standard CCTP flow:
13620
- * **Traditional flow**: Approve → Burn → FetchAttestation → Mint
13710
+ * Type guard that validates attestation response has expirationBlock === '0'.
13621
13711
  *
13622
- * Key features:
13623
- * - Rule-based transitions: Easy to extend with new step types and logic
13624
- * - Context-aware decisions: Considers execution history and step states
13625
- * - Actionable logic: Distinguishes between steps requiring user action vs waiting
13626
- * - Terminal states: Properly handles completion and non-actionable states
13712
+ * This is used after requestReAttestation() to poll until the attestation
13713
+ * is fully re-processed and has a zero expiration block (never expires).
13714
+ * The expiration block transitions from non-zero to zero when Circle
13715
+ * completes processing the re-attestation request.
13627
13716
  *
13628
- * @param bridgeResult - The bridge result containing step execution history.
13629
- * @returns Analysis result with continuation step and actionability information.
13630
- * @throws Error when bridgeResult is invalid or contains no steps array.
13717
+ * @param obj - The value to check, typically a parsed JSON response
13718
+ * @returns True if the attestation has expirationBlock === '0'
13719
+ * @throws {Error} With "Re-attestation not yet complete" if expirationBlock is not '0'
13631
13720
  *
13632
13721
  * @example
13633
13722
  * ```typescript
13634
- * import { analyzeSteps } from './analyzeSteps'
13723
+ * // After requesting re-attestation, use this to validate the response
13724
+ * const response = await pollApiGet(url, isReAttestedAttestationResponse, config)
13725
+ * // response.messages[0].decodedMessage.decodedMessageBody.expirationBlock === '0'
13726
+ * ```
13635
13727
  *
13636
- * // Failed approval step (requires user action)
13637
- * const bridgeResult = {
13638
- * steps: [
13639
- * { name: 'Approve', state: 'error', errorMessage: 'User rejected' }
13640
- * ]
13641
- * }
13728
+ * @internal
13729
+ */ const isReAttestedAttestationResponse = (obj)=>{
13730
+ // First validate the basic structure and completion status
13731
+ // This will throw appropriate errors for invalid structure or incomplete attestation
13732
+ if (!isAttestationResponse(obj)) ;
13733
+ // Check if the first message has expirationBlock === '0'
13734
+ const expirationBlock = obj.messages[0]?.decodedMessage?.decodedMessageBody?.expirationBlock;
13735
+ if (expirationBlock !== '0') {
13736
+ // Re-attestation not yet complete - allow retry via polling
13737
+ throw new Error('Re-attestation not yet complete: waiting for expirationBlock to become 0');
13738
+ }
13739
+ return true;
13740
+ };
13741
+ /**
13742
+ * Fetches attestation data and polls until expirationBlock === '0'.
13642
13743
  *
13643
- * const analysis = analyzeSteps(bridgeResult)
13644
- * // Result: { continuationStep: 'Approve', isRetryable: true,
13645
- * // reason: 'Retry failed approval' }
13646
- * ```
13744
+ * This function is used after calling requestReAttestation() to wait until
13745
+ * the attestation is fully re-processed. The expirationBlock transitions
13746
+ * from non-zero to zero when Circle completes the re-attestation.
13747
+ *
13748
+ * @param sourceDomainId - The CCTP domain ID of the source chain
13749
+ * @param transactionHash - The transaction hash to fetch attestation for
13750
+ * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
13751
+ * @param config - Optional configuration overrides
13752
+ * @returns The re-attested attestation response with expirationBlock === '0'
13753
+ * @throws If the request fails, times out, or expirationBlock never becomes 0
13647
13754
  *
13648
13755
  * @example
13649
13756
  * ```typescript
13650
- * // Pending transaction (requires waiting, not actionable)
13651
- * const bridgeResult = {
13652
- * steps: [
13653
- * { name: 'Approve', state: 'pending' }
13654
- * ]
13655
- * }
13757
+ * // After requesting re-attestation
13758
+ * await requestReAttestation(nonce, isTestnet)
13656
13759
  *
13657
- * const analysis = analyzeSteps(bridgeResult)
13658
- * // Result: { continuationStep: 'Approve', isRetryable: false,
13659
- * // reason: 'Continue pending approval' }
13760
+ * // Poll until expirationBlock becomes 0
13761
+ * const response = await fetchReAttestedAttestation(domainId, txHash, isTestnet)
13762
+ * // response.messages[0].decodedMessage.decodedMessageBody.expirationBlock === '0'
13660
13763
  * ```
13764
+ */ const fetchReAttestedAttestation = async (sourceDomainId, transactionHash, isTestnet, config = {})=>{
13765
+ const url = buildIrisUrl(sourceDomainId, transactionHash, isTestnet);
13766
+ const effectiveConfig = mergeAttestationConfig(config);
13767
+ return await pollApiGet(url, isReAttestedAttestationResponse, effectiveConfig);
13768
+ };
13769
+ /**
13770
+ * Builds the IRIS API URL for re-attestation requests.
13771
+ *
13772
+ * Constructs the URL for Circle's re-attestation endpoint that allows
13773
+ * requesting a fresh attestation for an expired nonce.
13774
+ *
13775
+ * @param nonce - The nonce from the original attestation
13776
+ * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
13777
+ * @returns A fully qualified URL string for the re-attestation endpoint
13661
13778
  *
13662
13779
  * @example
13663
13780
  * ```typescript
13664
- * // Completed bridge (nothing to do)
13665
- * const bridgeResult = {
13666
- * steps: [
13667
- * { name: 'Approve', state: 'success' },
13668
- * { name: 'Burn', state: 'success' },
13669
- * { name: 'FetchAttestation', state: 'success' },
13670
- * { name: 'Mint', state: 'success' }
13671
- * ]
13672
- * }
13781
+ * // Mainnet URL
13782
+ * const mainnetUrl = buildReAttestUrl('0xabc', false)
13783
+ * // => 'https://iris-api.circle.com/v2/reattest/0xabc'
13673
13784
  *
13674
- * const analysis = analyzeSteps(bridgeResult)
13675
- * // Result: { continuationStep: null, isRetryable: false,
13676
- * // reason: 'Bridge completed successfully' }
13785
+ * // Testnet URL
13786
+ * const testnetUrl = buildReAttestUrl('0xabc', true)
13787
+ * // => 'https://iris-api-sandbox.circle.com/v2/reattest/0xabc'
13677
13788
  * ```
13678
- */ const analyzeSteps = (bridgeResult)=>{
13679
- // Input validation
13680
- if (!bridgeResult || !Array.isArray(bridgeResult.steps)) {
13681
- throw new Error('Invalid bridgeResult: must contain a steps array');
13682
- }
13683
- const { steps } = bridgeResult;
13684
- // Build execution context from step history
13685
- const context = buildFlowContext(steps);
13686
- // Determine continuation logic using rule engine
13687
- const continuation = determineContinuationFromRules(context);
13688
- return {
13689
- continuationStep: continuation.nextStep,
13690
- isActionable: continuation.isActionable,
13691
- completedSteps: Array.from(context.completedSteps),
13692
- failedSteps: Array.from(context.failedSteps),
13693
- reason: continuation.reason
13694
- };
13789
+ */ const buildReAttestUrl = (nonce, isTestnet)=>{
13790
+ const baseUrl = isTestnet ? IRIS_API_SANDBOX_BASE_URL : IRIS_API_BASE_URL;
13791
+ const url = new URL(`${baseUrl}/v2/reattest/${nonce}`);
13792
+ return url.toString();
13695
13793
  };
13696
13794
  /**
13697
- * Build flow context from the execution history.
13795
+ * Type guard that validates the re-attestation API response structure.
13698
13796
  *
13699
- * @param steps - Array of executed bridge steps.
13700
- * @returns Flow context with execution state and history.
13701
- */ function buildFlowContext(steps) {
13702
- const completedSteps = new Set();
13703
- const failedSteps = new Set();
13704
- let lastStep;
13705
- // Process step history to build context
13706
- for (const step of steps){
13707
- if (step.state === 'success' || step.state === 'noop') {
13708
- completedSteps.add(step.name);
13709
- } else if (step.state === 'error') {
13710
- failedSteps.add(step.name);
13711
- }
13712
- // Track the last step for continuation logic
13713
- lastStep = {
13714
- name: step.name,
13715
- state: step.state
13716
- };
13797
+ * @param obj - The value to check, typically a parsed JSON response
13798
+ * @returns True if the object matches the ReAttestationResponse shape
13799
+ * @throws {Error} With "Invalid re-attestation response structure" if structure is invalid
13800
+ * @internal
13801
+ */ const isReAttestationResponse = (obj)=>{
13802
+ if (typeof obj !== 'object' || obj === null || !('message' in obj) || !('nonce' in obj) || typeof obj.message !== 'string' || typeof obj.nonce !== 'string') {
13803
+ throw new Error('Invalid re-attestation response structure');
13717
13804
  }
13718
- return {
13719
- completedSteps,
13720
- failedSteps,
13721
- ...lastStep && {
13722
- lastStep
13723
- }
13724
- };
13725
- }
13805
+ return true;
13806
+ };
13726
13807
  /**
13727
- * Determine continuation step using the rule engine.
13808
+ * Requests re-attestation for an expired attestation nonce.
13728
13809
  *
13729
- * @param context - The flow context with execution history.
13730
- * @returns Continuation decision with next step and actionability information.
13731
- */ function determineContinuationFromRules(context) {
13732
- const lastStepName = context.lastStep?.name;
13733
- // Handle initial state when no steps have been executed
13734
- if (lastStepName === undefined) {
13735
- const rules = STEP_TRANSITION_RULES[''];
13736
- const matchingRule = rules?.find((rule)=>rule.condition(context));
13737
- if (!matchingRule) {
13738
- return {
13739
- nextStep: null,
13740
- isActionable: false,
13741
- reason: 'No initial state rule found'
13742
- };
13743
- }
13744
- return {
13745
- nextStep: matchingRule.nextStep,
13746
- isActionable: matchingRule.isActionable,
13747
- reason: matchingRule.reason
13748
- };
13749
- }
13750
- // A step with an empty name is ambiguous and should be treated as an unrecoverable state.
13751
- if (lastStepName === '') {
13752
- return {
13753
- nextStep: null,
13754
- isActionable: false,
13755
- reason: 'No transition rules defined for step with empty name'
13756
- };
13757
- }
13758
- const rules = STEP_TRANSITION_RULES[lastStepName];
13759
- if (!rules) {
13760
- return {
13761
- nextStep: null,
13762
- isActionable: false,
13763
- reason: `No transition rules defined for step: ${lastStepName}`
13764
- };
13765
- }
13766
- // Find the first matching rule
13767
- const matchingRule = rules.find((rule)=>rule.condition(context));
13768
- if (!matchingRule) {
13769
- return {
13770
- nextStep: null,
13771
- isActionable: false,
13772
- reason: `No matching transition rule for current context`
13773
- };
13774
- }
13775
- return {
13776
- nextStep: matchingRule.nextStep,
13777
- isActionable: matchingRule.isActionable,
13778
- reason: matchingRule.reason
13779
- };
13780
- }
13781
-
13782
- /**
13783
- * Find a step by name in the bridge result.
13810
+ * This function calls Circle's re-attestation API endpoint to request a fresh
13811
+ * attestation for a previously issued nonce. After calling this function,
13812
+ * you should poll `fetchAttestation` to retrieve the new attestation.
13784
13813
  *
13785
- * @param result - The bridge result to search.
13786
- * @param stepName - The name of the step to find.
13787
- * @returns The step if found, undefined otherwise.
13814
+ * @param nonce - The nonce from the original (expired) attestation
13815
+ * @param isTestnet - Whether this is for a testnet chain (true) or mainnet chain (false)
13816
+ * @param config - Optional configuration overrides for the request
13817
+ * @returns The re-attestation response confirming the request was accepted
13818
+ * @throws If the request fails, times out, or returns invalid data
13788
13819
  *
13789
13820
  * @example
13790
13821
  * ```typescript
13791
- * import { findStepByName } from './findStep'
13822
+ * // Request re-attestation for an expired nonce
13823
+ * const response = await requestReAttestation('0xabc', true)
13824
+ * console.log(response.message) // "Re-attestation successfully requested for nonce."
13792
13825
  *
13793
- * const burnStep = findStepByName(result, 'burn')
13794
- * if (burnStep) {
13795
- * console.log('Burn tx:', burnStep.txHash)
13796
- * }
13826
+ * // After requesting re-attestation, poll for the new attestation
13827
+ * const attestation = await fetchAttestation(domainId, txHash, true)
13797
13828
  * ```
13798
- */ function findStepByName(result, stepName) {
13799
- return result.steps.find((step)=>step.name === stepName);
13800
- }
13829
+ */ const requestReAttestation = async (nonce, isTestnet, config = {})=>{
13830
+ const url = buildReAttestUrl(nonce, isTestnet);
13831
+ // Use minimal retries since we're just submitting a request, not polling for state
13832
+ const effectiveConfig = mergeAttestationConfig(config, {
13833
+ maxRetries: 3
13834
+ });
13835
+ return await pollApiPost(url, {}, isReAttestationResponse, effectiveConfig);
13836
+ };
13837
+
13801
13838
  /**
13802
- * Find a pending step by name and return it with its index.
13803
- *
13804
- * Searches for a step that matches both the step name and has a pending state.
13839
+ * Type guard that checks if the relayer has confirmed the mint transaction.
13805
13840
  *
13806
- * @param result - The bridge result containing steps to search through.
13807
- * @param stepName - The step name to find (e.g., 'burn', 'mint', 'fetchAttestation').
13808
- * @returns An object containing the step and its index in the steps array.
13809
- * @throws KitError if the specified pending step is not found.
13841
+ * This function validates that:
13842
+ * 1. The response has valid AttestationResponse structure
13843
+ * 2. At least one message has forwardState === 'CONFIRMED' (or 'COMPLETE') and a valid forwardTxHash
13810
13844
  *
13811
- * @example
13812
- * ```typescript
13813
- * import { findPendingStep } from './findStep'
13845
+ * If forwardState is 'FAILED', throws a non-retryable KitError.
13846
+ * If forwardState is 'PENDING' or not present, throws a RETRYABLE KitError to continue polling.
13814
13847
  *
13815
- * const { step, index } = findPendingStep(result, 'burn')
13816
- * console.log('Pending step:', step.name, 'at index:', index)
13817
- * ```
13818
- */ function findPendingStep(result, stepName) {
13819
- const index = result.steps.findIndex((step)=>step.name === stepName && step.state === 'pending');
13820
- if (index === -1) {
13848
+ * @param obj - The value to check, typically a parsed JSON response
13849
+ * @returns True if the relayer has confirmed the mint
13850
+ * @throws {KitError} With FATAL recoverability if structure is invalid
13851
+ * @throws {KitError} With RESUMABLE recoverability if forwardState is 'FAILED'
13852
+ * @throws {KitError} With RETRYABLE recoverability if still pending
13853
+ * @internal
13854
+ */ const isRelayerMintConfirmed = (obj)=>{
13855
+ // First check if the structure is valid
13856
+ if (!hasValidAttestationStructure(obj)) {
13821
13857
  throw new KitError({
13822
13858
  ...InputError.VALIDATION_FAILED,
13823
13859
  recoverability: 'FATAL',
13824
- message: `Pending step "${stepName}" not found in result`
13860
+ message: 'Invalid attestation response structure from IRIS API.'
13825
13861
  });
13826
13862
  }
13827
- const step = result.steps[index];
13828
- if (!step) {
13863
+ // Find the first message (typically there's only one)
13864
+ const message = obj.messages[0];
13865
+ if (!message) {
13829
13866
  throw new KitError({
13830
13867
  ...InputError.VALIDATION_FAILED,
13831
13868
  recoverability: 'FATAL',
13832
- message: 'Pending step is undefined'
13869
+ message: 'No attestation messages found in IRIS API response.'
13833
13870
  });
13834
13871
  }
13835
- return {
13836
- step,
13837
- index
13838
- };
13839
- }
13872
+ // Check for FAILED state - this is a permanent failure
13873
+ if (message.forwardState === 'FAILED') {
13874
+ throw new KitError({
13875
+ ...NetworkError.RELAYER_FORWARD_FAILED,
13876
+ recoverability: 'RESUMABLE',
13877
+ message: 'Circle relayer failed to forward the mint transaction. The mint may still have succeeded if another party submitted it. Check the recipient wallet balance before retrying. If the mint did not occur, you can manually submit it using the attestation data in the error cause.',
13878
+ cause: {
13879
+ trace: {
13880
+ eventNonce: message.eventNonce,
13881
+ attestation: message.attestation,
13882
+ message: message.message
13883
+ }
13884
+ }
13885
+ });
13886
+ }
13887
+ // Check if mint is confirmed (or complete) with a valid transaction hash
13888
+ // We accept both CONFIRMED and COMPLETE since COMPLETE implies CONFIRMED
13889
+ if ((message.forwardState === 'CONFIRMED' || message.forwardState === 'COMPLETE') && typeof message.forwardTxHash === 'string' && message.forwardTxHash.trim().length > 0) {
13890
+ return true;
13891
+ }
13892
+ // Still pending or not yet processed - throw RETRYABLE error to continue polling
13893
+ throw new KitError({
13894
+ ...NetworkError.RELAYER_PENDING,
13895
+ recoverability: 'RETRYABLE',
13896
+ message: 'Relayer mint not ready. Waiting for confirmation.'
13897
+ });
13898
+ };
13840
13899
  /**
13841
- * Get the burn transaction hash from bridge result.
13842
- *
13843
- * @param result - The bridge result.
13844
- * @returns The burn transaction hash, or undefined if not found.
13900
+ * Polls the attestation API until the relayer's mint transaction is confirmed.
13845
13901
  *
13846
- * @example
13847
- * ```typescript
13848
- * import { getBurnTxHash } from './findStep'
13902
+ * This function is used when `useForwarder` is enabled. Instead of the user
13903
+ * submitting the mint transaction, Circle's Orbit relayer handles it automatically.
13904
+ * This function polls until the relayer has submitted and confirmed the mint transaction.
13849
13905
  *
13850
- * const burnTxHash = getBurnTxHash(result)
13851
- * if (burnTxHash) {
13852
- * console.log('Burn tx hash:', burnTxHash)
13853
- * }
13854
- * ```
13855
- */ function getBurnTxHash(result) {
13856
- return findStepByName(result, CCTPv2StepName.burn)?.txHash;
13857
- }
13858
- /**
13859
- * Get the attestation data from bridge result.
13906
+ * @remarks
13907
+ * - Uses a 20-minute timeout by default (600 retries × 2 seconds)
13908
+ * - Throws immediately if `forwardState` is 'FAILED'
13909
+ * - Waits for `forwardState` to be 'CONFIRMED' or 'COMPLETE' (COMPLETE implies CONFIRMED)
13910
+ * - Returns the attestation message with `forwardTxHash` populated
13860
13911
  *
13861
- * @param result - The bridge result.
13862
- * @returns The attestation data, or undefined if not found.
13912
+ * @param sourceDomainId - The CCTP domain ID of the source chain
13913
+ * @param transactionHash - The transaction hash of the burn operation
13914
+ * @param isTestnet - Whether this is for a testnet chain (true) or mainnet (false)
13915
+ * @param config - Optional configuration overrides for polling behavior
13916
+ * @returns The attestation message with confirmed forwardTxHash
13917
+ * @throws {KitError} With code 'NETWORK_RELAYER_FORWARD_FAILED' if relayer failed
13918
+ * @throws {KitError} If timeout is reached while still pending
13863
13919
  *
13864
13920
  * @example
13865
13921
  * ```typescript
13866
- * import { getAttestationData } from './findStep'
13867
- *
13868
- * const attestation = getAttestationData(result)
13869
- * if (attestation) {
13870
- * console.log('Attestation:', attestation.message)
13871
- * }
13922
+ * const attestation = await fetchRelayerMint(0, '0xabc...', false)
13923
+ * console.log('Relayer mint tx:', attestation.forwardTxHash)
13872
13924
  * ```
13873
- */ function getAttestationData(result) {
13874
- // Prefer reAttest data (most recent attestation after expiry)
13875
- const reAttestStep = findStepByName(result, CCTPv2StepName.reAttest);
13876
- if (reAttestStep?.state === 'success' && reAttestStep.data) {
13877
- return reAttestStep.data;
13925
+ */ const fetchRelayerMint = async (sourceDomainId, transactionHash, isTestnet, config = {})=>{
13926
+ const url = buildIrisUrl(sourceDomainId, transactionHash, isTestnet);
13927
+ const effectiveConfig = mergeAttestationConfig(config);
13928
+ let response;
13929
+ try {
13930
+ response = await pollApiGet(url, isRelayerMintConfirmed, effectiveConfig);
13931
+ } catch (error) {
13932
+ // Enrich RELAYER_FORWARD_FAILED errors with the burn transaction hash
13933
+ if (error instanceof KitError && error.name === 'NETWORK_RELAYER_FORWARD_FAILED') {
13934
+ throw new KitError({
13935
+ ...NetworkError.RELAYER_FORWARD_FAILED,
13936
+ recoverability: error.recoverability,
13937
+ message: error.message,
13938
+ cause: {
13939
+ ...error.cause,
13940
+ trace: {
13941
+ ...error.cause?.trace,
13942
+ burnTxHash: transactionHash
13943
+ }
13944
+ }
13945
+ });
13946
+ }
13947
+ throw error;
13878
13948
  }
13879
- // Fall back to fetchAttestation step
13880
- const fetchStep = findStepByName(result, CCTPv2StepName.fetchAttestation);
13881
- return fetchStep?.data;
13882
- }
13949
+ // Return the first message (which should have forwardTxHash)
13950
+ // Note: This check is needed for TypeScript type safety even though
13951
+ // isRelayerMintConfirmed validates messages[0] exists. The type guard
13952
+ // narrows the type at the call site, but TypeScript can't infer that
13953
+ // the array still has elements after pollApiGet returns.
13954
+ const message = response.messages[0];
13955
+ if (!message) {
13956
+ throw new KitError({
13957
+ ...InputError.VALIDATION_FAILED,
13958
+ recoverability: 'FATAL',
13959
+ message: 'No attestation messages found in response after polling.'
13960
+ });
13961
+ }
13962
+ return message;
13963
+ };
13883
13964
 
13965
+ const assertCCTPv2WalletContextSymbol = Symbol('assertCCTPv2WalletContext');
13884
13966
  /**
13885
- * Check if the analysis indicates a non-actionable pending state.
13886
- *
13887
- * A pending state is non-actionable when there's a continuation step but
13888
- * the analysis marks it as not actionable, typically because we need to
13889
- * wait for an ongoing operation to complete.
13967
+ * Asserts that the provided parameters match the CCTPv2 wallet context interface.
13968
+ * The validation includes:
13969
+ * - Basic wallet context validation (adapter, address, chain)
13970
+ * - CCTPv2-specific chain validation (must be an EVM chain)
13890
13971
  *
13891
- * @param analysis - The step analysis result from analyzeSteps.
13892
- * @param result - The bridge result to check for pending steps.
13893
- * @returns True if there is a pending step that we should wait for.
13972
+ * @param params - The parameters to validate
13973
+ * @throws {KitError} If validation fails with INPUT_VALIDATION_FAILED code (1098), with details about which properties failed
13894
13974
  *
13895
13975
  * @example
13896
13976
  * ```typescript
13897
- * import { hasPendingState } from './stepUtils'
13898
- * import { analyzeSteps } from '../analyzeSteps'
13977
+ * import { assertCCTPv2WalletContext } from '@circle-fin/provider-cctp-v2'
13978
+ * import { Ethereum } from '@core/chains'
13899
13979
  *
13900
- * const analysis = analyzeSteps(bridgeResult)
13901
- * if (hasPendingState(analysis, bridgeResult)) {
13902
- * // Wait for the pending operation to complete
13980
+ * // Prepare wallet context
13981
+ * const context = {
13982
+ * adapter: {
13983
+ * prepare: async () => ({ data: 'prepared transaction' }),
13984
+ * waitForTransaction: async () => ({ status: 'confirmed' })
13985
+ * },
13986
+ * address: '0x1234567890123456789012345678901234567890',
13987
+ * chain: {
13988
+ * ...Ethereum,
13989
+ * usdcAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
13990
+ * cctp: {
13991
+ * domain: 1,
13992
+ * contracts: {
13993
+ * v2: {
13994
+ * tokenMessenger: '0xTokenMessenger',
13995
+ * messageTransmitter: '0xMessageTransmitter'
13996
+ * }
13997
+ * }
13998
+ * }
13999
+ * }
13903
14000
  * }
13904
- * ```
13905
- */ /**
13906
- * Evaluate a transaction receipt and return the corresponding step state
13907
- * and error message. Centralises the success/revert/unconfirmed logic so
13908
- * every call-site behaves identically.
13909
14001
  *
13910
- * @param receipt - The transaction receipt containing status and block info.
13911
- * @param txHash - The transaction hash used in error messages.
13912
- * @returns An object with `state` and an optional `errorMessage`.
14002
+ * // This will throw if validation fails
14003
+ * assertCCTPv2WalletContext(context)
13913
14004
  *
13914
- * @example
13915
- * ```typescript
13916
- * const outcome = evaluateTransactionOutcome(receipt, '0xabc...')
13917
- * step.state = outcome.state
13918
- * if (outcome.errorMessage) step.errorMessage = outcome.errorMessage
14005
+ * // If we get here, context is guaranteed to be valid
14006
+ * console.log('CCTPv2 wallet context is valid')
13919
14007
  * ```
13920
- */ function evaluateTransactionOutcome(receipt, txHash) {
13921
- if (receipt.status === 'success' && receipt.blockNumber) {
13922
- return {
13923
- state: 'success'
13924
- };
13925
- }
13926
- return {
13927
- state: 'error',
13928
- errorMessage: receipt.status === 'reverted' ? `Transaction ${txHash} was reverted` : 'Transaction was not confirmed on-chain'
13929
- };
13930
- }
13931
- function hasPendingState(analysis, result) {
13932
- // Check if there's a continuation step that's marked as non-actionable
13933
- if (analysis.continuationStep === null || analysis.isActionable) {
13934
- return false;
14008
+ */ function assertCCTPv2WalletContext(params) {
14009
+ // First validate basic wallet context
14010
+ validateWithStateTracking(params, walletContextSchema, 'CCTPv2 wallet context', assertCCTPv2WalletContextSymbol);
14011
+ // After validation, we know params is WalletContext
14012
+ const context = params;
14013
+ // Validate USDC support
14014
+ if (context.chain.usdcAddress === null) {
14015
+ throw createInvalidChainError(context.chain.name, 'Does not have USDC configured');
14016
+ }
14017
+ // Validate CCTPv2 support
14018
+ if (!isCCTPV2Supported(context.chain)) {
14019
+ throw createInvalidChainError(context.chain.name, 'Does not support CCTPv2');
13935
14020
  }
13936
- // Verify that the continuation step actually exists and is in pending state
13937
- const pendingStep = result.steps.find((step)=>step.name === analysis.continuationStep && step.state === 'pending');
13938
- return pendingStep !== undefined;
13939
14021
  }
14022
+
14023
+ const assertCCTPv2BridgeParamsSymbol = Symbol('assertCCTPv2BridgeParams');
13940
14024
  /**
13941
- * Check if the step is the last one in the execution flow.
14025
+ * Asserts that the provided parameters match the CCTPv2 bridge parameters interface.
14026
+ * The validation includes:
14027
+ * - Basic parameter structure and types
14028
+ * - Amount validation (non-empty numeric string \> 0)
14029
+ * - Wallet address format validation (must be valid Ethereum address)
14030
+ * - Chain definition validation (must be a valid chain with required properties)
14031
+ * - Adapter validation (must implement required methods)
14032
+ * - Optional config validation (transfer speed and max fee)
14033
+ * - Network compatibility (source and destination chains must both be testnet or both mainnet)
14034
+ * - CCTPv2-specific wallet context validations
13942
14035
  *
13943
- * @param step - The step object to check.
13944
- * @param stepNames - The ordered list of step names in the execution flow.
13945
- * @returns True if this is the last step in the flow.
14036
+ * @param params - The parameters to validate
14037
+ * @throws {KitError} If validation fails, with details about which properties failed
13946
14038
  *
13947
14039
  * @example
13948
14040
  * ```typescript
13949
- * import { isLastStep } from './stepUtils'
14041
+ * import { assertCCTPv2BridgeParams } from '@circle-fin/provider-cctp-v2'
14042
+ * import { Ethereum, Base } from '@core/chains'
13950
14043
  *
13951
- * const stepNames = ['approve', 'burn', 'fetchAttestation', 'mint']
13952
- * isLastStep({ name: 'mint' }, stepNames) // true
13953
- * isLastStep({ name: 'burn' }, stepNames) // false
14044
+ * // Prepare transfer parameters
14045
+ * const params = {
14046
+ * amount: '100.50',
14047
+ * source: {
14048
+ * adapter: sourceAdapter,
14049
+ * address: '0xSourceAddress',
14050
+ * chain: {
14051
+ * ...Ethereum,
14052
+ * cctp: {
14053
+ * domain: 1,
14054
+ * contracts: {
14055
+ * v2: {
14056
+ * tokenMessenger: '0xTokenMessenger',
14057
+ * messageTransmitter: '0xMessageTransmitter'
14058
+ * }
14059
+ * }
14060
+ * }
14061
+ * }
14062
+ * },
14063
+ * destination: {
14064
+ * adapter: destAdapter,
14065
+ * address: '0xDestAddress',
14066
+ * chain: {
14067
+ * ...Base,
14068
+ * cctp: {
14069
+ * domain: 2,
14070
+ * contracts: {
14071
+ * v2: {
14072
+ * tokenMessenger: '0xTokenMessenger',
14073
+ * messageTransmitter: '0xMessageTransmitter'
14074
+ * }
14075
+ * }
14076
+ * }
14077
+ * }
14078
+ * },
14079
+ * token: 'USDC',
14080
+ * config: {
14081
+ * transferSpeed: 'FAST',
14082
+ * maxFee: '1000000'
14083
+ * }
14084
+ * }
14085
+ *
14086
+ * // This will throw if validation fails
14087
+ * assertCCTPv2BridgeParams(params)
14088
+ *
14089
+ * // If we get here, params is guaranteed to be valid
14090
+ * console.log('CCTPv2 transfer parameters are valid')
13954
14091
  * ```
13955
- */ function isLastStep(step, stepNames) {
13956
- const stepIndex = stepNames.indexOf(step.name);
13957
- return stepIndex === -1 || stepIndex >= stepNames.length - 1;
14092
+ */ function assertCCTPv2BridgeParams(params) {
14093
+ // First validate basic bridge params
14094
+ validateWithStateTracking(params, bridgeParamsSchema, 'CCTPv2 bridge parameters', assertCCTPv2BridgeParamsSymbol);
14095
+ // After validation, we know params is CCTPV2BridgeParams
14096
+ const bridgeParams = params;
14097
+ // Enforce that source and destination chains are either testnet or mainnet
14098
+ if (bridgeParams.source.chain.isTestnet !== bridgeParams.destination.chain.isTestnet) {
14099
+ throw createNetworkMismatchError(bridgeParams.source.chain, bridgeParams.destination.chain);
14100
+ }
14101
+ assertCCTPV2Support(bridgeParams.source.chain, bridgeParams.destination.chain);
14102
+ // Validate that the destination chain supports forwarding when forwarder is enabled
14103
+ assertForwarderRouteSupport(bridgeParams.source.chain, bridgeParams.destination.chain, bridgeParams.destination.useForwarder);
14104
+ /**
14105
+ * Enforce that if fee is defined then feeRecipient must be defined.
14106
+ * We do not do this in the validation function itself because we want to allow
14107
+ * optional properties when calling `provider.bridge()` due to the custom fee
14108
+ * configuration being possible at the kit level as well.
14109
+ */ if (bridgeParams.config?.customFee?.value !== undefined && bridgeParams.config?.customFee?.recipientAddress === undefined) {
14110
+ throw createValidationFailedError$1('recipientAddress', bridgeParams.config.customFee.value, 'Custom fee is defined but fee recipient is not. Please provide a fee recipient.');
14111
+ }
14112
+ // Check if this is a forwarder-only destination (no adapter, requires useForwarder: true)
14113
+ const isForwarderOnly = bridgeParams.destination.useForwarder === true && !('adapter' in bridgeParams.destination && bridgeParams.destination.adapter);
14114
+ // Forwarder-only destinations require recipientAddress
14115
+ if (isForwarderOnly) {
14116
+ if (!bridgeParams.destination.recipientAddress?.trim()) {
14117
+ throw createValidationFailedError$1('recipientAddress', bridgeParams.destination.recipientAddress, 'recipientAddress is required when using forwarder without a destination adapter.');
14118
+ }
14119
+ }
14120
+ // Validate CCTP v2 specific requirements for source wallet
14121
+ assertCCTPv2WalletContext(bridgeParams.source);
14122
+ // Validate that source adapter supports the chain (defense-in-depth)
14123
+ bridgeParams.source.adapter.validateChainSupport(bridgeParams.source.chain);
14124
+ // Only validate destination wallet context and adapter if not forwarder-only
14125
+ if (!isForwarderOnly) {
14126
+ assertCCTPv2WalletContext(bridgeParams.destination);
14127
+ // Validate that destination adapter supports the chain (defense-in-depth)
14128
+ bridgeParams.destination.adapter.validateChainSupport(bridgeParams.destination.chain);
14129
+ }
13958
14130
  }
13959
14131
  /**
13960
- * Wait for a pending transaction to complete.
13961
- *
13962
- * Poll the adapter until the transaction is confirmed on-chain and return
13963
- * the updated step with success or error state based on the receipt.
13964
- *
13965
- * @param pendingStep - The full step object containing the transaction hash.
13966
- * @param adapter - The adapter to use for waiting.
13967
- * @param chain - The chain where the transaction was submitted.
13968
- * @returns The updated step object with success or error state.
14132
+ * Validate CCTP v2 support on both chains
14133
+ */ /**
14134
+ * Throws a KitError if the given chain does not support CCTP v2.
13969
14135
  *
13970
- * @throws KitError when the pending step has no transaction hash.
14136
+ * @param chain - The chain to check for CCTP v2 support
14137
+ * @param otherChain - The other chain in the route (for error context)
14138
+ * @param isSource - Whether this is the source chain (for error context)
14139
+ */ function assertCCTPV2Support(source, destination) {
14140
+ if (!isCCTPV2Supported(source) || !isCCTPV2Supported(destination)) {
14141
+ throw createUnsupportedRouteError(source.name, destination.name);
14142
+ }
14143
+ }
14144
+ /**
14145
+ * Validates that the forwarder (relaying) feature is compatible with the route.
13971
14146
  *
13972
- * @example
13973
- * ```typescript
13974
- * import { waitForPendingTransaction } from './bridgeStepUtils'
14147
+ * Checks the destination chain's `cctp.forwarderSupported.destination` property
14148
+ * to determine whether the chain supports receiving forwarded transfers.
13975
14149
  *
13976
- * const pendingStep = { name: 'burn', state: 'pending', txHash: '0x123...' }
13977
- * const updatedStep = await waitForPendingTransaction(pendingStep, adapter, chain)
13978
- * // updatedStep.state is now 'success' or 'error'
13979
- * ```
13980
- */ async function waitForPendingTransaction(pendingStep, adapter, chain) {
13981
- if (!pendingStep.txHash) {
14150
+ * @param source - The source chain definition
14151
+ * @param destination - The destination chain definition
14152
+ * @param useForwarder - Whether the forwarder is enabled on the destination
14153
+ * @throws {KitError} If the forwarder is enabled and the destination chain does not support forwarding
14154
+ */ function assertForwarderRouteSupport(source, destination, useForwarder) {
14155
+ if (useForwarder === true && !destination.cctp?.forwarderSupported.destination) {
13982
14156
  throw new KitError({
13983
- ...InputError.VALIDATION_FAILED,
14157
+ ...InputError.UNSUPPORTED_ROUTE,
13984
14158
  recoverability: 'FATAL',
13985
- message: `Cannot wait for pending ${pendingStep.name}: no transaction hash available`
14159
+ message: `Route from ${source.name} to ${destination.name} with forwarder is not supported (destination chain does not support forwarding).`,
14160
+ cause: {
14161
+ trace: {
14162
+ source: source.name,
14163
+ destination: destination.name
14164
+ }
14165
+ }
13986
14166
  });
13987
14167
  }
13988
- const txHash = pendingStep.txHash;
13989
- const txReceipt = await retryAsync(async ()=>adapter.waitForTransaction(txHash, undefined, chain), {
13990
- isRetryable: (err)=>isRetryableError$1(parseBlockchainError(err, {
13991
- chain: chain.name,
13992
- txHash
13993
- }))
13994
- });
13995
- const outcome = evaluateTransactionOutcome(txReceipt, txHash);
13996
- return {
13997
- ...pendingStep,
13998
- state: outcome.state,
13999
- data: txReceipt,
14000
- explorerUrl: buildExplorerUrl(chain, txHash),
14001
- ...outcome.errorMessage ? {
14002
- errorMessage: outcome.errorMessage
14003
- } : {}
14004
- };
14005
14168
  }
14169
+
14006
14170
  /**
14007
- * Wait for a pending step to complete.
14008
- *
14009
- * For transaction steps: waits for the transaction to be confirmed.
14010
- * For attestation: re-executes the attestation fetch.
14011
- *
14012
- * @typeParam TFromAdapterCapabilities - The capabilities of the source adapter.
14013
- * @typeParam TToAdapterCapabilities - The capabilities of the destination adapter.
14014
- * @param pendingStep - The full step object (with name, state, txHash, data, etc.) to resolve.
14015
- * @param adapter - The adapter to use.
14016
- * @param chain - The chain where the step is executing.
14017
- * @param context - The retry context.
14018
- * @param result - The bridge result.
14019
- * @param provider - The CCTP v2 bridging provider.
14020
- * @returns The resolved step object with updated state.
14021
- *
14022
- * @throws KitError when fetching attestation but burn transaction hash is not found.
14171
+ * Checks if a decoded attestation field matches the corresponding transfer parameter.
14172
+ * If the values do not match, appends a descriptive error message to the errors array.
14023
14173
  *
14024
- * @example
14025
- * ```typescript
14026
- * import { waitForStepToComplete } from './bridgeStepUtils'
14174
+ * @param field - The name of the field being compared (for error reporting)
14175
+ * @param decoded - The value decoded from the attestation message
14176
+ * @param param - The expected value from the transfer parameters
14177
+ * @param errors - The array to which error messages will be appended if a mismatch is found
14178
+ */ function checkFieldMismatch(field, decoded, param, errors) {
14179
+ if (decoded !== param) {
14180
+ errors.push(`${field} mismatch: decoded=${String(decoded)}, params=${String(param)}`);
14181
+ }
14182
+ }
14183
+ /**
14184
+ * Asserts that the decoded message from attestation matches the provided transfer params.
14185
+ * Throws KitError if any field mismatches, with clear error messages.
14027
14186
  *
14028
- * const pendingStep = { name: 'burn', state: 'pending', txHash: '0x123...' }
14029
- * const updatedStep = await waitForStepToComplete(
14030
- * pendingStep,
14031
- * adapter,
14032
- * chain,
14033
- * context,
14034
- * result,
14035
- * provider,
14036
- * )
14037
- * // updatedStep.state is now 'success' or 'error'
14038
- * ```
14039
- */ async function waitForStepToComplete(pendingStep, adapter, chain, context, result, provider) {
14040
- if (pendingStep.name === CCTPv2StepName.fetchAttestation) {
14041
- // For attestation, re-run the fetch (it has built-in polling)
14042
- const burnTxHash = getBurnTxHash(result);
14043
- if (!burnTxHash) {
14044
- throw new KitError({
14045
- ...InputError.VALIDATION_FAILED,
14046
- recoverability: 'FATAL',
14047
- message: 'Cannot fetch attestation: burn transaction hash not found'
14048
- });
14049
- }
14050
- const sourceAddress = result.source.address;
14051
- const attestation = await provider.fetchAttestation({
14052
- chain: result.source.chain,
14053
- adapter: context.from,
14054
- address: sourceAddress
14055
- }, burnTxHash);
14056
- return {
14057
- ...pendingStep,
14058
- state: 'success',
14059
- data: attestation
14060
- };
14187
+ * @param attestation - The attestation message containing the decoded message
14188
+ * @param params - The transfer parameters to validate against
14189
+ * @throws {@link KitError} If any field mismatches
14190
+ */ async function assertCCTPv2AttestationParams(attestation, params) {
14191
+ const errors = [];
14192
+ const message = attestation.decodedMessage;
14193
+ const messageBody = message.decodedMessageBody;
14194
+ // Use recipientAddress if provided, otherwise use destination.address
14195
+ const destinationAddressForMint = params.destination.recipientAddress ?? params.destination.address;
14196
+ const mintRecipient = await getMintRecipientAccount(params.destination.chain.type, destinationAddressForMint, params.destination.chain.usdcAddress);
14197
+ let sender;
14198
+ if (hasCustomContractSupport(params.source.chain, 'bridge')) {
14199
+ if (params.source.chain.type === 'solana') {
14200
+ // Solana: User Bridge contract → CCTP (user remains sender)
14201
+ sender = params.source.address;
14202
+ } else {
14203
+ // Other chains (like EVM): Bridge contract → CCTP (bridge contract becomes sender)
14204
+ sender = params.source.chain.kitContracts?.bridge;
14205
+ }
14206
+ } else {
14207
+ sender = params.source.address;
14208
+ }
14209
+ checkFieldMismatch('sourceDomain', message.sourceDomain, params.source.chain.cctp.domain.toString(), errors);
14210
+ checkFieldMismatch('destinationDomain', message.destinationDomain, params.destination.chain.cctp.domain.toString(), errors);
14211
+ checkFieldMismatch('minFinalityThreshold', message.minFinalityThreshold, CCTPv2MinFinalityThreshold[params.config.transferSpeed ?? 'FAST'].toString(), errors);
14212
+ checkFieldMismatch('sender', params.source.chain.type === 'evm' ? messageBody.messageSender.toLowerCase() : messageBody.messageSender, params.source.chain.type === 'evm' ? sender?.toLowerCase() : sender, errors);
14213
+ checkFieldMismatch('recipient', params.destination.chain.type === 'evm' ? messageBody.mintRecipient.toLowerCase() : messageBody.mintRecipient, params.destination.chain.type === 'evm' ? mintRecipient.toLowerCase() : mintRecipient, errors);
14214
+ checkFieldMismatch('amount', messageBody.amount, params.amount.toString(), errors);
14215
+ checkFieldMismatch('burnToken', messageBody.burnToken.toLowerCase(), params.source.chain.usdcAddress.toLowerCase(), errors);
14216
+ if (errors.length > 0) {
14217
+ const errorMessage = 'Attestation validation failed: received attestation does not match expected transfer parameters';
14218
+ const firstError = errors[0] ?? '';
14219
+ throw new KitError({
14220
+ ...InputError.VALIDATION_FAILED,
14221
+ recoverability: 'FATAL',
14222
+ message: `${errorMessage}: ${firstError}`,
14223
+ cause: {
14224
+ trace: {
14225
+ validationErrors: errors
14226
+ }
14227
+ }
14228
+ });
14061
14229
  }
14062
- // For transaction steps, wait for the transaction to complete
14063
- return waitForPendingTransaction(pendingStep, adapter, chain);
14064
14230
  }
14065
14231
 
14066
14232
  /**
14067
- * Multiplier applied to a successful gas estimate before it is submitted.
14068
- *
14069
- * Estimates are exact, not padded: Sei returns 109_739 for an approve that
14070
- * consumes 107_717 (1.9% headroom). Chains that price storage in large steps
14071
- * can exceed the estimate if state changes between estimation and inclusion,
14072
- * so the estimate is padded before use.
14233
+ * Assert that `params` is a well-formed {@link BurnWithFeesParams} object.
14073
14234
  *
14074
- * @remarks
14075
- * This buffer alone does NOT cover Sei's ~51_500 per-new-slot step at approve
14076
- * scale (25% of ~110_000 is only ~27_500). For approve, the FLOOR is what
14077
- * covers a slot that exists at estimation time and is consumed before
14078
- * inclusion — so do not lower `APPROVE_GAS_LIMIT_EVM` on the reasoning that
14079
- * the estimate covers it. For burn the buffer does cover a step (25% of
14080
- * ~300_000 exceeds 51_500).
14081
- */ const GAS_ESTIMATE_BUFFER_PERCENT = 125n;
14082
- /**
14083
- * Resolve the gas limit for an EVM request as `max(estimate * buffer, floor)`.
14235
+ * Validates the full public-boundary input before any field destructuring,
14236
+ * `BigInt()` coercion, or adapter preparation runs, so malformed JS-caller
14237
+ * inputs always produce typed `KitError` validation failures.
14084
14238
  *
14085
- * Estimates first so chains whose real cost exceeds the floor are covered by
14086
- * their own measurement, and falls back to the floor whenever estimation is
14087
- * unavailable or under-reports. Estimation failure is never fatal here: before
14088
- * floors existed these requests were submitted with a pinned limit and no
14089
- * estimate at all, so degrading to the floor is never worse than the previous
14090
- * behaviour.
14239
+ * Checks performed (in order):
14240
+ * - `params` must be a non-null plain object
14241
+ * - `source` valid CCTP v2 wallet context (via `assertCCTPv2WalletContext`)
14242
+ * - `destinationChain` present and supports CCTP v2
14243
+ * - source and destination chains must both be testnet or both mainnet
14244
+ * - source and destination chains must differ
14245
+ * - `executor` — non-empty string
14246
+ * - `amount` — bigint or non-empty string coercible to bigint
14247
+ * - `feeTotalAmount` — bigint or non-empty string coercible to bigint
14248
+ * - `feeToken` — valid EVM address (`0x` + 40 hex chars)
14249
+ * - `claim.signedQuote` — valid `0x`-prefixed hex string
14250
+ * - `claim.refundAddress` — valid EVM address
14251
+ * - `hookData` — valid `0x`-prefixed hex string when present
14091
14252
  *
14092
- * @param request - The prepared EVM request to size a gas limit for
14093
- * @param gasFloor - The minimum gas limit to submit, in gas units
14094
- * @returns The gas limit to submit, in gas units
14095
- * @throws Never — estimation failures degrade to `gasFloor`
14253
+ * @param params - The value to validate.
14254
+ * @throws {KitError} If any field is missing or invalid.
14096
14255
  *
14097
14256
  * @example
14098
14257
  * ```typescript
14099
- * const gasLimit = await resolveGasLimit(request, 150_000)
14258
+ * assertBurnWithFeesParams(params)
14259
+ * // params is now typed as BurnWithFeesParams and safe to use
14260
+ * const { source, destinationChain, amount } = params
14100
14261
  * ```
14101
- */ const resolveGasLimit = async (request, gasFloor)=>{
14262
+ */ function assertBurnWithFeesParams(params) {
14263
+ if (params === null || typeof params !== 'object' || Array.isArray(params)) {
14264
+ throw createValidationFailedError$1('params', params, 'Must be a non-null plain object');
14265
+ }
14266
+ const p = params;
14267
+ // Source wallet context
14268
+ assertCCTPv2WalletContext(p['source']);
14269
+ const source = p['source'];
14270
+ // destinationChain
14271
+ const destinationChain = p['destinationChain'];
14272
+ if (destinationChain === null || destinationChain === undefined || typeof destinationChain !== 'object') {
14273
+ throw createValidationFailedError$1('destinationChain', destinationChain, 'Must be a chain definition object');
14274
+ }
14275
+ if (!isCCTPV2Supported(destinationChain)) {
14276
+ throw createValidationFailedError$1('destinationChain', destinationChain, 'destinationChain must support CCTP v2');
14277
+ }
14278
+ const dest = destinationChain;
14279
+ // Testnet / mainnet mismatch
14280
+ if (source.chain.isTestnet !== dest.isTestnet) {
14281
+ throw createNetworkMismatchError(source.chain, dest);
14282
+ }
14283
+ // Same-chain guard
14284
+ if (source.chain.name === dest.name) {
14285
+ throw createUnsupportedRouteError(source.chain.name, dest.name);
14286
+ }
14287
+ // executor
14288
+ const executor = p['executor'];
14289
+ if (typeof executor !== 'string' || executor === '') {
14290
+ throw createValidationFailedError$1('executor', executor, 'A GenericExecutor address is required (used for both mintRecipient and destinationCaller)');
14291
+ }
14292
+ // amount
14293
+ const rawAmount = p['amount'];
14294
+ if (typeof rawAmount !== 'bigint' && typeof rawAmount !== 'string' || rawAmount === '') {
14295
+ throw createValidationFailedError$1('amount', rawAmount, 'Must be a bigint or a numeric string');
14296
+ }
14102
14297
  try {
14103
- // Deliberately called without a `fallback`: both the viem and ethers
14104
- // adapters *return* the supplied fallback object when estimation reverts
14105
- // rather than throwing, which would set the estimate to the floor and then
14106
- // multiply it by the buffer below. Omitting it routes reverts through the
14107
- // catch, so a failed estimate degrades to exactly the floor.
14108
- const estimate = await request.estimate();
14109
- // The arithmetic stays inside the try on purpose. `EstimatedGas.gas` is
14110
- // typed `bigint`, but adapters are a public extension point and may be
14111
- // implemented in plain JS, so a non-bigint `gas` would throw here
14112
- // ("Cannot mix BigInt and other types"). Guarding it keeps the documented
14113
- // contract — estimation never aborts a step, it degrades to the floor.
14114
- const buffered = estimate.gas * GAS_ESTIMATE_BUFFER_PERCENT / 100n;
14115
- // Convert before comparing: Math.max throws on BigInt operands, and gas
14116
- // units are far below Number.MAX_SAFE_INTEGER so the narrowing is lossless.
14117
- return Math.max(Number(buffered), gasFloor);
14298
+ BigInt(rawAmount);
14118
14299
  } catch {
14119
- // Estimation is best-effort; the floor is the known-safe value.
14120
- return gasFloor;
14300
+ throw createValidationFailedError$1('amount', rawAmount, 'Must be a valid integer value coercible to bigint');
14301
+ }
14302
+ // feeTotalAmount
14303
+ const rawFee = p['feeTotalAmount'];
14304
+ if (typeof rawFee !== 'bigint' && typeof rawFee !== 'string' || rawFee === '') {
14305
+ throw createValidationFailedError$1('feeTotalAmount', rawFee, 'Must be a bigint or a numeric string');
14121
14306
  }
14122
- };
14123
- /**
14124
- * Executes a prepared chain request and returns the result as a bridge step.
14125
- *
14126
- * This function takes a prepared chain request (containing transaction data) and executes
14127
- * it using the appropriate adapter. It handles the execution details and formats
14128
- * the result as a standardized bridge step with transaction details and explorer URLs.
14129
- *
14130
- * @param params - The execution parameters containing:
14131
- * - `name`: The name of the step
14132
- * - `request`: The prepared chain request containing transaction data
14133
- * - `adapter`: The adapter that will execute the transaction
14134
- * - `confirmations`: The number of confirmations to wait for (defaults to 1)
14135
- * - `timeout`: The timeout for the request in milliseconds
14136
- * - `gasFloor`: Optional minimum gas limit (number); the request is submitted
14137
- * with `max(estimate * 1.25, gasFloor)`. Ignored for non-EVM requests
14138
- * @returns The bridge step with the transaction details and explorer URL
14139
- * @throws If the transaction execution fails
14140
- *
14141
- * @example
14142
- * ```typescript
14143
- * const step = await executePreparedChainRequest({
14144
- * name: 'approve',
14145
- * request: preparedRequest,
14146
- * adapter: adapter,
14147
- * confirmations: 2,
14148
- * timeout: 30000
14149
- * })
14150
- * console.log('Transaction hash:', step.txHash)
14151
- * ```
14152
- */ async function executePreparedChainRequest({ name, request, adapter, chain, confirmations = 1, timeout, gasFloor }) {
14153
- const step = {
14154
- name,
14155
- state: 'pending'
14156
- };
14157
14307
  try {
14158
- /**
14159
- * No-op requests are not executed.
14160
- * We return a noop step instead.
14161
- */ if (request.type === 'noop') {
14162
- step.state = 'noop';
14163
- return step;
14164
- }
14165
- const txHash = request.type === 'evm' && gasFloor !== undefined ? await request.execute({
14166
- gasLimit: await resolveGasLimit(request, gasFloor)
14167
- }) : await request.execute();
14168
- step.txHash = txHash;
14169
- const retryOptions = {
14170
- isRetryable: (err)=>isRetryableError$1(parseBlockchainError(err, {
14171
- chain: chain.name,
14172
- txHash
14173
- }))
14174
- };
14175
- if (timeout !== undefined) {
14176
- retryOptions.deadlineMs = Date.now() + timeout;
14177
- }
14178
- const transaction = await retryAsync(async ()=>adapter.waitForTransaction(txHash, {
14179
- confirmations,
14180
- timeout
14181
- }, chain), retryOptions);
14182
- const outcome = evaluateTransactionOutcome(transaction, txHash);
14183
- step.state = outcome.state;
14184
- step.data = transaction;
14185
- // Generate explorer URL for the step
14186
- step.explorerUrl = buildExplorerUrl(chain, txHash);
14187
- if (outcome.errorMessage) {
14188
- step.errorMessage = outcome.errorMessage;
14189
- // Transaction was mined but reverted on-chain.
14190
- step.errorCategory = 'chain_revert';
14191
- }
14192
- } catch (err) {
14193
- step.state = 'error';
14194
- step.error = err;
14195
- // Sequential path does not yet attempt fine-grained classification of
14196
- // pre-submission errors (user_rejected, capability errors, etc.). Mark
14197
- // as `unknown` so consumers can at least detect the category is
14198
- // populated uniformly across batched and sequential flows.
14199
- step.errorCategory = 'unknown';
14200
- // Optionally parse for common blockchain error formats
14201
- if (err instanceof Error) {
14202
- step.errorMessage = err.message;
14203
- } else if (typeof err === 'object' && err != null && 'message' in err) {
14204
- step.errorMessage = String(err.message);
14205
- } else {
14206
- step.errorMessage = `Unknown error occurred during ${name} step.`;
14207
- }
14308
+ BigInt(rawFee);
14309
+ } catch {
14310
+ throw createValidationFailedError$1('feeTotalAmount', rawFee, 'Must be a valid integer value coercible to bigint');
14311
+ }
14312
+ // feeToken
14313
+ if (!evmAddressSchema.safeParse(p['feeToken']).success) {
14314
+ throw createValidationFailedError$1('feeToken', p['feeToken'], 'Must be a valid EVM address (use the zero address for a native fee)');
14315
+ }
14316
+ // claim
14317
+ const rawClaim = p['claim'];
14318
+ if (rawClaim === null || typeof rawClaim !== 'object' || Array.isArray(rawClaim)) {
14319
+ throw createValidationFailedError$1('claim', rawClaim, 'Must be an object with signedQuote and refundAddress');
14320
+ }
14321
+ const claim = rawClaim;
14322
+ if (!hexStringSchema.safeParse(claim['signedQuote']).success) {
14323
+ throw createValidationFailedError$1('claim.signedQuote', claim['signedQuote'], 'Must be a valid hex string starting with 0x');
14324
+ }
14325
+ if (!evmAddressSchema.safeParse(claim['refundAddress']).success) {
14326
+ throw createValidationFailedError$1('claim.refundAddress', claim['refundAddress'], 'Must be a valid EVM address');
14327
+ }
14328
+ // hookData (optional)
14329
+ const hookData = p['hookData'];
14330
+ if (hookData !== undefined && hookData !== '' && !hexStringSchema.safeParse(hookData).success) {
14331
+ throw createValidationFailedError$1('hookData', hookData, 'Must be a valid hex string starting with 0x');
14208
14332
  }
14209
- return step;
14210
14333
  }
14211
14334
 
14212
14335
  /**
@@ -14237,7 +14360,7 @@ function hasPendingState(analysis, result) {
14237
14360
  adapter: params.source.adapter,
14238
14361
  chain: params.source.chain,
14239
14362
  request: await provider.approve(params.source, approvalAmount),
14240
- gasFloor: Number(APPROVE_GAS_LIMIT_EVM)
14363
+ gasFloor: Number(BRIDGE_STEP_GAS_FLOORS_EVM.approve)
14241
14364
  });
14242
14365
  }
14243
14366
 
@@ -14265,7 +14388,7 @@ function hasPendingState(analysis, result) {
14265
14388
  adapter: params.source.adapter,
14266
14389
  chain: params.source.chain,
14267
14390
  request: await provider.burn(params),
14268
- gasFloor: Number(DEPOSIT_FOR_BURN_GAS_LIMIT_EVM)
14391
+ gasFloor: Number(BRIDGE_STEP_GAS_FLOORS_EVM.burn)
14269
14392
  });
14270
14393
  }
14271
14394
 
@@ -14361,7 +14484,7 @@ function hasPendingState(analysis, result) {
14361
14484
  // eth_estimateGas does not account for, returning a below-floor value
14362
14485
  // without reverting. The floor covers those; chains that cost more than the
14363
14486
  // floor are covered by their own estimate.
14364
- gasFloor: Number(RECEIVE_MESSAGE_GAS_LIMIT_EVM)
14487
+ gasFloor: Number(BRIDGE_STEP_GAS_FLOORS_EVM.mint)
14365
14488
  });
14366
14489
  // Add forwarded: false for non-relayer mints
14367
14490
  return {
@@ -14884,7 +15007,7 @@ const mockAttestationMessage = {
14884
15007
  return step;
14885
15008
  }
14886
15009
 
14887
- var version$2 = "1.10.2";
15010
+ var version$2 = "1.11.0";
14888
15011
  var pkg$2 = {
14889
15012
  version: version$2};
14890
15013
 
@@ -15843,10 +15966,39 @@ function assertCCTPV2Config(config) {
15843
15966
  // CCTP-specific transfer params validation (includes base validation)
15844
15967
  assertCCTPv2BridgeParams(params);
15845
15968
  const { source, destination, amount } = params;
15846
- const estimateBurn = async ()=>{
15847
- const burn = await this.burn(params);
15848
- return await burn.estimate(undefined, await source.adapter.calculateTransactionFee(hasCustomContractSupport(source.chain, 'bridge') ? CUSTOM_BURN_GAS_ESTIMATE_EVM : DEPOSIT_FOR_BURN_GAS_ESTIMATE_EVM, undefined, source.chain));
15969
+ /**
15970
+ * Price the gas a step will RESERVE on-chain, not what it will spend.
15971
+ *
15972
+ * A transaction is only admitted when the sender holds
15973
+ * `gasLimit * gasPrice`, and `executePreparedChainRequest` submits
15974
+ * `max(estimate * buffer, floor)`. Quoting a bare `estimate()` therefore
15975
+ * under-reports what a wallet must hold to send at all: the floor governs
15976
+ * on virtually every chain, which put the burn quote ~2.5x below the real
15977
+ * requirement and left anyone funding from it unable to submit.
15978
+ *
15979
+ * Delegates to the same `resolveGasLimit` the execute path calls, so a
15980
+ * quote and the limit later submitted for that step cannot drift apart.
15981
+ * That also means an estimation failure degrades to the floor here exactly
15982
+ * as it does on execution, rather than surfacing as a failed quote — the
15983
+ * floor is what would be submitted, so it is the honest number to quote.
15984
+ *
15985
+ * Non-EVM requests are unchanged: `executePreparedChainRequest` only
15986
+ * applies a floor when `request.type === 'evm'`, so there is no reserved
15987
+ * limit to quote on other chains.
15988
+ */ const quoteReservedGas = async (request, gasFloor, priceGas, // Ignored on EVM — only evaluated and used on non-EVM paths.
15989
+ nonEvmFallbackGasEstimate)=>{
15990
+ if (request.type !== 'evm') {
15991
+ return nonEvmFallbackGasEstimate === undefined ? await request.estimate() : await request.estimate(undefined, await priceGas(nonEvmFallbackGasEstimate()));
15992
+ }
15993
+ // resolveGasLimit returns number; gas units are well below Number.MAX_SAFE_INTEGER,
15994
+ // so the Number() → resolveGasLimit → BigInt() round-trip is lossless.
15995
+ return await priceGas(BigInt(await resolveGasLimit(request, Number(gasFloor))));
15849
15996
  };
15997
+ const priceGasFor = (ctx)=>async (gasUnits)=>await ctx.adapter.calculateTransactionFee(gasUnits, undefined, ctx.chain);
15998
+ const priceSourceGas = priceGasFor(source);
15999
+ const priceDestinationGas = priceGasFor(destination);
16000
+ const estimateApprove = async ()=>await quoteReservedGas(await this.approve(source, amount), BRIDGE_STEP_GAS_FLOORS_EVM.approve, priceSourceGas);
16001
+ const estimateBurn = async ()=>await quoteReservedGas(await this.burn(params), BRIDGE_STEP_GAS_FLOORS_EVM.burn, priceSourceGas, ()=>hasCustomContractSupport(source.chain, 'bridge') ? CUSTOM_BURN_GAS_ESTIMATE_EVM : DEPOSIT_FOR_BURN_GAS_ESTIMATE_EVM);
15850
16002
  // Only estimate Mint gas when not using forwarder (user pays gas)
15851
16003
  // When useForwarder=true, Circle's Orbit relayer handles and pays for the mint
15852
16004
  const useForwarder = destination.useForwarder === true;
@@ -15855,12 +16007,11 @@ function assertCCTPV2Config(config) {
15855
16007
  return null // Skip mint estimation when forwarder handles it
15856
16008
  ;
15857
16009
  }
15858
- const mint = await this.mint(source, destination, mockAttestationMessage);
15859
- return await mint.estimate(undefined, await destination.adapter.calculateTransactionFee(RECEIVE_MESSAGE_GAS_ESTIMATE_EVM, undefined, destination.chain));
16010
+ return await quoteReservedGas(await this.mint(source, destination, mockAttestationMessage), BRIDGE_STEP_GAS_FLOORS_EVM.mint, priceDestinationGas, ()=>RECEIVE_MESSAGE_GAS_ESTIMATE_EVM);
15860
16011
  };
15861
16012
  // Parallelize all independent async operations
15862
16013
  const [approveEstimate, depositForBurnFee, receiveMessageFee, feeEstimates] = await Promise.allSettled([
15863
- this.approve(source, amount).then(async (approve)=>approve.estimate()),
16014
+ estimateApprove(),
15864
16015
  estimateBurn(),
15865
16016
  estimateMint(),
15866
16017
  this.getMaxFee(params)
@@ -17500,7 +17651,7 @@ registerKit(`${pkg$3.name}/${pkg$3.version}`);
17500
17651
  };
17501
17652
 
17502
17653
  var name$1 = "@circle-fin/swap-kit";
17503
- var version$1 = "1.5.1";
17654
+ var version$1 = "1.5.2";
17504
17655
  var pkg$1 = {
17505
17656
  name: name$1,
17506
17657
  version: version$1};
@@ -19443,7 +19594,7 @@ new Set(Object.values(Blockchain));
19443
19594
  registerKit(`${pkg$1.name}/${pkg$1.version}`);
19444
19595
 
19445
19596
  var name = "@circle-fin/earn-kit";
19446
- var version = "1.5.0";
19597
+ var version = "1.5.1";
19447
19598
  var pkg = {
19448
19599
  name: name,
19449
19600
  version: version};
@@ -21014,7 +21165,7 @@ registerKit(`${pkg.name}/${pkg.version}`);
21014
21165
  * token: 'USDC'
21015
21166
  * })
21016
21167
  *
21017
- * console.log('Bridge completed:', result.hash)
21168
+ * console.log(`Bridged ${result.amount} ${result.token} (${result.state})`)
21018
21169
  * ```
21019
21170
  */ const bridge = async (context, params)=>{
21020
21171
  const kit = createBridgeKit(context);