@aegis-engine/core 0.6.0 → 0.8.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.
Files changed (78) hide show
  1. package/README.md +232 -7
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/dist/account.d.ts +11 -0
  4. package/dist/account.js +129 -0
  5. package/dist/actions/allowance.d.ts +94 -0
  6. package/dist/actions/directPoolSwap.d.ts +10 -1
  7. package/dist/actions/kyberSwap.d.ts +2 -0
  8. package/dist/actions/types.d.ts +10 -3
  9. package/dist/actions/wallet.d.ts +1 -0
  10. package/dist/aegis-core.js +9653 -200
  11. package/dist/backendAdapters.d.ts +3 -1
  12. package/dist/config/chains.d.ts +1 -0
  13. package/dist/config/constants.d.ts +4 -0
  14. package/dist/config/tokens.d.ts +2 -1
  15. package/dist/config/types.d.ts +8 -0
  16. package/dist/contract/backendClient.d.ts +3 -1
  17. package/dist/contract/generated/aegis-swap.d.ts +6337 -1377
  18. package/dist/contract/generated/market-data.d.ts +8286 -0
  19. package/dist/contract/index.d.ts +1 -0
  20. package/dist/contract/responseBudget.d.ts +9 -0
  21. package/dist/contract/schemas.d.ts +13 -3
  22. package/dist/engine/account/accounting.d.ts +24 -0
  23. package/dist/engine/account/accountingSchemas.d.ts +2056 -0
  24. package/dist/engine/account/activity.d.ts +42 -0
  25. package/dist/engine/account/activitySchemas.d.ts +327 -0
  26. package/dist/engine/account/amountSchemas.d.ts +9 -0
  27. package/dist/engine/account/catalogSchemas.d.ts +108 -0
  28. package/dist/engine/account/client.d.ts +14 -0
  29. package/dist/engine/account/history.d.ts +40 -0
  30. package/dist/engine/account/historySchemas.d.ts +251 -0
  31. package/dist/engine/account/management.d.ts +13 -0
  32. package/dist/engine/account/portfolioSchemas.d.ts +712 -0
  33. package/dist/engine/account/positionPerformance.d.ts +18 -0
  34. package/dist/engine/account/positionPerformanceSchemas.d.ts +101 -0
  35. package/dist/engine/account/positionPnl.d.ts +18 -0
  36. package/dist/engine/account/positionPnlSchemas.d.ts +149 -0
  37. package/dist/engine/account/transactionHistory.d.ts +50 -0
  38. package/dist/engine/account/transactionSchemas.d.ts +101 -0
  39. package/dist/engine/account/transactions.d.ts +26 -0
  40. package/dist/engine/account/transport.d.ts +31 -0
  41. package/dist/engine/account/types.d.ts +39 -0
  42. package/dist/engine/actions.d.ts +14 -4
  43. package/dist/engine/adaptiveFee.d.ts +14 -0
  44. package/dist/engine/balancedLending.d.ts +82 -0
  45. package/dist/engine/borrowCollateralFloor.d.ts +3 -0
  46. package/dist/engine/borrowLimits.d.ts +18 -0
  47. package/dist/engine/dataSource.d.ts +2 -0
  48. package/dist/engine/index.d.ts +20 -0
  49. package/dist/engine/marketAdapter.d.ts +3 -0
  50. package/dist/engine/marketSeries.d.ts +61 -0
  51. package/dist/engine/marketSeriesSchemas.d.ts +312 -0
  52. package/dist/engine/marketTrust.d.ts +26 -0
  53. package/dist/engine/openingEntry.d.ts +41 -0
  54. package/dist/engine/rateHistorySchemas.d.ts +88 -0
  55. package/dist/engine/reads.d.ts +1 -1
  56. package/dist/engine/registry.d.ts +1 -1
  57. package/dist/engine/restSchemas.d.ts +59 -1
  58. package/dist/engine/tradeExecutionSession.d.ts +155 -0
  59. package/dist/engine/types.d.ts +169 -15
  60. package/dist/engine/v4Quote.d.ts +5 -0
  61. package/dist/index.d.ts +13 -8
  62. package/dist/internal/guardedWalletTransaction.d.ts +31 -0
  63. package/dist/permit.d.ts +80 -6
  64. package/dist/quote/aggregatedSwapQuote.d.ts +5 -1
  65. package/dist/quote/kyberCalldata.d.ts +5 -1
  66. package/dist/{sdkRuntime-C_vaU-0g.js → sdkRuntime-3aRt_g55.js} +3385 -2957
  67. package/dist/services/kyberSwap.d.ts +12 -0
  68. package/dist/swap/authorizePermit.d.ts +11 -9
  69. package/dist/swap/executeSwapTransaction.d.ts +5 -1
  70. package/dist/swap/receiptWait.d.ts +9 -0
  71. package/dist/swap/sendSwapTransaction.d.ts +7 -0
  72. package/dist/swap/settlement.d.ts +4 -0
  73. package/dist/swap/trustedMarket.d.ts +25 -0
  74. package/dist/transactionHistory-1Zl2KCcV.js +5915 -0
  75. package/dist/transactionProgress.d.ts +41 -2
  76. package/dist/wallet.d.ts +5 -1
  77. package/package.json +12 -5
  78. package/dist/index-D9EfUokZ.js +0 -11031
@@ -1,3 +1,4 @@
1
+ import type { AegisTransactionObservation } from '../swap/receiptWait.js';
1
2
  import type { Address, Hex, PublicClient, TransactionReceipt } from 'viem';
2
3
  import type { AegisSwapChainConfig, AegisSwapToken } from '../config/index.js';
3
4
  import type { SignedPermitBatch } from '../encoding.js';
