@circle-fin/app-kit 1.11.0 → 1.12.0

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/earn.mjs CHANGED
@@ -37,6 +37,7 @@ import 'bn.js';
37
37
  import '@coral-xyz/anchor';
38
38
  import 'bs58';
39
39
  import '@noble/curves/ed25519';
40
+ import { decodeFunctionData } from 'viem';
40
41
  import { formatUnits as formatUnits$1 } from '@ethersproject/units';
41
42
  import { keccak256 } from '@ethersproject/keccak256';
42
43
 
@@ -677,6 +678,11 @@ class KitError extends Error {
677
678
  name: 'INPUT_INSUFFICIENT_SWAP_AMOUNT',
678
679
  type: 'INPUT'
679
680
  },
681
+ /** Action not supported by this adapter / ecosystem */ UNSUPPORTED_ACTION: {
682
+ code: 1008,
683
+ name: 'INPUT_UNSUPPORTED_ACTION',
684
+ type: 'INPUT'
685
+ },
680
686
  /** No route satisfies the slippage or minimum-output constraint */ SLIPPAGE_CONSTRAINT_NOT_MET: {
681
687
  code: 1009,
682
688
  name: 'INPUT_SLIPPAGE_CONSTRAINT_NOT_MET',
@@ -741,6 +747,29 @@ class KitError extends Error {
741
747
  type: 'LIQUIDITY'
742
748
  }
743
749
  };
750
+ /**
751
+ * Standardized error definitions for RPC type errors.
752
+ *
753
+ * RPC errors occur when communicating with blockchain RPC providers,
754
+ * including endpoint failures, invalid responses, and provider-specific issues.
755
+ *
756
+ * @example
757
+ * ```typescript
758
+ * import { RpcError } from '@core/errors'
759
+ *
760
+ * const error = new KitError({
761
+ * ...RpcError.ENDPOINT_ERROR,
762
+ * recoverability: 'RETRYABLE',
763
+ * message: 'RPC endpoint unavailable on Ethereum',
764
+ * cause: { trace: { endpoint: 'https://mainnet.infura.io' } }
765
+ * })
766
+ * ```
767
+ */ const RpcError = {
768
+ /** RPC endpoint returned error or is unavailable */ ENDPOINT_ERROR: {
769
+ code: 4001,
770
+ name: 'RPC_ENDPOINT_ERROR',
771
+ type: 'RPC'
772
+ }};
744
773
  /**
745
774
  * Standardized error definitions for NETWORK type errors.
746
775
  *
@@ -2340,6 +2369,8 @@ function getOptionalString(value) {
2340
2369
  Blockchain["World_Chain_Sepolia"] = "World_Chain_Sepolia";
2341
2370
  Blockchain["XDC"] = "XDC";
2342
2371
  Blockchain["XDC_Apothem"] = "XDC_Apothem";
2372
+ Blockchain["X_Layer"] = "X_Layer";
2373
+ Blockchain["X_Layer_Testnet"] = "X_Layer_Testnet";
2343
2374
  Blockchain["ZKSync_Era"] = "ZKSync_Era";
2344
2375
  Blockchain["ZKSync_Sepolia"] = "ZKSync_Sepolia";
2345
2376
  })(Blockchain || (Blockchain = {}));
@@ -2393,6 +2424,7 @@ var BridgeChain;
2393
2424
  BridgeChain["Unichain"] = "Unichain";
2394
2425
  BridgeChain["World_Chain"] = "World_Chain";
2395
2426
  BridgeChain["XDC"] = "XDC";
2427
+ BridgeChain["X_Layer"] = "X_Layer";
2396
2428
  // Testnet chains with CCTPv2 support
2397
2429
  BridgeChain["Arc_Testnet"] = "Arc_Testnet";
2398
2430
  BridgeChain["Arbitrum_Sepolia"] = "Arbitrum_Sepolia";
@@ -2418,6 +2450,7 @@ var BridgeChain;
2418
2450
  BridgeChain["Unichain_Sepolia"] = "Unichain_Sepolia";
2419
2451
  BridgeChain["World_Chain_Sepolia"] = "World_Chain_Sepolia";
2420
2452
  BridgeChain["XDC_Apothem"] = "XDC_Apothem";
2453
+ BridgeChain["X_Layer_Testnet"] = "X_Layer_Testnet";
2421
2454
  })(BridgeChain || (BridgeChain = {}));
2422
2455
  var UnifiedBalanceChain;
2423
2456
  (function(UnifiedBalanceChain) {
@@ -4955,7 +4988,8 @@ var EarnChain;
4955
4988
  isTestnet: true,
4956
4989
  explorerUrl: 'https://amoy.polygonscan.com/tx/{hash}',
4957
4990
  rpcEndpoints: [
4958
- 'https://rpc-amoy.polygon.technology'
4991
+ 'https://polygon-amoy-bor-rpc.publicnode.com',
4992
+ 'https://polygon-amoy.drpc.org'
4959
4993
  ],
4960
4994
  eurcAddress: null,
4961
4995
  usdcAddress: '0x41e94eb019c0762f9bfcf9fb1e58725bfb0e7582',
@@ -5820,6 +5854,104 @@ var EarnChain;
5820
5854
  }
5821
5855
  });
5822
5856
 
5857
+ /**
5858
+ * X Layer Mainnet chain definition
5859
+ * @remarks
5860
+ * This represents the official production network for the X Layer blockchain.
5861
+ * X Layer is an EVM-compatible OP Stack Layer-2 blockchain built by OKX,
5862
+ * using OKB as its native gas token. (Migrated from Polygon zkEVM/CDK to the
5863
+ * OP Stack on 2025-10-27; older docs describing it as zkEVM are obsolete.)
5864
+ */ const XLayer = defineChain({
5865
+ type: 'evm',
5866
+ chain: Blockchain.X_Layer,
5867
+ name: 'X Layer',
5868
+ title: 'X Layer Mainnet',
5869
+ nativeCurrency: {
5870
+ name: 'OKB',
5871
+ symbol: 'OKB',
5872
+ decimals: 18
5873
+ },
5874
+ chainId: 196,
5875
+ isTestnet: false,
5876
+ explorerUrl: 'https://www.oklink.com/xlayer/tx/{hash}',
5877
+ rpcEndpoints: [
5878
+ 'https://xlayerrpc.okx.com'
5879
+ ],
5880
+ eurcAddress: null,
5881
+ usdcAddress: '0xB6CEceAB302E2E4948951eE7843FC24E92933061',
5882
+ usdtAddress: null,
5883
+ cctp: {
5884
+ domain: 37,
5885
+ contracts: {
5886
+ v2: {
5887
+ type: 'split',
5888
+ tokenMessenger: '0x28b5a0e9C621a5BadaA536219b3a228C8168cf5d',
5889
+ messageTransmitter: '0x81D40F21F12A8F0E3252Bccb954D722d4c464B64',
5890
+ confirmations: 65,
5891
+ fastConfirmations: 1
5892
+ }
5893
+ },
5894
+ forwarderSupported: {
5895
+ source: false,
5896
+ destination: false
5897
+ }
5898
+ },
5899
+ kitContracts: {
5900
+ bridge: BRIDGE_CONTRACT_EVM_MAINNET
5901
+ }
5902
+ });
5903
+
5904
+ /**
5905
+ * X Layer Testnet chain definition
5906
+ * @remarks
5907
+ * This represents the official test network for the X Layer blockchain.
5908
+ * X Layer is an EVM-compatible OP Stack Layer-2 blockchain built by OKX,
5909
+ * using OKB as its native gas token. (Migrated from Polygon zkEVM/CDK to the
5910
+ * OP Stack on 2025-10-27; older docs describing it as zkEVM are obsolete.)
5911
+ */ const XLayerTestnet = defineChain({
5912
+ type: 'evm',
5913
+ chain: Blockchain.X_Layer_Testnet,
5914
+ name: 'X Layer Testnet',
5915
+ title: 'X Layer Testnet',
5916
+ nativeCurrency: {
5917
+ name: 'OKB',
5918
+ symbol: 'OKB',
5919
+ decimals: 18
5920
+ },
5921
+ chainId: 1952,
5922
+ isTestnet: true,
5923
+ // Deliberately not oklink.com (used for mainnet): viem's bundled OKLink
5924
+ // testnet URL targets the deprecated pre-rebrand chain ID 195, not this
5925
+ // chain's ID (1952). Verified against the internal chain-expansion-scripts
5926
+ // config (`v2config.sandbox.yml`) — do not "normalize" this to match mainnet.
5927
+ explorerUrl: 'https://web3.okx.com/explorer/x-layer-testnet/tx/{hash}',
5928
+ rpcEndpoints: [
5929
+ 'https://testrpc.xlayer.tech'
5930
+ ],
5931
+ eurcAddress: null,
5932
+ usdcAddress: '0xDec90b78111Ba2fc6FC6d84d8B9ec159A2d4b9B3',
5933
+ usdtAddress: null,
5934
+ cctp: {
5935
+ domain: 37,
5936
+ contracts: {
5937
+ v2: {
5938
+ type: 'split',
5939
+ tokenMessenger: '0x8FE6B999Dc680CcFDD5Bf7EB0974218be2542DAA',
5940
+ messageTransmitter: '0xE737e5cEBEEBa77EFE34D4aa090756590b1CE275',
5941
+ confirmations: 65,
5942
+ fastConfirmations: 1
5943
+ }
5944
+ },
5945
+ forwarderSupported: {
5946
+ source: false,
5947
+ destination: false
5948
+ }
5949
+ },
5950
+ kitContracts: {
5951
+ bridge: BRIDGE_CONTRACT_EVM_TESTNET
5952
+ }
5953
+ });
5954
+
5823
5955
  /**
5824
5956
  * ZKSync Era Mainnet chain definition
5825
5957
  * @remarks
@@ -5939,6 +6071,8 @@ var Chains = /*#__PURE__*/Object.freeze({
5939
6071
  WorldChainSepolia: WorldChainSepolia,
5940
6072
  XDC: XDC,
5941
6073
  XDCApothem: XDCApothem,
6074
+ XLayer: XLayer,
6075
+ XLayerTestnet: XLayerTestnet,
5942
6076
  ZKSyncEra: ZKSyncEra,
5943
6077
  ZKSyncEraSepolia: ZKSyncEraSepolia
5944
6078
  });
@@ -7382,6 +7516,7 @@ const swapTokenEnumSchema = z.enum([
7382
7516
  [Blockchain.Unichain]: '0x078D782b760474a361dDA0AF3839290b0EF57AD6',
7383
7517
  [Blockchain.World_Chain]: '0x79A02482A880bCE3F13e09Da970dC34db4CD24d1',
7384
7518
  [Blockchain.XDC]: '0xfA2958CB79b0491CC627c1557F441eF849Ca8eb1',
7519
+ [Blockchain.X_Layer]: '0xB6CEceAB302E2E4948951eE7843FC24E92933061',
7385
7520
  [Blockchain.ZKSync_Era]: '0x1d17CBcF0D6D143135aE902365D2E5e2A16538D4',
7386
7521
  // =========================================================================
7387
7522
  // Testnets (alphabetically sorted)
@@ -7416,6 +7551,7 @@ const swapTokenEnumSchema = z.enum([
7416
7551
  [Blockchain.Unichain_Sepolia]: '0x31d0220469e10c4E71834a79b1f276d740d3768F',
7417
7552
  [Blockchain.World_Chain_Sepolia]: '0x66145f38cBAC35Ca6F1Dfb4914dF98F1614aeA88',
7418
7553
  [Blockchain.XDC_Apothem]: '0xb5AB69F7bBada22B28e79C8FFAECe55eF1c771D4',
7554
+ [Blockchain.X_Layer_Testnet]: '0xDec90b78111Ba2fc6FC6d84d8B9ec159A2d4b9B3',
7419
7555
  [Blockchain.ZKSync_Sepolia]: '0xAe045DE5638162fa134807Cb558E15A3F5A7F853'
7420
7556
  }
7421
7557
  };
@@ -8129,6 +8265,52 @@ const swapTokenEnumSchema = z.enum([
8129
8265
  return explorerUrl;
8130
8266
  }
8131
8267
 
8268
+ /**
8269
+ * Assert that a value has type `never` (exhaustive switch helper).
8270
+ *
8271
+ * @remarks
8272
+ * Use in the `default` branch of a switch over a discriminated union.
8273
+ * If all union members are handled, the default is unreachable and TypeScript
8274
+ * narrows the parameter to `never`. If a member is missed, the compiler errors.
8275
+ *
8276
+ * @param _x - The value (typed as `never` when switch is exhaustive).
8277
+ * @returns Never returns; always throws.
8278
+ * @throws Error when the switch is not exhaustive.
8279
+ *
8280
+ * @example
8281
+ * ```typescript
8282
+ * type Foo = { type: 'a'; x: number } | { type: 'b'; y: string }
8283
+ *
8284
+ * function handle(foo: Foo): string {
8285
+ * switch (foo.type) {
8286
+ * case 'a': return String(foo.x)
8287
+ * case 'b': return foo.y
8288
+ * default: return assertNever(foo)
8289
+ * }
8290
+ * }
8291
+ * ```
8292
+ */ function assertNever$2(x) {
8293
+ // Plain `String(x)` collapses non-primitive union members (objects, arrays)
8294
+ // to `'[object Object]'`, which is useless when triaging which discriminant
8295
+ // was missed. Attempt `JSON.stringify` first so the thrown message preserves
8296
+ // the offending shape. Fall back to a minimal `typeof`-based label if
8297
+ // serialization fails (`BigInt` member, circular references, host objects).
8298
+ //
8299
+ // `x` is statically typed as `never` (the whole point of this helper), but
8300
+ // at runtime callers may still pass an unexpected value when the switch is
8301
+ // not actually exhaustive — that's exactly the bug we want to surface. Cast
8302
+ // through `unknown` so the runtime defence is not stripped by the compiler.
8303
+ const value = x;
8304
+ let stringified;
8305
+ try {
8306
+ const json = JSON.stringify(value);
8307
+ stringified = typeof json === 'string' ? json : `<${typeof value}>`;
8308
+ } catch {
8309
+ stringified = `<unstringifiable ${typeof value}>`;
8310
+ }
8311
+ throw new Error(`Unhandled switch case: ${stringified}`);
8312
+ }
8313
+
8132
8314
  /**
8133
8315
  * CCTP forwarding magic bytes prefix.
8134
8316
  *
@@ -8511,7 +8693,7 @@ const swapTokenEnumSchema = z.enum([
8511
8693
  }
8512
8694
 
8513
8695
  var name$3 = "@circle-fin/bridge-kit";
8514
- var version$3 = "1.12.2";
8696
+ var version$3 = "1.13.0";
8515
8697
  var pkg$3 = {
8516
8698
  name: name$3,
8517
8699
  version: version$3};
@@ -8547,13 +8729,21 @@ var pkg$3 = {
8547
8729
  computeFee: z.function().returns(z.string().or(z.promise(z.string()))).optional(),
8548
8730
  calculateFee: z.function().returns(z.string().or(z.promise(z.string()))).optional(),
8549
8731
  resolveFeeRecipientAddress: z.function().returns(z.string().or(z.promise(z.string())))
8550
- }).strict().refine((data)=>{
8732
+ }).strict().superRefine((data, ctx)=>{
8551
8733
  const hasComputeFee = data.computeFee !== undefined;
8552
8734
  const hasCalculateFee = data.calculateFee !== undefined;
8553
- // XOR: exactly one must be provided
8554
- return hasComputeFee !== hasCalculateFee;
8555
- }, {
8556
- message: 'Provide either computeFee or calculateFee, not both. Use computeFee (recommended) for human-readable amounts.'
8735
+ if (hasComputeFee && hasCalculateFee) {
8736
+ ctx.addIssue({
8737
+ code: z.ZodIssueCode.custom,
8738
+ message: 'Provide either computeFee or calculateFee, not both. Use computeFee (recommended) for human-readable amounts.'
8739
+ });
8740
+ }
8741
+ if (!hasComputeFee && !hasCalculateFee) {
8742
+ ctx.addIssue({
8743
+ code: z.ZodIssueCode.custom,
8744
+ message: 'Provide either computeFee or calculateFee. Use computeFee (recommended) for human-readable amounts.'
8745
+ });
8746
+ }
8557
8747
  });
8558
8748
 
8559
8749
  /**
@@ -9379,7 +9569,7 @@ var TransferSpeed;
9379
9569
  registerKit(`${pkg$3.name}/${pkg$3.version}`);
9380
9570
 
9381
9571
  var name$2 = "@circle-fin/swap-kit";
9382
- var version$2 = "1.5.0";
9572
+ var version$2 = "1.5.1";
9383
9573
  var pkg$2 = {
9384
9574
  name: name$2,
9385
9575
  version: version$2};
@@ -10175,6 +10365,311 @@ getQuoteRequestBaseSchema.superRefine(requireCrossChainQuoteToAddress);
10175
10365
  return apiKeyPattern.test(apiKey);
10176
10366
  };
10177
10367
 
10368
+ /**
10369
+ * IAdapter contract ABI.
10370
+ *
10371
+ * Shared ABI for the on-chain Adapter contract used by multiple kits
10372
+ * (swap, earn) for executing signed instruction sets. The `execute()`
10373
+ * function accepts EIP-712 signed execution parameters, token inputs,
10374
+ * and a signature, then executes the corresponding on-chain
10375
+ * instructions.
10376
+ */ const adapterContractAbi = [
10377
+ {
10378
+ type: 'function',
10379
+ name: 'execute',
10380
+ inputs: [
10381
+ {
10382
+ name: 'params',
10383
+ type: 'tuple',
10384
+ internalType: 'struct IAdapter.ExecutionParams',
10385
+ components: [
10386
+ {
10387
+ name: 'instructions',
10388
+ type: 'tuple[]',
10389
+ internalType: 'struct IAdapter.Instruction[]',
10390
+ components: [
10391
+ {
10392
+ name: 'target',
10393
+ type: 'address',
10394
+ internalType: 'address'
10395
+ },
10396
+ {
10397
+ name: 'data',
10398
+ type: 'bytes',
10399
+ internalType: 'bytes'
10400
+ },
10401
+ {
10402
+ name: 'value',
10403
+ type: 'uint256',
10404
+ internalType: 'uint256'
10405
+ },
10406
+ {
10407
+ name: 'tokenIn',
10408
+ type: 'address',
10409
+ internalType: 'address'
10410
+ },
10411
+ {
10412
+ name: 'amountToApprove',
10413
+ type: 'uint256',
10414
+ internalType: 'uint256'
10415
+ },
10416
+ {
10417
+ name: 'tokenOut',
10418
+ type: 'address',
10419
+ internalType: 'address'
10420
+ },
10421
+ {
10422
+ name: 'minTokenOut',
10423
+ type: 'uint256',
10424
+ internalType: 'uint256'
10425
+ }
10426
+ ]
10427
+ },
10428
+ {
10429
+ name: 'tokens',
10430
+ type: 'tuple[]',
10431
+ internalType: 'struct IAdapter.TokenRecipient[]',
10432
+ components: [
10433
+ {
10434
+ name: 'token',
10435
+ type: 'address',
10436
+ internalType: 'address'
10437
+ },
10438
+ {
10439
+ name: 'beneficiary',
10440
+ type: 'address',
10441
+ internalType: 'address'
10442
+ }
10443
+ ]
10444
+ },
10445
+ {
10446
+ name: 'execId',
10447
+ type: 'uint256',
10448
+ internalType: 'uint256'
10449
+ },
10450
+ {
10451
+ name: 'deadline',
10452
+ type: 'uint256',
10453
+ internalType: 'uint256'
10454
+ },
10455
+ {
10456
+ name: 'metadata',
10457
+ type: 'bytes',
10458
+ internalType: 'bytes'
10459
+ }
10460
+ ]
10461
+ },
10462
+ {
10463
+ name: 'tokenInputs',
10464
+ type: 'tuple[]',
10465
+ internalType: 'struct IAdapter.TokenInput[]',
10466
+ components: [
10467
+ {
10468
+ name: 'permitType',
10469
+ type: 'uint8',
10470
+ internalType: 'enum IAdapter.PermitType'
10471
+ },
10472
+ {
10473
+ name: 'token',
10474
+ type: 'address',
10475
+ internalType: 'address'
10476
+ },
10477
+ {
10478
+ name: 'amount',
10479
+ type: 'uint256',
10480
+ internalType: 'uint256'
10481
+ },
10482
+ {
10483
+ name: 'permitCalldata',
10484
+ type: 'bytes',
10485
+ internalType: 'bytes'
10486
+ }
10487
+ ]
10488
+ },
10489
+ {
10490
+ name: 'signature',
10491
+ type: 'bytes',
10492
+ internalType: 'bytes'
10493
+ }
10494
+ ],
10495
+ outputs: [],
10496
+ stateMutability: 'payable'
10497
+ }
10498
+ ];
10499
+
10500
+ /**
10501
+ * Minimal ERC-4626 tokenized-vault ABI.
10502
+ *
10503
+ * Covers only the mutating methods EarnKit bundles as inner instructions inside
10504
+ * an Adapter `execute()` call: `deposit`, `withdraw`, and `redeem`. It exists so
10505
+ * clients can decode the inner instruction calldata into a human-readable
10506
+ * summary of what a signer is authorizing (asset amount, receiver, owner)
10507
+ * rather than showing opaque bytes. The 4-byte selectors match the calldata the
10508
+ * earn service signs (`deposit(uint256,address)` = `0x6e553f65`,
10509
+ * `withdraw(uint256,address,address)` = `0xb460af94`,
10510
+ * `redeem(uint256,address,address)` = `0xba087652`).
10511
+ */ const erc4626VaultAbi = [
10512
+ {
10513
+ type: 'function',
10514
+ name: 'deposit',
10515
+ stateMutability: 'nonpayable',
10516
+ inputs: [
10517
+ {
10518
+ name: 'assets',
10519
+ type: 'uint256',
10520
+ internalType: 'uint256'
10521
+ },
10522
+ {
10523
+ name: 'receiver',
10524
+ type: 'address',
10525
+ internalType: 'address'
10526
+ }
10527
+ ],
10528
+ outputs: [
10529
+ {
10530
+ name: 'shares',
10531
+ type: 'uint256',
10532
+ internalType: 'uint256'
10533
+ }
10534
+ ]
10535
+ },
10536
+ {
10537
+ type: 'function',
10538
+ name: 'withdraw',
10539
+ stateMutability: 'nonpayable',
10540
+ inputs: [
10541
+ {
10542
+ name: 'assets',
10543
+ type: 'uint256',
10544
+ internalType: 'uint256'
10545
+ },
10546
+ {
10547
+ name: 'receiver',
10548
+ type: 'address',
10549
+ internalType: 'address'
10550
+ },
10551
+ {
10552
+ name: 'owner',
10553
+ type: 'address',
10554
+ internalType: 'address'
10555
+ }
10556
+ ],
10557
+ outputs: [
10558
+ {
10559
+ name: 'shares',
10560
+ type: 'uint256',
10561
+ internalType: 'uint256'
10562
+ }
10563
+ ]
10564
+ },
10565
+ {
10566
+ type: 'function',
10567
+ name: 'redeem',
10568
+ stateMutability: 'nonpayable',
10569
+ inputs: [
10570
+ {
10571
+ name: 'shares',
10572
+ type: 'uint256',
10573
+ internalType: 'uint256'
10574
+ },
10575
+ {
10576
+ name: 'receiver',
10577
+ type: 'address',
10578
+ internalType: 'address'
10579
+ },
10580
+ {
10581
+ name: 'owner',
10582
+ type: 'address',
10583
+ internalType: 'address'
10584
+ }
10585
+ ],
10586
+ outputs: [
10587
+ {
10588
+ name: 'assets',
10589
+ type: 'uint256',
10590
+ internalType: 'uint256'
10591
+ }
10592
+ ]
10593
+ }
10594
+ ];
10595
+
10596
+ /**
10597
+ * Minimal FeeTaker ABI.
10598
+ *
10599
+ * The earn service appends a `takeFeeERC20` instruction to withdraw bundles
10600
+ * when Circle charges a withdrawal fee. This ABI decodes that inner instruction
10601
+ * so the fee (token, beneficiary, amount) is visible in the signing summary
10602
+ * instead of appearing as opaque calldata alongside the redeem/withdraw call.
10603
+ */ const feeTakerAbi = [
10604
+ {
10605
+ type: 'function',
10606
+ name: 'takeFeeERC20',
10607
+ stateMutability: 'nonpayable',
10608
+ inputs: [
10609
+ {
10610
+ name: 'token',
10611
+ type: 'address',
10612
+ internalType: 'address'
10613
+ },
10614
+ {
10615
+ name: 'beneficiary',
10616
+ type: 'address',
10617
+ internalType: 'address'
10618
+ },
10619
+ {
10620
+ name: 'fee',
10621
+ type: 'uint256',
10622
+ internalType: 'uint256'
10623
+ },
10624
+ {
10625
+ name: 'kitType',
10626
+ type: 'bytes8',
10627
+ internalType: 'bytes8'
10628
+ }
10629
+ ],
10630
+ outputs: []
10631
+ }
10632
+ ];
10633
+
10634
+ /**
10635
+ * Minimal Merkl Distributor ABI.
10636
+ *
10637
+ * EarnKit claim-rewards bundles a single `claim` instruction targeting the
10638
+ * Merkl Distributor, batching one entry per reward token. This ABI decodes that
10639
+ * inner instruction so the claimed tokens and amounts are visible in the signing
10640
+ * summary. `claim` uses dynamic array arguments, which is why a real ABI decoder
10641
+ * (rather than fixed-word slicing) is required for the reward instruction.
10642
+ */ const merklDistributorAbi = [
10643
+ {
10644
+ type: 'function',
10645
+ name: 'claim',
10646
+ stateMutability: 'nonpayable',
10647
+ inputs: [
10648
+ {
10649
+ name: 'users',
10650
+ type: 'address[]',
10651
+ internalType: 'address[]'
10652
+ },
10653
+ {
10654
+ name: 'tokens',
10655
+ type: 'address[]',
10656
+ internalType: 'address[]'
10657
+ },
10658
+ {
10659
+ name: 'amounts',
10660
+ type: 'uint256[]',
10661
+ internalType: 'uint256[]'
10662
+ },
10663
+ {
10664
+ name: 'proofs',
10665
+ type: 'bytes32[][]',
10666
+ internalType: 'bytes32[][]'
10667
+ }
10668
+ ],
10669
+ outputs: []
10670
+ }
10671
+ ];
10672
+
10178
10673
  /**
10179
10674
  * Zod schema for validating EVM adapter capabilities.
10180
10675
  *
@@ -12688,7 +13183,7 @@ new Set(Object.values(Blockchain));
12688
13183
  registerKit(`${pkg$2.name}/${pkg$2.version}`);
12689
13184
 
12690
13185
  var name$1 = "@circle-fin/earn-kit";
12691
- var version$1 = "1.4.0";
13186
+ var version$1 = "1.5.0";
12692
13187
  var pkg$1 = {
12693
13188
  name: name$1,
12694
13189
  version: version$1};
@@ -13332,78 +13827,1010 @@ const GAS_SAFETY_MULTIPLIER_DENOMINATOR = 10n;
13332
13827
  }
13333
13828
 
13334
13829
  /**
13335
- * Prepare an earn adapter action, execute it, wait for confirmation, and
13336
- * throw a structured revert error if the receipt status is `'reverted'`.
13337
- *
13338
- * Wraps the prepareAction, execute, waitForTransaction, and status check
13339
- * sequence so the provider can dispatch any `earn.*` action key with
13340
- * consistent revert handling.
13341
- *
13342
- * Gas estimation: after preparing the action the helper calls
13343
- * {@link estimateBufferedGasLimit}, which applies a safety buffer to the
13344
- * returned gas value. If estimation fails, execution falls through to the
13345
- * adapter's default gas handling.
13346
- *
13347
- * @typeParam TActionKey - Earn action key being executed.
13348
- * @param params - Adapter action, execution context, and revert message.
13349
- * @returns The confirmed on-chain transaction hash and explorer URL.
13350
- * @throws {@link KitError} If the transaction reverts on-chain.
13351
- *
13352
- * @example
13353
- * ```typescript
13354
- * const { txHash, explorerUrl } = await executeEarnAction({
13355
- * adapter,
13356
- * chain,
13357
- * address,
13358
- * actionKey: 'earn.deposit',
13359
- * actionParams: { executeParams, tokenInputs, signature },
13360
- * revertMessage: 'Earn deposit reverted on-chain',
13361
- * })
13362
- * ```
13363
- *
13364
- * @internal
13365
- */ async function executeEarnAction(params) {
13366
- const { adapter, chain, address, actionKey, actionParams, revertMessage } = params;
13367
- const prepared = await adapter.prepareAction(actionKey, actionParams, {
13368
- chain,
13369
- address
13370
- });
13371
- const gasLimitOverride = await estimateBufferedGasLimit(prepared);
13372
- const txHash = prepared.type === 'evm' && gasLimitOverride !== undefined ? await prepared.execute({
13373
- gasLimit: gasLimitOverride
13374
- }) : await prepared.execute();
13375
- const explorerUrl = buildExplorerUrl(chain, txHash);
13376
- const receipt = await adapter.waitForTransaction(txHash, {
13377
- confirmations: 1
13378
- }, chain);
13379
- if (receipt.status === 'reverted') {
13380
- throw createTransactionRevertedError(chain.name, revertMessage, undefined, txHash, explorerUrl);
13830
+ * Combined ABI of every inner instruction EarnKit can bundle inside an Adapter
13831
+ * `execute()` call. `decodeFunctionData` matches an instruction's calldata to
13832
+ * one of these functions by its 4-byte selector.
13833
+ */ const earnInstructionAbi = [
13834
+ ...erc4626VaultAbi,
13835
+ ...feeTakerAbi,
13836
+ ...merklDistributorAbi
13837
+ ];
13838
+ /**
13839
+ * Extract and shallow-validate the `instructions` array from loosely-typed
13840
+ * signed execution params.
13841
+ *
13842
+ * The earn service schema validates `tokenIn`/`amountToApprove` and passes the
13843
+ * remaining instruction fields through untyped, so the params arrive as a plain
13844
+ * record; each accessed field is narrowed at runtime.
13845
+ */ function requireInstructions(executionParams) {
13846
+ const instructions = executionParams['instructions'];
13847
+ if (!Array.isArray(instructions)) {
13848
+ throw decodeMismatchError('execution params are missing an instructions array', {
13849
+ instructions
13850
+ });
13381
13851
  }
13382
- return {
13383
- txHash,
13384
- explorerUrl,
13385
- ...receipt.gasUsed !== undefined && {
13386
- gasUsed: receipt.gasUsed
13387
- },
13388
- ...receipt.effectiveGasPrice !== undefined && {
13389
- effectiveGasPrice: receipt.effectiveGasPrice
13852
+ return instructions.map((instruction, index)=>{
13853
+ if (typeof instruction !== 'object' || instruction === null) {
13854
+ throw decodeMismatchError(`instructions[${index.toString()}] is not an object`, {
13855
+ index
13856
+ });
13390
13857
  }
13391
- };
13858
+ return instruction;
13859
+ });
13392
13860
  }
13393
-
13394
13861
  /**
13395
- * Validate that a service-signed execution payload has not expired before
13396
- * the SDK asks the wallet to broadcast a transaction.
13862
+ * Build a fail-closed {@link KitError} for an earn decode or review failure.
13397
13863
  *
13398
- * @internal
13399
- */ function validateExecutionDeadline(executionParams) {
13400
- const deadline = BigInt(executionParams.deadline);
13401
- const now = BigInt(Math.floor(Date.now() / 1000));
13402
- if (deadline <= now) {
13403
- throw createValidationFailedError('executionParams.deadline', executionParams.deadline, 'Earn execution deadline has expired');
13404
- }
13405
- }
13406
-
13864
+ * Marked non-recoverable: a mismatch between what would be shown and what would
13865
+ * be signed is never safe to retry, so the operation fails fast rather than
13866
+ * presenting misleading decoded data. `messagePrefix` names the failing stage
13867
+ * (calldata decode vs. review construction); callers bind it once and pass the
13868
+ * specific failure as `message`.
13869
+ */ function failClosedEarnError(messagePrefix, message, trace) {
13870
+ return new KitError({
13871
+ ...EarnError.INTERNAL_ERROR,
13872
+ recoverability: 'FATAL',
13873
+ message: `${messagePrefix}: ${message}`,
13874
+ cause: {
13875
+ trace
13876
+ }
13877
+ });
13878
+ }
13879
+ /**
13880
+ * Build a {@link KitError} for a decode or consistency failure.
13881
+ *
13882
+ * Thin wrapper over {@link failClosedEarnError} bound to the decode-stage
13883
+ * message prefix.
13884
+ */ function decodeMismatchError(message, trace) {
13885
+ return failClosedEarnError('Unable to decode earn transaction', message, trace);
13886
+ }
13887
+ /**
13888
+ * Narrow an untyped value to a 0x-prefixed hex string, or fail fast.
13889
+ */ function requireHex(value, path) {
13890
+ if (typeof value === 'string' && /^0x[0-9a-fA-F]*$/.test(value)) {
13891
+ return value;
13892
+ }
13893
+ throw decodeMismatchError(`${path} is not a hex string`, {
13894
+ path,
13895
+ value
13896
+ });
13897
+ }
13898
+ /**
13899
+ * Narrow an untyped value to a 20-byte EVM address, or fail fast.
13900
+ */ function requireAddress(value, path) {
13901
+ if (typeof value === 'string' && /^0x[0-9a-fA-F]{40}$/.test(value)) {
13902
+ return value;
13903
+ }
13904
+ throw decodeMismatchError(`${path} is not an address`, {
13905
+ path,
13906
+ value
13907
+ });
13908
+ }
13909
+ /**
13910
+ * Narrow an untyped `uint256`-like value (decimal string, bigint, or integer)
13911
+ * to a bigint, or fail fast.
13912
+ */ function requireUint(value, path) {
13913
+ if (typeof value === 'bigint') {
13914
+ return value;
13915
+ }
13916
+ if (typeof value === 'string' && /^\d+$/.test(value)) {
13917
+ return BigInt(value);
13918
+ }
13919
+ if (typeof value === 'number' && Number.isInteger(value) && value >= 0) {
13920
+ return BigInt(value);
13921
+ }
13922
+ throw decodeMismatchError(`${path} is not a uint256 value`, {
13923
+ path,
13924
+ value
13925
+ });
13926
+ }
13927
+ /**
13928
+ * Decode inner instruction calldata against the earn instruction ABI, mapping a
13929
+ * viem decode failure (unknown selector, malformed args) to a fail-fast error.
13930
+ */ function decodeEarnInstructionData(data, index) {
13931
+ try {
13932
+ return decodeFunctionData({
13933
+ abi: earnInstructionAbi,
13934
+ data
13935
+ });
13936
+ } catch (error) {
13937
+ throw decodeMismatchError(`instructions[${index.toString()}] calldata is not a recognized earn instruction`, {
13938
+ index,
13939
+ selector: data.slice(0, 10),
13940
+ error: String(error)
13941
+ });
13942
+ }
13943
+ }
13944
+ /**
13945
+ * Decode Adapter `execute()` calldata, mapping a viem decode failure to a
13946
+ * fail-fast error.
13947
+ */ function decodeExecuteCalldata(calldata) {
13948
+ try {
13949
+ return decodeFunctionData({
13950
+ abi: adapterContractAbi,
13951
+ data: calldata
13952
+ });
13953
+ } catch (error) {
13954
+ throw decodeMismatchError('encoded calldata is not a valid Adapter execute() call', {
13955
+ error: String(error)
13956
+ });
13957
+ }
13958
+ }
13959
+ /**
13960
+ * Decode one inner instruction's calldata into a typed {@link
13961
+ * DecodedEarnInstruction}.
13962
+ */ function decodeInstruction(instruction, index) {
13963
+ const target = requireAddress(instruction['target'], `instructions[${index.toString()}].target`);
13964
+ const data = requireHex(instruction['data'], `instructions[${index.toString()}].data`);
13965
+ const decoded = decodeEarnInstructionData(data, index);
13966
+ switch(decoded.functionName){
13967
+ case 'deposit':
13968
+ {
13969
+ const [assets, receiver] = decoded.args;
13970
+ return {
13971
+ method: 'deposit',
13972
+ vault: target,
13973
+ assets: assets.toString(),
13974
+ receiver
13975
+ };
13976
+ }
13977
+ case 'withdraw':
13978
+ {
13979
+ const [assets, receiver, owner] = decoded.args;
13980
+ return {
13981
+ method: 'withdraw',
13982
+ vault: target,
13983
+ assets: assets.toString(),
13984
+ receiver,
13985
+ owner
13986
+ };
13987
+ }
13988
+ case 'redeem':
13989
+ {
13990
+ const [shares, receiver, owner] = decoded.args;
13991
+ return {
13992
+ method: 'redeem',
13993
+ vault: target,
13994
+ shares: shares.toString(),
13995
+ receiver,
13996
+ owner
13997
+ };
13998
+ }
13999
+ case 'takeFeeERC20':
14000
+ {
14001
+ const [token, beneficiary, fee, kitType] = decoded.args;
14002
+ return {
14003
+ method: 'takeFeeERC20',
14004
+ feeTaker: target,
14005
+ token,
14006
+ beneficiary,
14007
+ fee: fee.toString(),
14008
+ kitType
14009
+ };
14010
+ }
14011
+ case 'claim':
14012
+ {
14013
+ const users = decoded.args[0];
14014
+ const tokens = decoded.args[1];
14015
+ const amounts = decoded.args[2];
14016
+ // Merkl claim(users, tokens, amounts, proofs) carries parallel arrays,
14017
+ // one entry per reward. Reject any length skew rather than padding with
14018
+ // zero amounts or dropping trailing entries, so the preview can never
14019
+ // misstate what is claimed or for whom.
14020
+ //
14021
+ // Note: Merkl `amounts` are the *cumulative lifetime* total claimable per
14022
+ // (user, token); the Distributor transfers only `amount - alreadyClaimed`.
14023
+ // This decode faithfully surfaces the signed cumulative value, which is
14024
+ // what `DecodedRewardClaim.amount` documents. See that type's doc.
14025
+ if (new Set([
14026
+ users.length,
14027
+ tokens.length,
14028
+ amounts.length
14029
+ ]).size !== 1) {
14030
+ throw decodeMismatchError(`instructions[${index.toString()}] claim has mismatched recipient/token/amount lengths`, {
14031
+ index,
14032
+ users: users.length,
14033
+ tokens: tokens.length,
14034
+ amounts: amounts.length
14035
+ });
14036
+ }
14037
+ const rewards = tokens.map((token, rewardIndex)=>({
14038
+ recipient: requireAddress(users[rewardIndex], `instructions[${index.toString()}].claim.users[${rewardIndex.toString()}]`),
14039
+ address: token,
14040
+ amount: requireUint(amounts[rewardIndex], `instructions[${index.toString()}].claim.amounts[${rewardIndex.toString()}]`).toString()
14041
+ }));
14042
+ return {
14043
+ method: 'claim',
14044
+ distributor: target,
14045
+ rewards
14046
+ };
14047
+ }
14048
+ /* v8 ignore next 2 -- exhaustive switch; default is unreachable */ default:
14049
+ return assertNever$2(decoded);
14050
+ }
14051
+ }
14052
+ /**
14053
+ * Lift the primary values a wallet prompt cares about out of the decoded
14054
+ * instructions into a flat summary.
14055
+ */ function buildSummary(instructions, envelope) {
14056
+ const summary = {};
14057
+ instructions.forEach((instruction, index)=>{
14058
+ switch(instruction.method){
14059
+ case 'deposit':
14060
+ case 'withdraw':
14061
+ case 'redeem':
14062
+ {
14063
+ // The summary lifts a single primary token movement to the top level.
14064
+ // An earn bundle carries exactly one deposit/withdraw/redeem today;
14065
+ // fail fast rather than silently overwriting an earlier one, which
14066
+ // would drop it from the wallet-facing preview.
14067
+ if (summary.token !== undefined) {
14068
+ throw decodeMismatchError('multiple deposit/withdraw/redeem instructions cannot be summarized into a single preview', {
14069
+ index
14070
+ });
14071
+ }
14072
+ // Pair the amount with the token it is actually denominated in so the
14073
+ // preview never folds two units into one entry:
14074
+ // - deposit: `assets` of the underlying asset pulled in (`tokenIn`)
14075
+ // - redeem: `shares` of the vault-share token burned (`tokenIn`)
14076
+ // - withdraw: `assets` of the underlying asset paid out (`tokenOut`).
14077
+ // `withdraw(assets)` counts the underlying received, not the shares
14078
+ // burned to produce it, so `tokenIn` (the share token) would misstate
14079
+ // the unit; the underlying is the instruction's `tokenOut`.
14080
+ const amount = instruction.method === 'redeem' ? instruction.shares : instruction.assets;
14081
+ const tokenField = instruction.method === 'withdraw' ? 'tokenOut' : 'tokenIn';
14082
+ summary.vault = instruction.vault;
14083
+ summary.receiver = instruction.receiver;
14084
+ summary.token = {
14085
+ address: requireAddress(envelope[index]?.[tokenField], `instructions[${index.toString()}].${tokenField}`),
14086
+ amount
14087
+ };
14088
+ break;
14089
+ }
14090
+ case 'takeFeeERC20':
14091
+ {
14092
+ // As with the vault case, a second fee would silently overwrite the
14093
+ // first and understate what is charged; fail fast instead.
14094
+ if (summary.fee !== undefined) {
14095
+ throw decodeMismatchError('multiple fee instructions cannot be summarized into a single preview', {
14096
+ index
14097
+ });
14098
+ }
14099
+ summary.fee = {
14100
+ address: instruction.token,
14101
+ amount: instruction.fee
14102
+ };
14103
+ break;
14104
+ }
14105
+ case 'claim':
14106
+ {
14107
+ // A second claim would silently drop the first from the preview
14108
+ // (rewards are already batched inside one Merkl claim); fail fast.
14109
+ if (summary.rewards !== undefined) {
14110
+ throw decodeMismatchError('multiple claim instructions cannot be summarized into a single preview', {
14111
+ index
14112
+ });
14113
+ }
14114
+ summary.rewards = instruction.rewards;
14115
+ break;
14116
+ }
14117
+ /* v8 ignore next 2 -- exhaustive switch; default is unreachable */ default:
14118
+ assertNever$2(instruction);
14119
+ }
14120
+ });
14121
+ return summary;
14122
+ }
14123
+ /**
14124
+ * Vault/claim instruction methods each declared action may decode to. The
14125
+ * mapping is many-to-one: a full withdrawal decodes to `redeem`, and any action
14126
+ * may carry an auxiliary `takeFeeERC20` alongside its primary instruction.
14127
+ */ const ACTION_ALLOWED_METHODS = {
14128
+ deposit: new Set([
14129
+ 'deposit'
14130
+ ]),
14131
+ withdraw: new Set([
14132
+ 'withdraw',
14133
+ 'redeem'
14134
+ ]),
14135
+ claimRewards: new Set([
14136
+ 'claim'
14137
+ ])
14138
+ };
14139
+ /**
14140
+ * Fail fast when the caller-declared `action` disagrees with the decoded
14141
+ * instructions, so the preview's headline can never mislabel what is signed
14142
+ * (e.g. a `deposit`-labeled call handed withdraw params). `takeFeeERC20` is an
14143
+ * auxiliary Circle-fee instruction and is allowed alongside any action.
14144
+ */ function assertActionMatchesInstructions(action, instructions) {
14145
+ const allowed = ACTION_ALLOWED_METHODS[action];
14146
+ instructions.forEach((instruction, index)=>{
14147
+ if (instruction.method === 'takeFeeERC20') {
14148
+ return;
14149
+ }
14150
+ if (!allowed.has(instruction.method)) {
14151
+ throw decodeMismatchError(`decoded instruction method '${instruction.method}' does not match the '${action}' action`, {
14152
+ action,
14153
+ method: instruction.method,
14154
+ index
14155
+ });
14156
+ }
14157
+ });
14158
+ }
14159
+ /**
14160
+ * Decode a same-chain earn `execute()` bundle into a human-readable summary.
14161
+ *
14162
+ * Decodes every inner instruction in the service-signed `executionParams` — the
14163
+ * same object the SDK ABI-encodes into the transaction — so the returned decode
14164
+ * is a faithful, drift-free view of what the signer is authorizing: input token
14165
+ * and amount, target vault, receiver, any Circle fee, and claimed rewards. Fails
14166
+ * fast with a non-recoverable {@link KitError} if any instruction cannot be
14167
+ * decoded, rather than returning misleading data.
14168
+ *
14169
+ * @param input - Action, chain, adapter, and the signed execution params.
14170
+ * @returns The decoded transaction summary.
14171
+ * @throws {@link KitError} If an instruction's calldata cannot be decoded.
14172
+ *
14173
+ * @example
14174
+ * ```typescript
14175
+ * const decoded = decodeEarnExecute({
14176
+ * action: 'deposit',
14177
+ * chain: 'Arc_Testnet',
14178
+ * adapter: '0x7fb8c7260b63934d8da38af902f87ae6e284a845',
14179
+ * executionParams,
14180
+ * })
14181
+ * // decoded.summary -> { token: { address, amount }, vault, receiver }
14182
+ * ```
14183
+ *
14184
+ * @internal
14185
+ */ function decodeEarnExecute(input) {
14186
+ const { action, chain, adapter, executionParams } = input;
14187
+ const envelope = requireInstructions(executionParams);
14188
+ const instructions = envelope.map((instruction, index)=>decodeInstruction(instruction, index));
14189
+ assertActionMatchesInstructions(action, instructions);
14190
+ return {
14191
+ action,
14192
+ chain,
14193
+ adapter,
14194
+ instructions,
14195
+ summary: buildSummary(instructions, envelope)
14196
+ };
14197
+ }
14198
+ /**
14199
+ * Assert that ABI-encoded Adapter `execute()` calldata encodes the same
14200
+ * instruction set as the service-signed execution params.
14201
+ *
14202
+ * Fail-fast preview check: the SDK encodes `execute(executeParams, ...)` locally,
14203
+ * so decoding those final bytes and comparing every field of each instruction
14204
+ * against the signed params proves the previewed instruction set matches what
14205
+ * will be signed. It compares `instructions[]` only — the outer `tokens`,
14206
+ * `execId`, `deadline`, and `metadata` are not re-compared here. The
14207
+ * authoritative integrity guarantee for the full signed struct is the on-chain
14208
+ * EIP-712 signature verification, which reverts if any signed field is altered.
14209
+ *
14210
+ * @param calldata - Encoded `execute()` calldata about to be signed.
14211
+ * @param executionParams - Service-signed execution params.
14212
+ * @throws {@link KitError} If the calldata is not an `execute()` call or any
14213
+ * instruction field differs from the signed params.
14214
+ *
14215
+ * @example
14216
+ * ```typescript
14217
+ * assertEarnCalldataMatchesExecuteParams(
14218
+ * prepared.getCallData().data,
14219
+ * executionParams,
14220
+ * )
14221
+ * ```
14222
+ *
14223
+ * @internal
14224
+ */ function assertEarnCalldataMatchesExecuteParams(calldata, executionParams) {
14225
+ // adapterContractAbi declares only `execute`, so a successful decode is always
14226
+ // the execute() call; a non-execute selector throws inside
14227
+ // decodeExecuteCalldata above.
14228
+ const decoded = decodeExecuteCalldata(calldata);
14229
+ const encoded = decoded.args[0].instructions;
14230
+ const signed = requireInstructions(executionParams);
14231
+ // Compare each encoded instruction against its signed counterpart. Iterating
14232
+ // the encoded instructions and indexing the signed set keeps both mismatch
14233
+ // branches reachable: a signed set that is too short trips the guard below,
14234
+ // and one that is too long trips the post-loop check.
14235
+ encoded.forEach((instruction, index)=>{
14236
+ const signedInstruction = signed[index];
14237
+ if (signedInstruction === undefined) {
14238
+ throw decodeMismatchError(`signed params are missing instruction ${index.toString()}`, {
14239
+ index,
14240
+ encoded: encoded.length,
14241
+ signed: signed.length
14242
+ });
14243
+ }
14244
+ const path = `instructions[${index.toString()}]`;
14245
+ assertHexEqual(instruction.target, signedInstruction['target'], `${path}.target`);
14246
+ assertHexEqual(instruction.data, signedInstruction['data'], `${path}.data`);
14247
+ assertUintEqual(instruction.value, signedInstruction['value'], `${path}.value`);
14248
+ assertHexEqual(instruction.tokenIn, signedInstruction['tokenIn'], `${path}.tokenIn`);
14249
+ assertUintEqual(instruction.amountToApprove, signedInstruction['amountToApprove'], `${path}.amountToApprove`);
14250
+ assertHexEqual(instruction.tokenOut, signedInstruction['tokenOut'], `${path}.tokenOut`);
14251
+ assertUintEqual(instruction.minTokenOut, signedInstruction['minTokenOut'], `${path}.minTokenOut`);
14252
+ });
14253
+ if (signed.length > encoded.length) {
14254
+ throw decodeMismatchError('signed params contain more instructions than the encoded calldata', {
14255
+ encoded: encoded.length,
14256
+ signed: signed.length
14257
+ });
14258
+ }
14259
+ }
14260
+ /**
14261
+ * Assert two hex values are equal, case-insensitively (addresses and calldata).
14262
+ */ function assertHexEqual(encoded, signed, path) {
14263
+ const signedHex = requireHex(signed, path);
14264
+ if (encoded.toLowerCase() !== signedHex.toLowerCase()) {
14265
+ throw decodeMismatchError(`${path} differs from signed params`, {
14266
+ path,
14267
+ encoded,
14268
+ signed: signedHex
14269
+ });
14270
+ }
14271
+ }
14272
+ /**
14273
+ * Assert an encoded bigint equals a signed `uint256`-like value.
14274
+ */ function assertUintEqual(encoded, signed, path) {
14275
+ const signedUint = requireUint(signed, path);
14276
+ if (encoded !== signedUint) {
14277
+ throw decodeMismatchError(`${path} differs from signed params`, {
14278
+ path,
14279
+ encoded: encoded.toString(),
14280
+ signed: signedUint.toString()
14281
+ });
14282
+ }
14283
+ }
14284
+
14285
+ /**
14286
+ * Namespaced discriminator for the EarnKit authorization review.
14287
+ *
14288
+ * Applications match on this in an adapter `onBeforeAuthorize` hook to decide
14289
+ * whether the request carries EarnKit semantic data. Prefer the
14290
+ * {@link isEarnExecuteReview} type guard over comparing this string directly.
14291
+ *
14292
+ * @example
14293
+ * ```typescript
14294
+ * if (review?.kind === EARN_EXECUTE_REVIEW_KIND) { … }
14295
+ * ```
14296
+ */ const EARN_EXECUTE_REVIEW_KIND = 'earn.execute';
14297
+
14298
+ /**
14299
+ * Build a fail-closed {@link KitError} for a review-construction failure.
14300
+ *
14301
+ * Marked non-recoverable: a review that cannot prove the calldata matches the
14302
+ * signed operation must abort authorization, never retry with misleading data.
14303
+ */ function reviewError(message, trace) {
14304
+ return failClosedEarnError('Unable to build earn authorization review', message, trace);
14305
+ }
14306
+ /**
14307
+ * Narrow the canonical authorization payload to the single Adapter `execute()`
14308
+ * call a same-chain earn operation authorizes.
14309
+ *
14310
+ * Same-chain deposit, withdraw, and claim-rewards each authorize exactly one
14311
+ * `evm-calls` payload carrying one call. Anything else (typed data, a batch,
14312
+ * an empty call list) means this descriptor was attached to the wrong
14313
+ * authorization unit, so fail closed rather than decode misleading data.
14314
+ */ function assertSingleEvmCallPayload(payload) {
14315
+ if (payload.type !== 'evm-calls') {
14316
+ throw reviewError(`expected an 'evm-calls' payload but received '${payload.type}'`, {
14317
+ type: payload.type
14318
+ });
14319
+ }
14320
+ const [call, ...rest] = payload.calls;
14321
+ if (call === undefined) {
14322
+ throw reviewError('the evm-calls payload contains no calls to review', {
14323
+ callCount: payload.calls.length
14324
+ });
14325
+ }
14326
+ if (rest.length > 0) {
14327
+ throw reviewError('a same-chain earn operation authorizes exactly one Adapter execute() call', {
14328
+ callCount: payload.calls.length
14329
+ });
14330
+ }
14331
+ return call;
14332
+ }
14333
+ /**
14334
+ * Select the final earn `execute()` call from an atomic Earn batch.
14335
+ *
14336
+ * Same-chain batched deposit/withdraw authorizes either `[execute]` when the
14337
+ * current allowance is sufficient, or `[approve, execute]` when a top-up is
14338
+ * required. Any other shape means the descriptor was attached to an
14339
+ * unexpected authorization unit, so fail closed.
14340
+ */ function assertBatchedEarnExecuteCall(payload) {
14341
+ if (payload.type !== 'evm-calls') {
14342
+ throw reviewError(`expected an 'evm-calls' payload but received '${payload.type}'`, {
14343
+ type: payload.type
14344
+ });
14345
+ }
14346
+ if (payload.calls.length !== 1 && payload.calls.length !== 2) {
14347
+ throw reviewError('a batched earn operation authorizes [execute] or [approve, execute]', {
14348
+ callCount: payload.calls.length
14349
+ });
14350
+ }
14351
+ const executeCall = payload.calls.at(-1);
14352
+ if (executeCall === undefined) {
14353
+ throw reviewError('the earn batch contains no execute call to review', {
14354
+ callCount: payload.calls.length
14355
+ });
14356
+ }
14357
+ return executeCall;
14358
+ }
14359
+ /**
14360
+ * Map a canonical {@link EvmCall} to the {@link EarnEncodedTransaction} preview
14361
+ * shape, failing closed when the earn `execute()` call carries no calldata.
14362
+ */ function toEarnEncodedTransaction(call) {
14363
+ if (call.data === undefined) {
14364
+ throw reviewError('the earn execute() call is missing calldata', {
14365
+ to: call.to
14366
+ });
14367
+ }
14368
+ return {
14369
+ to: call.to,
14370
+ data: call.data,
14371
+ ...call.value !== undefined && {
14372
+ value: call.value
14373
+ }
14374
+ };
14375
+ }
14376
+ /**
14377
+ * Create an Earn authorization descriptor using the supplied canonical-payload
14378
+ * call selector.
14379
+ *
14380
+ * @param input - The action, chain, and service-signed execution params.
14381
+ * @param selectCall - Fail-closed selector for the execute call under review.
14382
+ * @returns A lazy descriptor that decodes and verifies the selected call.
14383
+ *
14384
+ * @internal
14385
+ */ function createEarnExecuteDescriptor(input, selectCall) {
14386
+ const { action, chain, executionParams } = input;
14387
+ const createReview = (payload)=>{
14388
+ const call = selectCall(payload);
14389
+ const encoded = toEarnEncodedTransaction(call);
14390
+ const decoded = decodeEarnExecute({
14391
+ action,
14392
+ chain,
14393
+ adapter: encoded.to,
14394
+ executionParams
14395
+ });
14396
+ // Prove the calldata about to be signed encodes the same instruction set as
14397
+ // the service-signed params. Throwing here aborts before the wallet prompt.
14398
+ assertEarnCalldataMatchesExecuteParams(encoded.data, executionParams);
14399
+ const review = {
14400
+ kind: EARN_EXECUTE_REVIEW_KIND,
14401
+ data: {
14402
+ encoded,
14403
+ decoded
14404
+ }
14405
+ };
14406
+ return review;
14407
+ };
14408
+ return {
14409
+ createReview
14410
+ };
14411
+ }
14412
+ /**
14413
+ * Build the lazy `earn.execute` authorization descriptor for a same-chain earn
14414
+ * action.
14415
+ *
14416
+ * The returned descriptor carries only a `createReview` factory — no intent
14417
+ * override, because the adapter's action system supplies the intent from the
14418
+ * action key. The factory is evaluated at most once, and only when the
14419
+ * application configured an adapter `onBeforeAuthorize` hook. When it runs it:
14420
+ *
14421
+ * 1. narrows the canonical payload to its single Adapter `execute()` call;
14422
+ * 2. lifts that call into an {@link EarnEncodedTransaction};
14423
+ * 3. decodes it into a `DecodedEarnTx`; and
14424
+ * 4. asserts the decoded calldata matches the service-signed params, throwing
14425
+ * (aborting authorization before the wallet or signer) on any mismatch.
14426
+ *
14427
+ * @param input - The action, chain, and service-signed execution params.
14428
+ * @returns An authorization descriptor to pass as the fourth `prepareAction`
14429
+ * argument for the final earn action only (never the allowance approval).
14430
+ * @throws {@link KitError} From the review factory when the payload is not a
14431
+ * single earn `execute()` call or the calldata diverges from the signed
14432
+ * params. The throw surfaces through the adapter gate before authorization.
14433
+ *
14434
+ * @example
14435
+ * ```typescript
14436
+ * const descriptor = buildEarnExecuteDescriptor({
14437
+ * action: 'deposit',
14438
+ * chain: 'Arc_Testnet',
14439
+ * executionParams,
14440
+ * })
14441
+ * await adapter.prepareAction('earn.deposit', actionParams, ctx, {
14442
+ * authorization: descriptor,
14443
+ * })
14444
+ * ```
14445
+ *
14446
+ * @internal
14447
+ */ function buildEarnExecuteDescriptor(input) {
14448
+ return createEarnExecuteDescriptor(input, assertSingleEvmCallPayload);
14449
+ }
14450
+ /**
14451
+ * Build a lazy `earn.execute` authorization descriptor for an atomic Earn
14452
+ * batch containing either `[execute]` or `[approve, execute]`.
14453
+ *
14454
+ * The review always decodes and verifies the final call against the
14455
+ * service-signed execution params. Unexpected payload types and call counts
14456
+ * fail closed before wallet authorization.
14457
+ *
14458
+ * @param input - The action, chain, and service-signed execution params.
14459
+ * @returns A descriptor suitable for `batchExecute` authorization options.
14460
+ * @throws {@link KitError} From the lazy review factory when the batch shape or
14461
+ * final execute calldata cannot be verified.
14462
+ *
14463
+ * @internal
14464
+ */ function buildBatchedEarnExecuteDescriptor(input) {
14465
+ return createEarnExecuteDescriptor(input, assertBatchedEarnExecuteCall);
14466
+ }
14467
+
14468
+ /**
14469
+ * Prepare an earn adapter action, execute it, wait for confirmation, and
14470
+ * throw a structured revert error if the receipt status is `'reverted'`.
14471
+ *
14472
+ * Wraps the prepareAction, execute, waitForTransaction, and status check
14473
+ * sequence so the provider can dispatch any `earn.*` action key with
14474
+ * consistent revert handling.
14475
+ *
14476
+ * Gas estimation: after preparing the action the helper calls
14477
+ * {@link estimateBufferedGasLimit}, which applies a safety buffer to the
14478
+ * returned gas value. If estimation fails, execution falls through to the
14479
+ * adapter's default gas handling.
14480
+ *
14481
+ * @typeParam TActionKey - Earn action key being executed.
14482
+ * @param params - Adapter action, execution context, and revert message.
14483
+ * @returns The confirmed on-chain transaction hash and explorer URL.
14484
+ * @throws {@link KitError} If the transaction reverts on-chain.
14485
+ *
14486
+ * @example
14487
+ * ```typescript
14488
+ * const { txHash, explorerUrl } = await executeEarnAction({
14489
+ * adapter,
14490
+ * chain,
14491
+ * address,
14492
+ * actionKey: 'earn.deposit',
14493
+ * actionParams: { executeParams, tokenInputs, signature },
14494
+ * action: 'deposit',
14495
+ * executionParams,
14496
+ * revertMessage: 'Earn deposit reverted on-chain',
14497
+ * })
14498
+ * ```
14499
+ *
14500
+ * @internal
14501
+ */ async function executeEarnAction(params) {
14502
+ const { adapter, chain, address, actionKey, actionParams, action, executionParams, revertMessage } = params;
14503
+ // Attach the lazy `earn.execute` review to the final earn action only (never
14504
+ // the allowance approval, which runs on a separate path). The adapter's
14505
+ // action system supplies the intent from `actionKey`, so the descriptor
14506
+ // carries only the review factory. The factory is evaluated at most once,
14507
+ // and only when the application configured an `onBeforeAuthorize` hook.
14508
+ const authorization = buildEarnExecuteDescriptor({
14509
+ action,
14510
+ // The provider validates the chain is Earn-supported in
14511
+ // `resolveAdapterContext` before reaching execute, so the concrete chain
14512
+ // identifier is a valid `EarnChainIdentifier`. It is carried through to the
14513
+ // decoded preview's display `chain` field only.
14514
+ chain: chain.chain,
14515
+ executionParams
14516
+ });
14517
+ // The abstract `Adapter.prepareAction` is 3-arg; the fourth authorization
14518
+ // argument lives on the `withLegacyCompat` wrapper that produced the concrete
14519
+ // adapter passed here. Narrow the single seam that threads the descriptor.
14520
+ const prepared = await adapter.prepareAction(actionKey, actionParams, {
14521
+ chain,
14522
+ address
14523
+ }, {
14524
+ authorization
14525
+ });
14526
+ const gasLimitOverride = await estimateBufferedGasLimit(prepared);
14527
+ const txHash = prepared.type === 'evm' && gasLimitOverride !== undefined ? await prepared.execute({
14528
+ gasLimit: gasLimitOverride
14529
+ }) : await prepared.execute();
14530
+ const explorerUrl = buildExplorerUrl(chain, txHash);
14531
+ const receipt = await adapter.waitForTransaction(txHash, {
14532
+ confirmations: 1
14533
+ }, chain);
14534
+ if (receipt.status === 'reverted') {
14535
+ throw createTransactionRevertedError(chain.name, revertMessage, undefined, txHash, explorerUrl);
14536
+ }
14537
+ return {
14538
+ txHash,
14539
+ explorerUrl,
14540
+ ...receipt.gasUsed !== undefined && {
14541
+ gasUsed: receipt.gasUsed
14542
+ },
14543
+ ...receipt.effectiveGasPrice !== undefined && {
14544
+ effectiveGasPrice: receipt.effectiveGasPrice
14545
+ }
14546
+ };
14547
+ }
14548
+
14549
+ /**
14550
+ * Decide whether a same-chain earn action should be submitted as a single
14551
+ * atomic batch.
14552
+ *
14553
+ * Returns `true` only when the consumer has not opted out
14554
+ * (`batchTransactions !== false`), the source chain is EVM, the adapter
14555
+ * structurally exposes the shared batch methods, and the wallet reports atomic
14556
+ * batch support. `address` is forwarded as `fromAddress` so developer-controlled
14557
+ * adapters can probe the specific wallet. Any thrown capability probe is
14558
+ * treated as "no support".
14559
+ *
14560
+ * @param params - Adapter, chain, address, and the resolved `batchTransactions` flag.
14561
+ * @returns `true` when batched execution should be attempted.
14562
+ *
14563
+ * @example
14564
+ * ```typescript
14565
+ * if (await shouldUseBatchedEarnAction({ adapter, chain, address, batchTransactions })) {
14566
+ * // take the batched approve + execute path
14567
+ * }
14568
+ * ```
14569
+ *
14570
+ * @internal
14571
+ */ async function shouldUseBatchedEarnAction(params) {
14572
+ const { adapter, chain, address, batchTransactions } = params;
14573
+ if (batchTransactions === false) {
14574
+ return false;
14575
+ }
14576
+ if (chain.type !== 'evm') {
14577
+ return false;
14578
+ }
14579
+ const candidate = adapter;
14580
+ if (typeof candidate.supportsAtomicBatch !== 'function' || typeof candidate.batchExecute !== 'function') {
14581
+ return false;
14582
+ }
14583
+ try {
14584
+ return await candidate.supportsAtomicBatch(chain, {
14585
+ fromAddress: address
14586
+ });
14587
+ } catch {
14588
+ return false;
14589
+ }
14590
+ }
14591
+ async function buildSuccessfulBatchResult(adapter, chain, receipt, batchId, revertMessage) {
14592
+ const transaction = {
14593
+ txHash: receipt.txHash,
14594
+ explorerUrl: buildExplorerUrl(chain, receipt.txHash)
14595
+ };
14596
+ let confirmed;
14597
+ try {
14598
+ confirmed = await adapter.waitForTransaction(receipt.txHash, {
14599
+ confirmations: 1
14600
+ }, chain);
14601
+ } catch {
14602
+ // The batch adapter already confirmed success. Receipt enrichment is
14603
+ // telemetry-only, so an additional RPC failure must not turn an accepted
14604
+ // money-moving operation into a retryable business failure.
14605
+ return transaction;
14606
+ }
14607
+ if (confirmed.status === 'reverted') {
14608
+ throw createTransactionRevertedError(chain.name, revertMessage, {
14609
+ batchId
14610
+ }, receipt.txHash, transaction.explorerUrl);
14611
+ }
14612
+ return {
14613
+ ...transaction,
14614
+ ...confirmed.gasUsed !== undefined && {
14615
+ gasUsed: confirmed.gasUsed
14616
+ },
14617
+ ...confirmed.effectiveGasPrice !== undefined && {
14618
+ effectiveGasPrice: confirmed.effectiveGasPrice
14619
+ }
14620
+ };
14621
+ }
14622
+ function throwBatchFailure(result, executeReceipt, chain, actionKey, revertMessage) {
14623
+ const cause = result.error;
14624
+ if (result.statusCode === 400) {
14625
+ throw new KitError({
14626
+ ...RpcError.ENDPOINT_ERROR,
14627
+ recoverability: 'RETRYABLE',
14628
+ message: `Batched earn ${actionKey} failed off-chain before inclusion (batch ${result.batchId}).`,
14629
+ cause: {
14630
+ trace: {
14631
+ batchId: result.batchId,
14632
+ statusCode: result.statusCode,
14633
+ cause
14634
+ }
14635
+ }
14636
+ });
14637
+ }
14638
+ const causeTrace = cause instanceof KitError && typeof cause.cause?.trace === 'object' && cause.cause.trace !== null ? cause.cause.trace : undefined;
14639
+ if (cause instanceof KitError && causeTrace?.['kind'] === 'failed_offchain') {
14640
+ throw cause;
14641
+ }
14642
+ const isConfirmedRevert = cause instanceof KitError && cause.name === OnchainError.TRANSACTION_REVERTED.name || result.statusCode === 500 || result.statusCode === 600 || result.statusCode === undefined && cause === undefined && executeReceipt?.status === 'error' && executeReceipt.txHash !== '';
14643
+ if (isConfirmedRevert) {
14644
+ throw createTransactionRevertedError(chain.name, revertMessage, {
14645
+ batchId: result.batchId,
14646
+ error: cause
14647
+ });
14648
+ }
14649
+ throw new KitError({
14650
+ ...NetworkError.TIMEOUT,
14651
+ recoverability: 'FATAL',
14652
+ message: `Batched earn ${actionKey} was submitted (batch ${result.batchId}) but its outcome could not be confirmed; check the transaction status before retrying.`,
14653
+ cause: {
14654
+ trace: {
14655
+ batchId: result.batchId,
14656
+ cause
14657
+ }
14658
+ }
14659
+ });
14660
+ }
14661
+ /**
14662
+ * Execute the `approve` and `execute` steps of a same-chain earn action as a
14663
+ * single atomic batch.
14664
+ *
14665
+ * Prepare both `PreparedChainRequest` objects upfront, extract their raw call
14666
+ * data via `getCallData()`, then submit both through the adapter's shared
14667
+ * `batchExecute`. `address` is forwarded as `opts.fromAddress` so
14668
+ * developer-controlled adapters batch on behalf of the right wallet;
14669
+ * `idempotencyKey` is forwarded for adapters that deduplicate ambiguous
14670
+ * submissions (the Circle developer-controlled adapter reuses the Earn
14671
+ * execution id); other adapters may ignore either option. Reused by both the
14672
+ * deposit and withdraw flows via the `actionKey` parameter.
14673
+ *
14674
+ * @param params - Adapter, chain, action key, signed payload, and approval inputs.
14675
+ * @returns The confirmed execute transaction hash, explorer URL, and receipt
14676
+ * gas data when the adapter can retrieve it.
14677
+ * @throws {@link KitError} when the source chain is not EVM.
14678
+ * @throws {@link KitError} when calldata extraction (`getCallData`) is not
14679
+ * supported by the prepared requests.
14680
+ * @throws {@link KitError} when the batch reverts on-chain (a confirmed
14681
+ * terminal revert), carrying `batchId`.
14682
+ * @throws {@link KitError} RETRYABLE when EIP-5792 reports an off-chain
14683
+ * failure carrying `batchId` and status code `400`; no call was included.
14684
+ * @throws {@link KitError} FATAL `NetworkError.TIMEOUT` when the batch was
14685
+ * submitted but its outcome could not be confirmed (poll timeout or any
14686
+ * other non-revert post-submission failure); carries `batchId` so the caller
14687
+ * can check transaction status before retrying.
14688
+ * @remarks
14689
+ * Once the batch has been submitted this function does not fall back to the
14690
+ * sequential path — the batch is already on its way, so a fallback would risk
14691
+ * double-spend. Post-submission failures surface through the adapter's batch
14692
+ * result: a confirmed on-chain revert (Circle: a `TRANSACTION_REVERTED` cause;
14693
+ * Viem: status code `500`/`600`) is thrown as a revert error, status code `400`
14694
+ * is reported as a retryable off-chain failure, and any other unconfirmed
14695
+ * outcome is thrown as a FATAL timeout error carrying `batchId`.
14696
+ *
14697
+ * @example
14698
+ * ```typescript
14699
+ * const { txHash, explorerUrl } = await executeBatchedEarnAction({
14700
+ * adapter,
14701
+ * chain,
14702
+ * address,
14703
+ * actionKey: 'earn.deposit',
14704
+ * executeParams,
14705
+ * tokenInputs,
14706
+ * signature,
14707
+ * approvalToken: usdcAddress,
14708
+ * delegate: adapterContractAddress,
14709
+ * requiredAllowance: 1_000_000n,
14710
+ * idempotencyKey: '550e8400-e29b-41d4-a716-446655440000',
14711
+ * revertMessage: 'Earn deposit reverted on-chain',
14712
+ * })
14713
+ * ```
14714
+ *
14715
+ * @internal
14716
+ */ async function executeBatchedEarnAction(params) {
14717
+ const { adapter, chain, address, actionKey, executeParams, tokenInputs, signature, approvalToken, delegate, requiredAllowance, idempotencyKey, revertMessage } = params;
14718
+ if (chain.type !== 'evm') {
14719
+ throw new KitError({
14720
+ ...InputError.INVALID_CHAIN,
14721
+ recoverability: 'FATAL',
14722
+ message: 'Batched earn execution is only supported on EVM chains.'
14723
+ });
14724
+ }
14725
+ const evmChain = chain;
14726
+ const batchAdapter = adapter;
14727
+ // Read the current allowance so the approval tops up only the missing amount.
14728
+ // When the existing allowance already covers the payload, skip the approve
14729
+ // call and batch only the execute — this mirrors the sequential
14730
+ // approveAllowanceIfNeeded guard and avoids an increaseAllowance underflow
14731
+ // (requiredAllowance - currentAllowance would be negative, which reverts as
14732
+ // an out-of-range uint256).
14733
+ const allowancePrepared = await adapter.prepareAction('token.allowance', {
14734
+ tokenAddress: approvalToken,
14735
+ delegate
14736
+ }, {
14737
+ chain,
14738
+ address
14739
+ });
14740
+ const currentAllowance = parseAllowanceResponse(await allowancePrepared.execute());
14741
+ const approvalNeeded = currentAllowance < requiredAllowance;
14742
+ const executePrepared = await adapter.prepareAction(actionKey, {
14743
+ executeParams,
14744
+ tokenInputs,
14745
+ signature
14746
+ }, {
14747
+ chain,
14748
+ address
14749
+ });
14750
+ const approvePrepared = approvalNeeded ? await prepareApprovalAction({
14751
+ adapter,
14752
+ chain,
14753
+ address,
14754
+ tokenAddress: approvalToken,
14755
+ delegate,
14756
+ currentAllowance,
14757
+ requiredAllowance
14758
+ }) : undefined;
14759
+ if (executePrepared.type !== 'evm' || !executePrepared.getCallData) {
14760
+ throw new KitError({
14761
+ ...InputError.UNSUPPORTED_ACTION,
14762
+ recoverability: 'FATAL',
14763
+ message: 'Batched earn execution requires EVM prepared requests with getCallData() support.'
14764
+ });
14765
+ }
14766
+ if (approvePrepared !== undefined && (approvePrepared.type !== 'evm' || !approvePrepared.getCallData)) {
14767
+ throw new KitError({
14768
+ ...InputError.UNSUPPORTED_ACTION,
14769
+ recoverability: 'FATAL',
14770
+ message: 'Batched earn execution requires EVM prepared requests with getCallData() support.'
14771
+ });
14772
+ }
14773
+ const executeCallData = executePrepared.getCallData();
14774
+ // Prepend the approve call only when an allowance top-up is required.
14775
+ const calls = approvePrepared?.type === 'evm' && approvePrepared.getCallData ? [
14776
+ approvePrepared.getCallData(),
14777
+ executeCallData
14778
+ ] : [
14779
+ executeCallData
14780
+ ];
14781
+ const authorization = buildBatchedEarnExecuteDescriptor({
14782
+ action: actionKey === 'earn.deposit' ? 'deposit' : 'withdraw',
14783
+ chain: evmChain.chain,
14784
+ executionParams: executeParams
14785
+ });
14786
+ const result = await batchAdapter.batchExecute(calls, evmChain, {
14787
+ fromAddress: address,
14788
+ idempotencyKey,
14789
+ atomicRequired: true,
14790
+ authorization
14791
+ });
14792
+ // Success fans one confirmed hash across every receipt; the execute call is
14793
+ // the last one (approve, if present, precedes it). On failure a confirming
14794
+ // adapter returns no receipts, so a missing/non-success last receipt — or a
14795
+ // populated `result.error` — means the batch failed after submission (point
14796
+ // of no return). We never fall back, which would double-spend.
14797
+ const receiptCountMatches = result.receipts.length === calls.length;
14798
+ const executeReceipt = receiptCountMatches ? result.receipts[calls.length - 1] : undefined;
14799
+ const succeeded = receiptCountMatches && (result.statusCode === undefined || result.statusCode === 200) && result.error === undefined && executeReceipt?.status === 'success' && executeReceipt.txHash !== '';
14800
+ if (succeeded) {
14801
+ return buildSuccessfulBatchResult(adapter, evmChain, executeReceipt, result.batchId, revertMessage);
14802
+ }
14803
+ // Distinguish an off-chain rejection, a confirmed on-chain revert, and an
14804
+ // unknown outcome across both adapter conventions that share this contract:
14805
+ // - Circle SCA: no receipts + `error`; its trace kind identifies an
14806
+ // off-chain rejection, confirmed revert, or unconfirmed outcome.
14807
+ // - Viem EIP-5792: statusCode 500/600 explicitly confirms an on-chain
14808
+ // full/partial revert.
14809
+ // - Legacy/string-status wallets: a real-hash error receipt with no cause
14810
+ // is the best available confirmed-revert signal.
14811
+ // statusCode 400 is terminal but off-chain: the wallet confirms no call was
14812
+ // included, so it must not be labeled as a revert or unknown outcome.
14813
+ // Anything else — a poll timeout or any other post-submission failure with no
14814
+ // confirmed-revert signal — means the batch was submitted but its fate is
14815
+ // unconfirmed. Surface that as a FATAL (non-auto-retry) error carrying
14816
+ // `batchId` so the caller checks status before retrying, rather than
14817
+ // mislabeling it a revert.
14818
+ return throwBatchFailure(result, executeReceipt, evmChain, actionKey, revertMessage);
14819
+ }
14820
+
14821
+ /**
14822
+ * Validate that a service-signed execution payload has not expired before
14823
+ * the SDK asks the wallet to broadcast a transaction.
14824
+ *
14825
+ * @internal
14826
+ */ function validateExecutionDeadline(executionParams) {
14827
+ const deadline = BigInt(executionParams.deadline);
14828
+ const now = BigInt(Math.floor(Date.now() / 1000));
14829
+ if (deadline <= now) {
14830
+ throw createValidationFailedError('executionParams.deadline', executionParams.deadline, 'Earn execution deadline has expired');
14831
+ }
14832
+ }
14833
+
13407
14834
  /** Base discriminators shared by every earn action payload. */ const EARN_ACTION_BASE = {
13408
14835
  protocol: 'earn',
13409
14836
  service: 'earn-service'
@@ -14687,7 +16114,7 @@ const bridgeDepositPrepareReviewSchema = z.object({
14687
16114
  }
14688
16115
 
14689
16116
  var name = "@circle-fin/provider-earn-service";
14690
- var version = "1.3.1";
16117
+ var version = "1.4.0";
14691
16118
  var pkg = {
14692
16119
  name: name,
14693
16120
  version: version};
@@ -16315,6 +17742,46 @@ function finishElapsedWait(lastStatus, lastError) {
16315
17742
  const approvalToken = resolveEarnApprovalToken(executionParams);
16316
17743
  const tokenInputs = approvalToken === undefined ? [] : buildEarnTokenInputs(executionParams, approvalToken);
16317
17744
  const requiredAllowance = sumTokenInputAmounts(tokenInputs);
17745
+ const approvalNeeded = !options.skipApprove && approvalToken !== undefined && requiredAllowance > 0n;
17746
+ // Batch-capable wallets bundle approve + deposit into one atomic
17747
+ // submission. Only attempt this when an approval is actually needed.
17748
+ if (approvalNeeded && approvalToken !== undefined && await shouldUseBatchedEarnAction({
17749
+ adapter,
17750
+ chain,
17751
+ address,
17752
+ batchTransactions: config?.batchTransactions
17753
+ })) {
17754
+ const { txHash, explorerUrl } = await this.runPhase(ctx, 'deposit', 'execute', async ()=>{
17755
+ try {
17756
+ const result = await executeBatchedEarnAction({
17757
+ adapter,
17758
+ chain,
17759
+ address,
17760
+ actionKey: 'earn.deposit',
17761
+ executeParams: executionParams,
17762
+ tokenInputs,
17763
+ signature,
17764
+ approvalToken,
17765
+ delegate: adapterContractAddress,
17766
+ requiredAllowance,
17767
+ idempotencyKey: execId,
17768
+ revertMessage: 'Earn deposit reverted on-chain'
17769
+ });
17770
+ reportTransactionSuccess(transactionReportContext, 'Deposit', result);
17771
+ return result;
17772
+ } catch (error) {
17773
+ reportTransactionFailure(transactionReportContext, 'Deposit', error);
17774
+ throw error;
17775
+ }
17776
+ }, ({ txHash })=>txHash);
17777
+ return {
17778
+ kind: 'same-chain',
17779
+ txHash,
17780
+ explorerUrl,
17781
+ vaultAddress,
17782
+ amount: params.amount
17783
+ };
17784
+ }
16318
17785
  if (!options.skipApprove && approvalToken !== undefined && requiredAllowance > 0n) {
16319
17786
  await this.runPhase(ctx, 'approve', 'approve', async ()=>{
16320
17787
  try {
@@ -16347,6 +17814,8 @@ function finishElapsedWait(lastStatus, lastError) {
16347
17814
  tokenInputs,
16348
17815
  signature
16349
17816
  },
17817
+ action: 'deposit',
17818
+ executionParams,
16350
17819
  revertMessage: 'Earn deposit reverted on-chain'
16351
17820
  });
16352
17821
  reportTransactionSuccess(transactionReportContext, 'Deposit', result);
@@ -16478,6 +17947,44 @@ function finishElapsedWait(lastStatus, lastError) {
16478
17947
  const tokenInputs = buildEarnTokenInputs(executionParams, vaultAddress);
16479
17948
  const approvalToken = tokenInputs[0]?.token;
16480
17949
  const requiredAllowance = sumTokenInputAmounts(tokenInputs);
17950
+ // Batch-capable wallets bundle approve + withdraw into one atomic
17951
+ // submission. Only attempt this when an approval is actually needed.
17952
+ if (!options.skipApprove && approvalToken !== undefined && requiredAllowance > 0n && await shouldUseBatchedEarnAction({
17953
+ adapter,
17954
+ chain,
17955
+ address,
17956
+ batchTransactions: config?.batchTransactions
17957
+ })) {
17958
+ const { txHash, explorerUrl } = await this.runPhase(ctx, 'withdraw', 'execute', async ()=>{
17959
+ try {
17960
+ const result = await executeBatchedEarnAction({
17961
+ adapter,
17962
+ chain,
17963
+ address,
17964
+ actionKey: 'earn.withdraw',
17965
+ executeParams: executionParams,
17966
+ tokenInputs,
17967
+ signature,
17968
+ approvalToken,
17969
+ delegate: adapterContractAddress,
17970
+ requiredAllowance,
17971
+ idempotencyKey: execId,
17972
+ revertMessage: 'Earn withdraw reverted on-chain'
17973
+ });
17974
+ reportTransactionSuccess(transactionReportContext, 'Withdraw', result);
17975
+ return result;
17976
+ } catch (error) {
17977
+ reportTransactionFailure(transactionReportContext, 'Withdraw', error);
17978
+ throw error;
17979
+ }
17980
+ }, ({ txHash })=>txHash);
17981
+ return {
17982
+ txHash,
17983
+ explorerUrl,
17984
+ vaultAddress,
17985
+ amount: params.amount
17986
+ };
17987
+ }
16481
17988
  if (!options.skipApprove && approvalToken !== undefined) {
16482
17989
  await this.runPhase(ctx, 'approve', 'approve', async ()=>{
16483
17990
  try {
@@ -16510,6 +18017,8 @@ function finishElapsedWait(lastStatus, lastError) {
16510
18017
  tokenInputs,
16511
18018
  signature
16512
18019
  },
18020
+ action: 'withdraw',
18021
+ executionParams,
16513
18022
  revertMessage: 'Earn withdraw reverted on-chain'
16514
18023
  });
16515
18024
  reportTransactionSuccess(transactionReportContext, 'Withdraw', result);
@@ -16589,6 +18098,8 @@ function finishElapsedWait(lastStatus, lastError) {
16589
18098
  tokenInputs: [],
16590
18099
  signature
16591
18100
  },
18101
+ action: 'claimRewards',
18102
+ executionParams,
16592
18103
  revertMessage: 'Earn claim rewards reverted on-chain'
16593
18104
  }), ({ txHash })=>txHash);
16594
18105
  return {
@@ -17272,11 +18783,16 @@ const sourceAdapterContextSchema = z.object({
17272
18783
  *
17273
18784
  * Validate the optional Kit Key field using the standard `apiKeySchema`
17274
18785
  * format (`KIT_KEY:<keyId>:<keySecret>`). When omitted, the SDK
17275
- * operates in permissionless mode.
18786
+ * operates in permissionless mode. `baseUrl` overrides the Earn Service
18787
+ * endpoint (e.g. staging); `batchTransactions: false` opts out of atomic
18788
+ * batched execution. Both are forwarded to the provider, so this `.strict()`
18789
+ * schema must accept them or a valid config object is rejected.
17276
18790
  *
17277
18791
  * @internal
17278
18792
  */ const earnConfigSchema = z.object({
17279
- kitKey: apiKeySchema.optional()
18793
+ kitKey: apiKeySchema.optional(),
18794
+ baseUrl: z.string().optional(),
18795
+ batchTransactions: z.boolean().optional()
17280
18796
  }).strict();
17281
18797
  /**
17282
18798
  * Canonical decimal form: a leading digit with no leading zeros (a single