@@ -30,6 +31,13 @@ export type AegisEngineMarketMetrics = {
30
31
  manualOverride?: boolean | null;
31
32
  perSwapMode?: boolean | null;
32
33
  feeSource?: string | null;
34
+ /** Post-swap surge-trigger threshold from the opt-in REST v2 market plane.
35
+ * It is observability data, not a hard price, tick, or slippage limit. */
36
+ adaptiveTickThresholdTicks?: number;
37
+ /** Present exactly when adaptiveTickThresholdTicks is present. */
38
+ adaptiveTickThresholdMode?: 'post_swap_surge_trigger';
39
+ /** Fee-quote observation time from the opt-in REST v2 market plane. */
40
+ feeObservedAt?: string | null;
33
41
  computedAt?: string | null;
34
42
  updatedAt?: string | null;
35
43
  engineUpdatedAt?: string | null;
@@ -55,6 +63,7 @@ export type AegisEngineMarket = {
55
63
  source: AegisEngineMarketSource;
56
64
  status: AegisEngineMarketStatus;
57
65
  displayName: string;
66
+ labels?: string[];
58
67
  poolId: Hex;
59
68
  token0: AegisEngineToken;
60
69
  token1: AegisEngineToken;
@@ -109,6 +118,14 @@ export type AegisEngineMetricPoint = {
109
118
  inCapEvent: boolean | null;
110
119
  manualOverride: boolean | null;
111
120
  perSwapMode: boolean | null;
121
+ /** Required-nullable on the REST v2 wire; absent only after a 404 fallback
122
+ * to the frozen v1 history endpoint. */
123
+ adaptiveTickThresholdTicks?: number | null;
124
+ /** Paired with adaptiveTickThresholdTicks; describes a post-swap trigger,
125
+ * never an execution cap. */
126
+ adaptiveTickThresholdMode?: 'post_swap_surge_trigger' | null;
127
+ /** Required-nullable on the REST v2 wire; absent after a v1 fallback. */
128
+ feeObservedAt?: string | null;
112
129
  warnings: string[];
113
130
  };
114
131
  export type AegisEngineMetricHistory = {
@@ -347,8 +364,8 @@ export type AegisEnginePositionActivitySnapshot = {
347
364
  /** Off-chain opening intent for one confirmed Long/Short transaction. The
348
365
  * Engine transaction does not encode its target scenario or average leverage,
349
366
  * so consumers may persist this small record and join it back to the indexed
350
- * opening transaction. Indexed actions remain authoritative for direction and
351
- * entry price. */
367
+ * opening transaction. Indexed actions identify the opening direction; they do not prove an
368
+ * executed entry price. */
352
369
  export type AegisEngineTradePositionIntent = {
353
370
  schemaVersion: '1';
354
371
  chainId: number;
@@ -367,7 +384,7 @@ export type AegisEngineTradePositionIntent = {
367
384
  /** Durable Long/Short identity reconstructed from one vault's indexed opening
368
385
  * transaction. Optional scenario fields are present only when a matching
369
386
  * off-chain intent record survived; they never override indexed direction or
370
- * entry price. */
387
+ * supply execution evidence. */
371
388
  export type AegisEngineTradePositionStrategy = {
372
389
  kind: 'trade';
373
390
  vaultId: string;
@@ -375,8 +392,16 @@ export type AegisEngineTradePositionStrategy = {
375
392
  direction: AegisEngineTradeDirection;
376
393
  openTxHash: Hex;
377
394
  openedAt: number;
378
- /** Executed opening spot, token1 per token0, derived from DebtModified. */
395
+ /** Receipt-reconciled opening swap price in token1 per token0. Indexed
396
+ * Engine actions alone leave this null; this is not wallet cost basis or PnL. */
379
397
  entryPrice: number | null;
398
+ /** Missing on legacy host records; consumers must treat those as unverified. */
399
+ entryPriceBasis?: 'receipt-reconciled' | 'unavailable';
400
+ /** Informational debt-action ratio only. Never substitute it for entryPrice. */
401
+ referencePrice?: {
402
+ basis: 'debt-action-token-ratio';
403
+ price: number | null;
404
+ };
380
405
  /** Reviewed average leverage to the target scenario, not current leverage. */
381
406
  averageLeverage: number | null;
382
407
  /** Reviewed scenario only. Null when no matching intent record is available. */
@@ -396,6 +421,12 @@ export type AegisEngineBorrowPositionHydration = {
396
421
  rL: bigint;
397
422
  /** Accrued debt in L units at this hydration frame. */
398
423
  debtLLatest: bigint;
424
+ /** Rounded-up full-range repayment legs at the same verified block.
425
+ * Null/absent means USD debt and equity must not be estimated from L alone. */
426
+ debtAmounts?: {
427
+ amount0: bigint;
428
+ amount1: bigint;
429
+ } | null;
399
430
  idle0: bigint;
400
431
  idle1: bigint;
401
432
  /** Null when the vault has no debt, never a synthetic zero. */
@@ -440,6 +471,7 @@ export type AegisEnginePositionsHydrationInput = {
440
471
  export type AegisEngineRestSource = {
441
472
  kind: 'rest';
442
473
  baseUrl: string;
474
+ includeLabels?: boolean;
443
475
  headers?: Record<string, string>;
444
476
  /**
445
477
  * Maximum time for a shared REST request, including response-body parsing.
@@ -456,6 +488,9 @@ export type AegisEngineRestSource = {
456
488
  */
457
489
  export type AegisEngineStaticSource = {
458
490
  kind: 'static';
491
+ /** Read current balances and vault state for supplied positions through the
492
+ * host's public client. Opt in for interactive simulation or host indexes. */
493
+ hydratePositions?: boolean;
459
494
  markets: AegisEngineMarket[];
460
495
  positions?: AegisEnginePosition[];
461
496
  lendPositions?: AegisEngineLendSharesPosition[];
@@ -521,6 +556,21 @@ export type AegisEngineReadFrame = {
521
556
  /** Local wall-clock time when the frame was assembled, in Unix milliseconds. */
522
557
  observedAt: number;
523
558
  };
559
+ /** Block-pinned DFM state. The threshold is observed after execution and can
560
+ * activate or adapt surge fees; it is not an on-chain swap limit. */
561
+ export type AegisEngineAdaptiveFeeEvidence = {
562
+ source: 'rpc';
563
+ enforcement: 'post-swap-surge-trigger';
564
+ evaluationScope: 'per-swap' | 'per-block';
565
+ blockNumber: bigint;
566
+ activeFeePpm: number;
567
+ baseFeePpm: number;
568
+ surgeFeePpm: number;
569
+ adaptiveTickThresholdTicks: number;
570
+ surgeActive: boolean;
571
+ inCapEvent: boolean;
572
+ manualOverride: boolean;
573
+ };
524
574
  export type AegisEngineVersion = 'v0.4.0' | 'v1.0.2' | 'v1.0.3';
525
575
  export type AegisEngineBorrowMarketContext = {
526
576
  poolId: Hex;
@@ -584,6 +634,9 @@ export type AegisEngineQuoteBase = {
584
634
  };
585
635
  export type AegisEngineDepositQuoteInput = AegisEngineQuoteBase & {
586
636
  amountIn: bigint;
637
+ /** Required host policy. A swap quote above this block-pinned impact is
638
+ * returned as non-executable; this is independent of output slippage. */
639
+ maxPriceImpactBps: number;
587
640
  };
588
641
  /**
589
642
  * Live snapshot of an already-open borrow vault, in the pool's real token
@@ -632,6 +685,10 @@ export type AegisEngineBorrowCapacityInput = Omit<AegisEngineQuoteBase, 'owner'
632
685
  /** Optional output-first target. When supplied, the result includes the
633
686
  * collateral floor for the deterministic no-swap path. */
634
687
  borrowOut?: bigint;
688
+ /** Include wallet and market quick-fill limits in this same live frame. */
689
+ includeBorrowLimits?: boolean;
690
+ /** Spendable collateral after the native gas reserve; omitted when unknown. */
691
+ walletCollateralIn?: bigint;
635
692
  tauPips?: number;
636
693
  /** See `AegisEngineBorrowQuoteInput.tauPercentOfMaxLtv`. */
637
694
  tauPercentOfMaxLtv?: number;
@@ -641,7 +698,7 @@ export type AegisEngineBorrowCapacityInput = Omit<AegisEngineQuoteBase, 'owner'
641
698
  export type AegisEngineDepositQuoteResult = {
642
699
  feasible: boolean;
643
700
  executable: boolean;
644
- infeasibleReason?: 'invalid-input' | 'quote-unavailable' | 'insufficient-output' | 'zero-liquidity' | 'builder-error';
701
+ infeasibleReason?: 'invalid-input' | 'quote-unavailable' | 'price-impact-unavailable' | 'price-impact-limit' | 'insufficient-output' | 'zero-liquidity' | 'builder-error';
645
702
  /** SDK recipe input retained for diagnostics. Use `tx` on the enclosing
646
703
  * Core quote for execution instead of encoding this value downstream. */
647
704
  encodeInput: unknown | null;
@@ -699,6 +756,9 @@ export type AegisEngineDepositQuote = {
699
756
  kind: 'lend';
700
757
  market: AegisEngineMarket;
701
758
  inputToken: AegisEngineToken;
759
+ /** Same-block DFM evidence when the trusted RPC read succeeded. Null means
760
+ * the quote carries no adaptive-fee observation, never a zero threshold. */
761
+ adaptiveFee?: AegisEngineAdaptiveFeeEvidence | null;
702
762
  quote: AegisEngineDepositQuoteResult;
703
763
  tx: AegisEnginePreparedTransaction | null;
704
764
  };
@@ -798,12 +858,28 @@ export type AegisEngineTradeOpenQuoteInput = {
798
858
  /** @deprecated Ignored. Spec-0168 always selects the lower-debt frontier. */
799
859
  rootPolicy?: AegisEngineTapRootPolicy;
800
860
  slippageBps: number;
861
+ /** Required host policy. Core rejects a block-pinned internal swap whose
862
+ * price impact exceeds this value. It is not a pool-movement invariant. */
863
+ maxPriceImpactBps: number;
801
864
  deadline?: bigint;
802
865
  /** Abort a superseded indicative quote between its block-pinned phases. */
803
866
  signal?: AbortSignal;
804
867
  /** Submit paths set this after changing router authorization. */
805
868
  forceExecutionEvidenceRefresh?: boolean;
806
869
  };
870
+ /** Exact caller-owned strategy and safety policy that produced a Trade quote.
871
+ * Execution sessions bind this echo before any wallet request. */
872
+ export type AegisEngineTradeOpenQuoteIntent = Readonly<{
873
+ owner: Address;
874
+ inputIsToken0: boolean;
875
+ collateralIn: bigint;
876
+ /** Null means the quote selected the live maximum. */
877
+ leverage: number | null;
878
+ horizonSeconds: number;
879
+ priceMove: number;
880
+ slippageBps: number;
881
+ maxPriceImpactBps: number;
882
+ }>;
807
883
  export type AegisEngineTradeOpenInfeasibleReason = AegisEngineTapInfeasibleReason['kind']
808
884
  /** The chosen root's swap trades against the requested direction at entry. */
809
885
  | 'swap-direction-mismatch'
@@ -814,7 +890,11 @@ export type AegisEngineTradeOpenInfeasibleReason = AegisEngineTapInfeasibleReaso
814
890
  /** LTV recomputed from the encoded amounts is at or above the open cap. */
815
891
  | 'ltv-above-max'
816
892
  /** The swap was quoted at a different block than the sizing state. */
817
- | 'stale-frame';
893
+ | 'stale-frame'
894
+ /** The block-pinned quote could not produce a finite impact assessment. */
895
+ | 'price-impact-unavailable'
896
+ /** The block-pinned quote exceeded the host's required impact limit. */
897
+ | 'price-impact-limit';
818
898
  /** Actionable bounds for a rejected quote. Each field is null when the
819
899
  * rejection did not produce one. */
820
900
  export type AegisEngineTradeOpenLimits = {
@@ -860,8 +940,25 @@ export type AegisEngineTradeOpenPosition = {
860
940
  /** Gross return from exact entry equity to target equity, before horizon
861
941
  * interest. The encoded swap output floor is already reflected in both. */
862
942
  grossReturnAtTargetPct: number;
943
+ /** Indicative equity at the reviewed prices, in token1 major units. Uses
944
+ * the quote rate held constant; excludes gas and future closing costs. */
945
+ scenario?: {
946
+ entryEquity: number;
947
+ targetEquityAfterInterest: number;
948
+ targetInterest: number;
949
+ };
863
950
  /** Borrow principal in rL units. */
864
951
  principalDeltaRl: bigint;
952
+ /**
953
+ * Market utilization immediately before and after this position's final,
954
+ * integer-rounded debt is added. Both values come from the quote's pinned
955
+ * market frame; consumers must not mix in a REST utilization snapshot.
956
+ */
957
+ marketUtilization?: {
958
+ beforePips: number;
959
+ afterPips: number;
960
+ capPips?: number;
961
+ };
865
962
  /** Vault idle at lock, in base units — the collateral `lockVault` values. */
866
963
  collateral0: bigint;
867
964
  collateral1: bigint;
@@ -887,6 +984,8 @@ export type AegisEngineTradeOpenQuote = {
887
984
  market: AegisEngineMarket;
888
985
  direction: AegisEngineTradeDirection;
889
986
  collateralToken: AegisEngineToken;
987
+ /** Exact request identity used to build this quote. */
988
+ intent: AegisEngineTradeOpenQuoteIntent;
890
989
  /** Thresholds read in the same live frame used to size the position. */
891
990
  thresholds: {
892
991
  maxLtvPips: number;
@@ -901,6 +1000,8 @@ export type AegisEngineTradeOpenQuote = {
901
1000
  position: AegisEngineTradeOpenPosition | null;
902
1001
  /** Null when the borrow already delivers the target mix. */
903
1002
  swap: AegisEngineTradeOpenSwap | null;
1003
+ /** Same-block DFM evidence. This is review telemetry, not an execution cap. */
1004
+ adaptiveFee?: AegisEngineAdaptiveFeeEvidence | null;
904
1005
  deposit: {
905
1006
  amount0: bigint;
906
1007
  amount1: bigint;
@@ -967,6 +1068,13 @@ export type AegisEnginePositionActionQuote = {
967
1068
  } | null;
968
1069
  /** Borrow principal affected by repay/close, in rL units. */
969
1070
  principalDeltaRl: bigint | null;
1071
+ requestedRepayProjection?: {
1072
+ ltvPips: number | null;
1073
+ debtFree: boolean;
1074
+ idle0: bigint;
1075
+ idle1: bigint;
1076
+ debtL: bigint;
1077
+ } | null;
970
1078
  /** Exact idle token amounts requested by withdraw. */
971
1079
  withdraw: {
972
1080
  amount0: bigint;
@@ -1120,6 +1228,24 @@ export type AegisEngineVaultActivityEntry = {
1120
1228
  receivedRaw: bigint | null;
1121
1229
  receivedIsToken0: boolean | null;
1122
1230
  };
1231
+ /** Settled sizing result. A floor is planning data, never execution permission. */
1232
+ export type AegisEngineBorrowCollateralFloor = {
1233
+ status: 'not-requested';
1234
+ } | {
1235
+ status: 'ready-positive';
1236
+ amountIn: bigint;
1237
+ } | {
1238
+ status: 'ready-zero';
1239
+ amountIn: 0n;
1240
+ outputSource: 'existing-idle' | 'new-debt' | 'unknown';
1241
+ } | {
1242
+ status: 'infeasible';
1243
+ reason: 'utilization-capped';
1244
+ } | {
1245
+ status: 'unavailable';
1246
+ reason: 'closed-form-not-applicable' | 'forward-validation-unavailable' | 'legacy-no-floor';
1247
+ retryable: boolean;
1248
+ };
1123
1249
  export type AegisEngineBorrowCapacity = {
1124
1250
  kind: 'borrow-capacity';
1125
1251
  market: AegisEngineMarket;
@@ -1135,16 +1261,25 @@ export type AegisEngineBorrowCapacity = {
1135
1261
  tauPercentOfMaxLtv: number | null;
1136
1262
  /** Echoed output target used to derive `minimumNoSwapCollateralIn`. */
1137
1263
  borrowOut: bigint | null;
1138
- /** Minimum fresh-vault deposit that crosses the SDK's integer no-swap
1264
+ /** Minimum deposit for the supplied vault that crosses the SDK's integer no-swap
1139
1265
  * boundary. Null when no output target was supplied, no closed-form
1140
1266
  * no-swap solution exists, or the market is utilization-capped. */
1141
1267
  minimumNoSwapCollateralIn: bigint | null;
1268
+ /** Always emitted by quoteEngineBorrowCapacity; optional for older host snapshots. */
1269
+ collateralFloor?: AegisEngineBorrowCollateralFloor;
1270
+ /** Market frame used for sizing; vault inputs still need executable revalidation. */
1271
+ frame?: AegisEngineReadFrame;
1142
1272
  /** Equals `capacity.utilizationPre >= capacity.utilizationCap` at quote
1143
1273
  * time. Named (rather than derived by consumers) because the SDK's stage
1144
1274
  * classifier can mask a cap block behind preserve-vs-allow reachability
1145
1275
  * (`preserve-collateral-blocked`), so `bindingConstraint`/quote reasons
1146
1276
  * can't be trusted for it. When true no borrow executes for any deposit
1147
1277
  * and no collateral floor is published. */
1278
+ borrowLimits?: {
1279
+ walletCollateralIn: bigint | null;
1280
+ walletBorrowOut: bigint | null;
1281
+ marketBorrowOut: bigint;
1282
+ };
1148
1283
  utilizationCapped: boolean;
1149
1284
  capacity: {
1150
1285
  yMaxLtv: bigint;
@@ -1177,7 +1312,10 @@ export type AegisEnginePreparedTransaction = {
1177
1312
  export type AegisEngineSignedPermitBatch = SignedPermitBatch;
1178
1313
  export type AegisEngineWalletSession = WalletSession;
1179
1314
  export type AegisEngineActionCallbacks = {
1315
+ onTransactionObservation?: (event: AegisTransactionObservation) => void;
1180
1316
  onStatus?: (status: 'approving' | 'signing' | 'submitting' | 'success' | 'idle') => void;
1317
+ /** Fires after simulation and chain guards, immediately before the wallet request. */
1318
+ onWalletRequest?: () => void;
1181
1319
  onTxHash?: (hash: Hex | null) => void;
1182
1320
  onSubmitted?: (hash: Hex) => void;
1183
1321
  };
@@ -1201,8 +1339,11 @@ export type AegisEngineAuthorizationStep = {
1201
1339
  id: AegisEngineAuthorizationStepKind;
1202
1340
  kind: AegisEngineAuthorizationStepKind;
1203
1341
  status: AegisEngineAuthorizationStepStatus;
1204
- /** Every current Long/Short authorization is an on-chain wallet transaction. */
1205
- walletAction: 'transaction';
1342
+ /**
1343
+ * Wallet interaction required by this step. Permit2 signature mode can fall
1344
+ * back to an on-chain spending-cap transaction when typed data is unavailable.
1345
+ */
1346
+ walletAction: 'transaction' | 'signature-or-transaction';
1206
1347
  /** Contract the wallet action targets. */
1207
1348
  target: Address;
1208
1349
  /** Contract receiving authority, when distinct from the target. */
@@ -1211,6 +1352,7 @@ export type AegisEngineAuthorizationStep = {
1211
1352
  token: AegisEngineToken | null;
1212
1353
  /** Current on-chain allowance, when the step governs a token amount. */
1213
1354
  currentAmount: bigint | null;
1355
+ currentExpiration?: number | null;
1214
1356
  /** Amount a required wallet action will set. Null for satisfied or non-token actions. */
1215
1357
  requestedAmount: bigint | null;
1216
1358
  /** Permit2 expiry in Unix seconds. Null when the authority has no expiry field. */
@@ -1229,6 +1371,12 @@ export type AegisEngineAuthorizationPlan = {
1229
1371
  token: AegisEngineToken;
1230
1372
  amount: bigint;
1231
1373
  approvalMode: 'exact' | 'max';
1374
+ /** Read observations drive permission presentation only, never submission authority. */
1375
+ observations?: {
1376
+ erc20Allowance: bigint | null;
1377
+ permit2Allowance: readonly [bigint, number, number] | null;
1378
+ permit2AuthorizationMode: 'signature' | 'spending-cap';
1379
+ };
1232
1380
  router: Address;
1233
1381
  permit2: Address;
1234
1382
  vaultRegistry: Address;
@@ -1237,7 +1385,7 @@ export type AegisEngineAuthorizationPlan = {
1237
1385
  missingPermissionCount: number;
1238
1386
  /** True when the known wallet chain adds a network-switch request; null when unknown. */
1239
1387
  walletChainSwitchRequired: boolean | null;
1240
- /** Sequential transaction request count. A network switch is reported separately. */
1388
+ /** Sequential wallet-action count. A network switch is reported separately. */
1241
1389
  walletPromptCount: number;
1242
1390
  /** True when only the final position transaction remains. */
1243
1391
  readyForOpen: boolean;
@@ -1252,12 +1400,16 @@ export type AegisEngineAuthorizationPlanInput = {
1252
1400
  token: AegisEngineToken;
1253
1401
  amount: bigint;
1254
1402
  approvalMode?: 'exact' | 'max';
1403
+ /** Must match the authorization mode used when the reviewed plan is executed. */
1404
+ permit2AuthorizationMode?: 'signature' | 'spending-cap';
1255
1405
  };
1256
1406
  export type AegisEngineAuthorizationProgress = {
1257
1407
  kind: AegisEngineAuthorizationStepKind;
1258
1408
  status: 'requesting' | 'confirmed';
1259
1409
  };
1260
- /** Lifecycle evidence for one Engine permission request. */
1410
+ /** Truthful per-prerequisite lifecycle. Kept separate from the legacy
1411
+ * requesting/confirmed projection so existing exhaustive consumers do not
1412
+ * break when submitted and terminal states are added. */
1261
1413
  export type AegisEngineAuthorizationExecutionEvent = Readonly<{
1262
1414
  kind: AegisEngineAuthorizationStepKind;
1263
1415
  status: 'wallet-requested';
@@ -1266,13 +1418,15 @@ export type AegisEngineAuthorizationExecutionEvent = Readonly<{
1266
1418
  kind: AegisEngineAuthorizationStepKind;
1267
1419
  status: 'submitted';
1268
1420
  hash: Hex;
1421
+ replacesHash?: Hex;
1422
+ executionChanged?: boolean;
1269
1423
  }> | Readonly<{
1270
1424
  kind: AegisEngineAuthorizationStepKind;
1271
1425
  status: 'confirmed';
1272
1426
  hash: Hex | null;
1273
1427
  }> | Readonly<{
1274
1428
  kind: AegisEngineAuthorizationStepKind;
1275
- status: 'cancelled' | 'failed';
1429
+ status: 'failed' | 'cancelled';
1276
1430
  hash: Hex | null;
1277
1431
  error: ClassifiedError;
1278
1432
  }>;
@@ -1280,9 +1434,9 @@ export type AegisEngineApprovalInput = {
1280
1434
  wallet: AegisEngineWalletSession;
1281
1435
  publicClient: PublicClient;
1282
1436
  activeChain: AegisSwapChainConfig;
1437
+ /** Reviewed market used to resolve Permit2 and router from the trusted registry. */
1438
+ market: AegisEngineMarket;
1283
1439
  token: AegisEngineToken;
1284
- permit2: Address;
1285
- router: Address;
1286
1440
  amount: bigint;
1287
1441
  approvalMode?: 'exact' | 'max';
1288
1442
  permit2AuthorizationMode?: 'signature' | 'spending-cap';
@@ -1291,7 +1445,7 @@ export type AegisEngineApprovalInput = {
1291
1445
  onStatus?: AegisEngineActionCallbacks['onStatus'];
1292
1446
  /** Fine-grained prerequisite progress for truthful wallet onboarding. */
1293
1447
  onAuthorizationProgress?: (progress: AegisEngineAuthorizationProgress) => void;
1294
- /** Full prerequisite lifecycle at the wallet and receipt boundaries. */
1448
+ /** Full prerequisite lifecycle at the real wallet and receipt boundaries. */
1295
1449
  onAuthorizationExecution?: (event: AegisEngineAuthorizationExecutionEvent) => void;
1296
1450
  /** Awaited after each prerequisite receipt and before another wallet request. */
1297
1451
  onAuthorizationCheckpoint?: () => Promise<void>;
@@ -0,0 +1,5 @@
1
+ export type AegisEngineV4ExactInputFrameQuote = Readonly<{
2
+ amountOut: bigint;
3
+ gasEstimate: bigint;
4
+ blockNumber: bigint;
5
+ }>;
package/dist/index.d.ts CHANGED
@@ -1,37 +1,40 @@
1
- export { AEGIS_DYNAMIC_FEE_FLAG, AEGIS_SWAP_CHAINS, AEGIS_SWAP_CHAIN_ID, AEGIS_SWAP_DEFAULT_FEE_BPS, AEGIS_SWAP_DEFAULT_FEE_RECIPIENT, AEGIS_SWAP_DEFAULT_METADATA_ENDPOINT, AEGIS_SWAP_DEFAULT_RPC_URLS, AEGIS_SWAP_HOOK, AEGIS_SWAP_MAINNET_CHAIN, AEGIS_SWAP_MAINNET_UNISWAP_V4_CONTRACTS, AEGIS_SWAP_PERMIT2, AEGIS_SWAP_ROUTER, AEGIS_SWAP_TOKENS, AEGIS_SWAP_TRUSTED_ROUTERS_BY_CHAIN, AEGIS_SWAP_V4_QUOTER, AGGREGATED_SWAP_CURATED_TOKENS, AGGREGATED_SWAP_DEFAULT_TOKEN_LIST, AGGREGATED_SWAP_DEFAULT_TOKENS, AGGREGATED_SWAP_SUPPORTED_CHAIN_IDS, AGGREGATED_SWAP_TOKEN_PRESETS, AGGREGATED_SWAP_WOLFGAME_TOKEN_LIST, AGGREGATED_SWAP_WOLFGAME_TOKENS, UNISWAP_V4_CONTRACTS_BY_CHAIN, createAegisSwapChainConfig, createAegisSwapChains, createAegisSwapMarketsFromPools, createAegisSwapPoolMarket, createAegisSwapUniswapV4Contracts, getExplorerUrl } from './config/index.js';
2
- export type { AegisPoolKey, AegisSwapBuiltInTokenSymbol, AegisSwapChainConfig, AegisSwapChainConfigInput, AegisSwapFeeConfig, AegisSwapMarket, AegisSwapPoolConfig, AegisSwapToken, AegisSwapTokenSymbol, AegisSwapUniswapV4Contracts, AegisSwapUniswapV4ContractsInput, AggregatedSwapDefaultTokenSymbol, AggregatedSwapToken, AggregatedSwapTokenSymbol, AggregatedSwapWolfGameTokenSymbol } from './config/index.js';
1
+ export { AEGIS_DYNAMIC_FEE_FLAG, AEGIS_SWAP_BSC_CHAIN, AEGIS_SWAP_BSC_CHAIN_ID, AEGIS_SWAP_BSC_HOOK, AEGIS_SWAP_BSC_ROUTER, AEGIS_SWAP_BSC_RPC_URLS, AEGIS_SWAP_BSC_TOKENS, AEGIS_SWAP_CHAINS, AEGIS_SWAP_CHAIN_ID, AEGIS_SWAP_DEFAULT_FEE_BPS, AEGIS_SWAP_DEFAULT_FEE_RECIPIENT, AEGIS_SWAP_DEFAULT_METADATA_ENDPOINT, AEGIS_SWAP_DEFAULT_RPC_URLS, AEGIS_SWAP_HOOK, AEGIS_SWAP_MAINNET_CHAIN, AEGIS_SWAP_MAINNET_UNISWAP_V4_CONTRACTS, AEGIS_SWAP_PERMIT2, AEGIS_SWAP_ROUTER, AEGIS_SWAP_TOKENS, AEGIS_SWAP_TRUSTED_ROUTERS_BY_CHAIN, AEGIS_SWAP_V4_QUOTER, AGGREGATED_SWAP_CURATED_TOKENS, AGGREGATED_SWAP_DEFAULT_TOKEN_LIST, AGGREGATED_SWAP_DEFAULT_TOKENS, AGGREGATED_SWAP_SUPPORTED_CHAIN_IDS, AGGREGATED_SWAP_TOKEN_PRESETS, AGGREGATED_SWAP_WOLFGAME_TOKEN_LIST, AGGREGATED_SWAP_WOLFGAME_TOKENS, UNISWAP_V4_CONTRACTS_BY_CHAIN, createAegisSwapChainConfig, createAegisSwapChains, createAegisSwapMarketsFromPools, createAegisSwapPoolMarket, createAegisSwapUniswapV4Contracts, getExplorerUrl } from './config/index.js';
2
+ export type { AegisPoolKey, AegisSwapBscTokenSymbol, AegisSwapBuiltInTokenSymbol, AegisSwapChainConfig, AegisSwapChainConfigInput, AegisSwapFeeConfig, AegisSwapMarket, AegisSwapPoolConfig, AegisSwapToken, AegisSwapTokenSymbol, AegisSwapUniswapV4Contracts, AegisSwapUniswapV4ContractsInput, AggregatedSwapDefaultTokenSymbol, AggregatedSwapToken, AggregatedSwapTokenSymbol, AggregatedSwapWolfGameTokenSymbol } from './config/index.js';
3
3
  export { assertUint128, buildExactInSwapTransaction, buildExactOutSwapTransaction, computePoolId, MAX_UINT128 } from './encoding.js';
4
4
  export type { BuiltSwapTransaction, ExecutionBatch, PermitBatch, PermitDetails, SignedPermitBatch, SwapOutputFee } from './encoding.js';
5
5
  export { getZeroForOne, outputFeeForQuote, quoteSpendAmount, reconcileSubmitQuote, sameQuote } from './quote.js';
6
6
  export type { DirectSwapQuote, ReconciledSubmitQuote, SwapQuoteMode } from './quote.js';
7
7
  export { AggregatedSwapBuildMismatchError, aggregatedSwapErrorMessage, fetchAggregatedSwapQuote } from './quote/aggregatedSwapQuote.js';
8
+ export type { AggregatedSwapExecutionIntent } from './quote/aggregatedSwapQuote.js';
8
9
  export { AggregatedSwapCalldataError } from './quote/kyberCalldata.js';
9
10
  export type { AggregatedSwapQuote, AggregatedSwapRoute, HopInfo } from './types/aggregatedSwap.js';
10
- export { KyberSwapApiError, KyberSwapContractError, buildKyberSwapRoute, fetchKyberSwapRoute, isRetryableKyberSwapError } from './services/kyberSwap.js';
11
+ export { KyberSwapApiError, KyberSwapContractError, KyberSwapResourceLimitError, buildKyberSwapRoute, fetchKyberSwapRoute, isRetryableKyberSwapError } from './services/kyberSwap.js';
11
12
  export type { KyberSwapBuild, KyberSwapError, KyberSwapFeeParams, KyberSwapRoute, KyberSwapRouteLeg, KyberSwapRouteSummary } from './services/kyberSwap.js';
12
- export { approveErc20Spender, approveErc20ToPermit2, approvePermit2ToRouter, buildSignedPermitBatch, DEFAULT_PERMIT_EXPIRATION_SECONDS, MAX_UINT160, MAX_UINT256, PERMIT2_FAR_FUTURE_EXPIRATION, readErc20Allowance, readPermit2RouterAllowance, SWAP_TX_DEADLINE_SECONDS } from './permit.js';
13
+ export { approveErc20Spender, approveErc20ToPermit2, approvePermit2ToRouter, buildSignedPermitBatch, DEFAULT_PERMIT_EXPIRATION_SECONDS, hasUsablePermit2Allowance, isUnlimitedErc20Approval, isUnlimitedPermit2Approval, MAX_UINT160, MAX_UINT256, PERMIT2_FAR_FUTURE_EXPIRATION, readErc20Allowance, readPermit2RouterAllowance, SWAP_TX_DEADLINE_SECONDS, UNLIMITED_ERC20_FLOOR, UNLIMITED_PERMIT2_FLOOR } from './permit.js';
13
14
  export { fetchGlobalTokenMetadata, resolveTokenIconUrl } from './metadata.js';
14
15
  export type { AegisSwapGlobalTokenMetadata, TokenMetadataByAddress } from './metadata.js';
15
- export { clearTokenPriceHistoryCache, fetchTokenPriceHistory, peekTokenPriceHistory } from './historicalPrices.js';
16
+ export { clearTokenPriceHistoryCache, fetchTokenPriceHistory, peekTokenPriceHistory, tokenPriceHistoryRestResponseSchema } from './historicalPrices.js';
16
17
  export type { AegisTokenPriceHistory, AegisTokenPriceHistoryStatus, AegisTokenPriceHistoryWindow, AegisTokenPricePoint } from './historicalPrices.js';
17
- export { createSwapPublicClient, getInjectedProvider, getProviderAccount, getProviderChainId, isEip1193Provider, normalizeAccount, normalizeWalletConnection, requestProviderAccount, subscribeProvider, switchProviderChain } from './wallet.js';
18
+ export { createSwapPublicClient, getInjectedProvider, getProviderAccount, getProviderChainId, isEip1193Provider, normalizeAccount, normalizeWalletConnection, requestProviderAccount, SDK_RPC_MULTICALL_RULE_ID, subscribeProvider, switchProviderChain } from './wallet.js';
18
19
  export type { AegisSwapProviderResolver, AegisSwapWalletConnection, Eip1193Provider, ProviderChainConfig } from './wallet.js';
19
20
  export { approveDirectPoolSwapInput, DirectPoolSwapPriceMovedError, executeDirectPoolSwap, fetchDirectPoolSwapQuote } from './actions/directPoolSwap.js';
20
21
  export type { DirectPoolSwapApprovalResult } from './actions/directPoolSwap.js';
21
22
  export { isNativeAssetAddress } from './address.js';
22
23
  export { approveKyberSwapInput, executeKyberSwap, isNativeToken, KyberSwapPriceMovedError, NATIVE_TOKEN_ADDRESS } from './actions/kyberSwap.js';
23
24
  export type { KyberSwapApprovalResult } from './actions/kyberSwap.js';
25
+ export { erc20ApprovalRequest, requiresErc20ApprovalReset } from './actions/allowance.js';
24
26
  export { ensureWalletChain, resolveWalletSession, waitForProviderChain } from './actions/wallet.js';
25
27
  export type { AegisSwapActionCallbacks, AegisSwapActionResult, AegisSwapApprovalProgress, AegisSwapApprovalRequest, AegisSwapAuthorizationProgress } from './actions/types.js';
26
28
  export { estimateSwapGasWithBuffer } from './swap/gas.js';
27
29
  export type { SwapGasRequest } from './swap/gas.js';
30
+ export { assertDirectSwapMarketTrusted, authorizeHostDirectSwapMarket, DIRECT_SWAP_MARKET_TRUST_RULE_ID, DirectSwapMarketTrustError, isDirectSwapMarketTrusted } from './swap/trustedMarket.js';
28
31
  export type { AegisSwapApprovalMode, AegisSwapSubmitDetails, WalletSession } from './swap/types.js';
29
32
  export { classifyError, errorMessage, isSubmittedTransactionReceiptError, isUserRejectedError, SubmittedTransactionReceiptError, TransactionReceiptTimeoutError, USER_REJECTED_MESSAGE, UserFacingError } from './errors.js';
30
33
  export type { ClassifiedError, UserFacingErrorKind } from './errors.js';
31
- export { isBusy, transactionProgressView } from './transactionProgress.js';
34
+ export { isBusy, progressRailSteps, transactionProgressView, transactionSequenceProgress } from './transactionProgress.js';
32
35
  export type { AegisSwapReceiptSummary, AegisSwapStatusSnapshot, AegisSwapStatusTransactionContext, AegisSwapStatusTransactionToken, AegisSwapWalletPromptProgress, SubmitStatus, TransactionProgressState, TransactionProgressView } from './transactionProgress.js';
33
36
  export { reconcileSubmittedReceipt } from './swap/receiptWait.js';
34
- export type { SubmittedReceiptOutcome } from './swap/receiptWait.js';
37
+ export type { SubmittedReceiptOutcome, AegisTransactionObservation } from './swap/receiptWait.js';
35
38
  export { summarizeTransactionReceipt } from './swap/sendSwapTransaction.js';
36
39
  export { isDocumentVisible, pollUntil, retryOnError } from './polling.js';
37
40
  export { AEGIS_BACKEND_PROD_BASE_URL, AegisBackendApiError, AegisBackendContractError, createAegisBackendApiClient, isRetryableAegisBackendApiError, normalizeAegisBackendBaseUrl } from './contract/backendClient.js';
@@ -40,4 +43,6 @@ export { backendTokenToAegisSwapToken, backendTokensToAegisSwapTokens, createAeg
40
43
  export type { AegisBackendAdapterSkip, AegisBackendAdapterSkipHandler, AegisBackendChainOptions } from './backendAdapters.js';
41
44
  export { aegisBackendAddressAllowlistSchema, aegisBackendAddressSchema, aegisBackendAllowlistsByChainSchema, aegisBackendChainSchema, aegisBackendChainIdSchema, aegisBackendConfigSchema, aegisBackendContractsByChainSchema, aegisBackendContractRegistrySchema, aegisBackendDecimalStringSchema, aegisBackendFeeConfigSchema, aegisBackendHealthResponseSchema, aegisBackendHexSchema, aegisBackendIsoDateTimeSchema, aegisBackendMarketMetricsSchema, aegisBackendMarketSchema, aegisBackendMarketStatusSchema, aegisBackendMarketsResponseSchema, aegisBackendQuoteDefaultsSchema, aegisBackendQuoteModeSchema, aegisBackendSwapProviderSchema, aegisBackendSwapQuoteRequestSchema, aegisBackendSwapQuoteResponseSchema, aegisBackendTokenSchema, aegisBackendTokensResponseSchema, aegisPoolKeySchema, AegisContractGuardError, assertCalldataHash, assertChainMatches, assertQuoteFresh, assertRouterAllowlisted, assertSpenderAllowlisted } from './contract/index.js';
42
45
  export type { AegisContractGuardCode } from './contract/index.js';
46
+ export { engineMarketsRestResponseSchema } from './engine/restSchemas.js';
43
47
  export * from './engine/index.js';
48
+ export { PortfolioQuerySchema, PortfolioPageQuerySchema, PortfolioResponseSchema, PortfolioPageSchema } from './engine/account/portfolioSchemas.js';
@@ -0,0 +1,31 @@
1
+ import type { Chain, Hex, PublicClient, TransactionReceipt } from 'viem';
2
+ import { type Eip1193Provider } from '../wallet.js';
3
+ import { type AegisTransactionObservation } from '../swap/receiptWait.js';
4
+ /**
5
+ * Sends one already-prepared wallet transaction through the safety boundary
6
+ * shared by swaps and authorization writes.
7
+ *
8
+ * Preparation and simulation stay with the caller. This helper owns the
9
+ * invariants that begin immediately before the wallet prompt: verify the
10
+ * active chain, honor cancellation until a hash exists, publish submitted and
11
+ * replacement hashes without trusting host callbacks, and reconcile the
12
+ * receipt. Once submitted, caller cancellation cannot hide the mined result.
13
+ */
14
+ export declare function runGuardedWalletTransaction(args: {
15
+ provider: Eip1193Provider;
16
+ publicClient: PublicClient;
17
+ chain: Chain;
18
+ signal?: AbortSignal;
19
+ timeoutMs: number;
20
+ submit: () => Promise<Hex>;
21
+ unreadableChainMessage: string;
22
+ cancelledMessage: string;
23
+ revertedMessage: string;
24
+ onWalletRequest?: () => void;
25
+ onHash?: (hash: Hex, replacement?: {
26
+ replacesHash: Hex;
27
+ executionChanged: boolean;
28
+ }) => void;
29
+ onTransactionObservation?: (event: AegisTransactionObservation) => void;
30
+ onSubmitted?: (hash: Hex) => void;
31
+ }): Promise<TransactionReceipt>;
package/dist/permit.d.ts CHANGED
@@ -1,8 +1,20 @@
1
1
  import { type Address, type Chain, type Hex, type PublicClient } from 'viem';
2
- import type { Eip1193Provider } from './wallet.js';
2
+ import { type Eip1193Provider } from './wallet.js';
3
3
  import type { SignedPermitBatch } from './encoding.js';
4
4
  export declare const MAX_UINT160: bigint;
5
5
  export declare const MAX_UINT256: bigint;
6
+ /** "No limit" only counts once the standing grant still reads as effectively
7
+ * unlimited. Half the type maximum tolerates tokens and Permit2 flows that
8
+ * decrement a max grant on spend — an equality test against the maximum would
9
+ * re-approve before every swap — while an exact-sized allowance, however large
10
+ * against today's amount, never qualifies. */
11
+ export declare const UNLIMITED_ERC20_FLOOR: bigint;
12
+ export declare const UNLIMITED_PERMIT2_FLOOR: bigint;
13
+ /** Whether an ERC-20 grant reads as "no limit" rather than a number worth
14
+ * showing — formatting the integer yields a quantity nobody can read. */
15
+ export declare function isUnlimitedErc20Approval(amount: bigint): boolean;
16
+ /** The Permit2 counterpart, against the uint160 wire type's own floor. */
17
+ export declare function isUnlimitedPermit2Approval(amount: bigint): boolean;
6
18
  export declare const SWAP_TX_DEADLINE_SECONDS = 600;
7
19
  export declare const DEFAULT_PERMIT_EXPIRATION_SECONDS: number;
8
20
  export declare const PERMIT2_FAR_FUTURE_EXPIRATION: number;
@@ -14,8 +26,14 @@ export declare function approveErc20ToPermit2(args: {
14
26
  token: Address;
15
27
  permit2: Address;
16
28
  amount?: bigint;
29
+ /** Stops preparation before the approval is handed to the wallet. */
30
+ signal?: AbortSignal;
17
31
  onWalletRequest?: () => void;
18
- onHash?: (hash: Hex) => void;
32
+ onHash?: (hash: Hex, replacement?: {
33
+ replacesHash: Hex;
34
+ executionChanged: boolean;
35
+ }) => void;
36
+ onSubmitted?: (hash: Hex) => void;
19
37
  }): Promise<Hex>;
20
38
  export declare function readErc20Allowance(args: {
21
39
  publicClient: PublicClient;
@@ -31,7 +49,24 @@ export declare function approveErc20Spender(args: {
31
49
  token: Address;
32
50
  spender: Address;
33
51
  amount?: bigint;
52
+ /** Stops preparation before the approval is handed to the wallet. */
53
+ signal?: AbortSignal;
54
+ onWalletRequest?: () => void;
55
+ onHash?: (hash: Hex, replacement?: {
56
+ replacesHash: Hex;
57
+ executionChanged: boolean;
58
+ }) => void;
59
+ onSubmitted?: (hash: Hex) => void;
34
60
  }): Promise<Hex>;
61
+ /**
62
+ * Installs a Permit2 -> router spending cap on-chain: the fallback for wallets
63
+ * whose typed-data signature Permit2 will not accept.
64
+ *
65
+ * `amount` follows the same convention as the ERC-20 writers above — omitted
66
+ * means maximum authority (MAX_UINT160), and an explicit `0n` revokes. Anything
67
+ * wider than the uint160 wire type is clamped. `expiration` defaults to
68
+ * Permit2's far-future sentinel.
69
+ */
35
70
  export declare function approvePermit2ToRouter(args: {
36
71
  provider: Eip1193Provider;
37
72
  publicClient: PublicClient;
@@ -42,8 +77,14 @@ export declare function approvePermit2ToRouter(args: {
42
77
  router: Address;
43
78
  amount?: bigint;
44
79
  expiration?: number;
80
+ /** Stops preparation before the approval is handed to the wallet. */
81
+ signal?: AbortSignal;
45
82
  onWalletRequest?: () => void;
46
- onHash?: (hash: Hex) => void;
83
+ onHash?: (hash: Hex, replacement?: {
84
+ replacesHash: Hex;
85
+ executionChanged: boolean;
86
+ }) => void;
87
+ onSubmitted?: (hash: Hex) => void;
47
88
  }): Promise<Hex>;
48
89
  export declare function readPermit2RouterAllowance(args: {
49
90
  publicClient: PublicClient;
@@ -52,7 +93,36 @@ export declare function readPermit2RouterAllowance(args: {
52
93
  token: Address;
53
94
  router: Address;
54
95
  }): Promise<readonly [amount: bigint, expiration: number, nonce: number]>;
55
- export declare function hasUsablePermit2Allowance(allowance: Awaited<ReturnType<typeof readPermit2RouterAllowance>>, amount: bigint): boolean;
96
+ export declare function hasUsablePermit2Allowance(allowance: Awaited<ReturnType<typeof readPermit2RouterAllowance>>, amount: bigint, sizing?: 'exact' | 'max'): boolean;
97
+ /**
98
+ * True only when Permit2's own `SignatureVerification` would accept this
99
+ * signature. It branches on the owner's code, not on the signature's shape: an
100
+ * address with code is checked through ERC-1271 alone, with no ecrecover
101
+ * fallback, so an EIP-7702-delegated EOA whose delegate does not implement
102
+ * `isValidSignature` rejects the ordinary 65-byte signature its own key just
103
+ * produced. A codeless owner takes the other branch and reverts on any length
104
+ * other than 64 or 65, which is where an ERC-6492 wrapper from an undeployed
105
+ * smart account dies.
106
+ *
107
+ * viem's `verifyTypedData` is used only for the codeless branch it models
108
+ * exactly, in `eoa` mode: its default `auto` mode opens with an `eth_call` that
109
+ * deploys viem's ERC-6492 validator, a blocking round trip sitting between the
110
+ * wallet signature and the submit on every ordinary swap.
111
+ *
112
+ * `false` means the owner refused, never "the check could not run": an RPC
113
+ * failure throws so the caller cannot mistake it for an unsignable wallet.
114
+ */
115
+ export declare function isPermit2AcceptableSignature(args: {
116
+ publicClient: PublicClient;
117
+ chainId: number;
118
+ permit2: Address;
119
+ signed: SignedPermitBatch;
120
+ /**
121
+ * The owner's deployed code, read by the caller so a failed read propagates
122
+ * instead of arriving here as a `false`.
123
+ */
124
+ ownerCode: Hex | undefined;
125
+ }): Promise<boolean>;
56
126
  export declare function buildSignedPermitBatch(args: {
57
127
  provider: Eip1193Provider;
58
128
  publicClient: PublicClient;
@@ -66,11 +136,15 @@ export declare function buildSignedPermitBatch(args: {
66
136
  /**
67
137
  * 'max' signs a MAX_UINT160 permit (still expiring in 30 minutes) so quick
68
138
  * follow-up swaps reuse it instead of prompting for a new signature each
69
- * time — Permit2 decrements exact-sized permits to zero on transfer.
70
- * Defaults to 'exact'.
139
+ * time — Permit2 decrements exact-sized permits to zero on transfer. It also
140
+ * re-signs over a merely amount-covering standing cap, because that cap is
141
+ * not the unlimited authority 'max' asked for. Defaults to 'exact'.
71
142
  */
72
143
  sizing?: 'exact' | 'max';
73
144
  /** Pre-started readPermit2RouterAllowance result to overlap with other RPC work. */
74
145
  allowanceRead?: ReturnType<typeof readPermit2RouterAllowance>;
146
+ /** Stops preparation before typed data is handed to the wallet. */
147
+ signal?: AbortSignal;
148
+ /** Fires only when a new typed-data signature is actually requested. */
75
149
  onWalletRequest?: () => void;
76
150
  }): Promise<SignedPermitBatch | null>;