@ocap/tx-pipeline 1.30.26 → 1.31.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 (149) hide show
  1. package/esm/appchain-sovereign-hub.d.mts +160 -0
  2. package/esm/appchain-sovereign-hub.mjs +348 -0
  3. package/esm/arcvault-external-adapter.d.mts +166 -0
  4. package/esm/arcvault-external-adapter.mjs +376 -0
  5. package/esm/encrypted-nft-envelope.d.mts +172 -0
  6. package/esm/encrypted-nft-envelope.mjs +458 -0
  7. package/esm/evm-simplified-bridge.d.mts +1370 -0
  8. package/esm/evm-simplified-bridge.mjs +3875 -0
  9. package/esm/give-to-mint-karma.d.mts +472 -0
  10. package/esm/give-to-mint-karma.mjs +1057 -0
  11. package/esm/helpers/replay-guard.d.mts +15 -0
  12. package/esm/helpers/replay-guard.mjs +23 -0
  13. package/esm/index.d.mts +10 -5
  14. package/esm/index.mjs +14 -10
  15. package/esm/legacy-protocol-sunset.d.mts +251 -0
  16. package/esm/legacy-protocol-sunset.mjs +1519 -0
  17. package/esm/library.d.mts +16 -0
  18. package/esm/library.mjs +17 -0
  19. package/esm/native-abt-exchange.d.mts +2055 -0
  20. package/esm/native-abt-exchange.mjs +7250 -0
  21. package/esm/ofac-screening.d.mts +17 -0
  22. package/esm/ofac-screening.mjs +39 -0
  23. package/esm/pipes/anti-land-attack.mjs +1 -1
  24. package/esm/pipes/decode-itx.mjs +43 -4
  25. package/esm/pipes/decode-tx.d.mts +2 -3
  26. package/esm/pipes/decode-tx.mjs +53 -115
  27. package/esm/pipes/extract-signer.mjs +2 -2
  28. package/esm/pipes/extract-state.mjs +14 -3
  29. package/esm/pipes/post-execution-invariant-gate.d.mts +61 -0
  30. package/esm/pipes/post-execution-invariant-gate.mjs +789 -0
  31. package/esm/pipes/pre-flight-waf.d.mts +34 -0
  32. package/esm/pipes/pre-flight-waf.mjs +603 -0
  33. package/esm/pipes/take-state-snapshot.mjs +3 -2
  34. package/esm/pipes/update-owner.mjs +39 -4
  35. package/esm/pipes/verify-account-migration.mjs +14 -4
  36. package/esm/pipes/verify-blocked.mjs +1 -1
  37. package/esm/pipes/verify-delegation.d.mts +22 -3
  38. package/esm/pipes/verify-delegation.mjs +259 -36
  39. package/esm/pipes/verify-list-size.mjs +1 -1
  40. package/esm/pipes/verify-multisig-v2.mjs +15 -7
  41. package/esm/pipes/verify-multisig.mjs +15 -7
  42. package/esm/pipes/verify-sender.mjs +1 -1
  43. package/esm/pipes/verify-signature.mjs +35 -6
  44. package/esm/pipes/verify-signer.mjs +2 -2
  45. package/esm/pipes/verify-state-diff.mjs +3 -3
  46. package/esm/pipes/verify-token-access.mjs +1 -1
  47. package/esm/pipes/verify-token-balance.mjs +13 -5
  48. package/esm/pipes/verify-transferrable.d.mts +8 -1
  49. package/esm/pipes/verify-transferrable.mjs +3 -3
  50. package/esm/pipes/verify-tx-input.mjs +2 -2
  51. package/esm/pipes/verify-tx-size.mjs +46 -2
  52. package/esm/pipes/verify-tx.mjs +5 -7
  53. package/esm/pipes/verify-updater.mjs +1 -1
  54. package/esm/social-economy-factories.d.mts +346 -0
  55. package/esm/social-economy-factories.mjs +845 -0
  56. package/esm/super-suites-foundation.d.mts +513 -0
  57. package/esm/super-suites-foundation.mjs +1241 -0
  58. package/esm/transaction-block.d.mts +471 -0
  59. package/esm/transaction-block.mjs +1906 -0
  60. package/esm/uniswap-erc7683-solver.d.mts +201 -0
  61. package/esm/uniswap-erc7683-solver.mjs +321 -0
  62. package/esm/uniswap-lp-copilot.d.mts +113 -0
  63. package/esm/uniswap-lp-copilot.mjs +320 -0
  64. package/esm/uniswap-router.d.mts +335 -0
  65. package/esm/uniswap-router.mjs +578 -0
  66. package/esm/uniswap-token-factory-graduation.d.mts +187 -0
  67. package/esm/uniswap-token-factory-graduation.mjs +426 -0
  68. package/esm/uniswap-v4-hook.d.mts +173 -0
  69. package/esm/uniswap-v4-hook.mjs +517 -0
  70. package/lib/appchain-sovereign-hub.cjs +352 -0
  71. package/lib/appchain-sovereign-hub.d.cts +160 -0
  72. package/lib/arcvault-external-adapter.cjs +383 -0
  73. package/lib/arcvault-external-adapter.d.cts +166 -0
  74. package/lib/encrypted-nft-envelope.cjs +477 -0
  75. package/lib/encrypted-nft-envelope.d.cts +172 -0
  76. package/lib/evm-simplified-bridge.cjs +3943 -0
  77. package/lib/evm-simplified-bridge.d.cts +1370 -0
  78. package/lib/give-to-mint-karma.cjs +1084 -0
  79. package/lib/give-to-mint-karma.d.cts +472 -0
  80. package/lib/helpers/replay-guard.cjs +27 -0
  81. package/lib/helpers/replay-guard.d.cts +15 -0
  82. package/lib/index.cjs +49 -16
  83. package/lib/index.d.cts +10 -5
  84. package/lib/legacy-protocol-sunset.cjs +1543 -0
  85. package/lib/legacy-protocol-sunset.d.cts +251 -0
  86. package/lib/library.cjs +303 -0
  87. package/lib/library.d.cts +16 -0
  88. package/lib/native-abt-exchange.cjs +7322 -0
  89. package/lib/native-abt-exchange.d.cts +2055 -0
  90. package/lib/ofac-screening.cjs +42 -0
  91. package/lib/ofac-screening.d.cts +17 -0
  92. package/lib/pipes/anti-land-attack.cjs +2 -2
  93. package/lib/pipes/decode-itx.cjs +43 -4
  94. package/lib/pipes/decode-itx.d.cts +1 -1
  95. package/lib/pipes/decode-tx.cjs +52 -116
  96. package/lib/pipes/decode-tx.d.cts +3 -4
  97. package/lib/pipes/extract-signer.cjs +2 -2
  98. package/lib/pipes/extract-state.cjs +14 -3
  99. package/lib/pipes/post-execution-invariant-gate.cjs +800 -0
  100. package/lib/pipes/post-execution-invariant-gate.d.cts +61 -0
  101. package/lib/pipes/pre-flight-waf.cjs +616 -0
  102. package/lib/pipes/pre-flight-waf.d.cts +34 -0
  103. package/lib/pipes/take-state-snapshot.cjs +3 -2
  104. package/lib/pipes/update-owner.cjs +40 -5
  105. package/lib/pipes/update-owner.d.cts +1 -1
  106. package/lib/pipes/verify-account-migration.cjs +14 -4
  107. package/lib/pipes/verify-blocked.cjs +1 -1
  108. package/lib/pipes/verify-delegation.cjs +259 -36
  109. package/lib/pipes/verify-delegation.d.cts +22 -3
  110. package/lib/pipes/verify-list-size.cjs +1 -1
  111. package/lib/pipes/verify-multisig-v2.cjs +15 -7
  112. package/lib/pipes/verify-multisig.cjs +15 -7
  113. package/lib/pipes/verify-sender.cjs +1 -1
  114. package/lib/pipes/verify-service-fee.d.cts +1 -1
  115. package/lib/pipes/verify-signature.cjs +35 -6
  116. package/lib/pipes/verify-signature.d.cts +1 -1
  117. package/lib/pipes/verify-signer.cjs +2 -2
  118. package/lib/pipes/verify-state-diff.cjs +4 -4
  119. package/lib/pipes/verify-token-access.cjs +2 -2
  120. package/lib/pipes/verify-token-balance.cjs +13 -5
  121. package/lib/pipes/verify-transferrable.cjs +3 -3
  122. package/lib/pipes/verify-transferrable.d.cts +8 -1
  123. package/lib/pipes/verify-tx-input.cjs +3 -3
  124. package/lib/pipes/verify-tx-size.cjs +46 -2
  125. package/lib/pipes/verify-tx-size.d.cts +1 -1
  126. package/lib/pipes/verify-tx.cjs +6 -8
  127. package/lib/pipes/verify-tx.d.cts +1 -1
  128. package/lib/pipes/verify-updater.cjs +1 -1
  129. package/lib/social-economy-factories.cjs +852 -0
  130. package/lib/social-economy-factories.d.cts +346 -0
  131. package/lib/super-suites-foundation.cjs +1257 -0
  132. package/lib/super-suites-foundation.d.cts +513 -0
  133. package/lib/transaction-block.cjs +1941 -0
  134. package/lib/transaction-block.d.cts +471 -0
  135. package/lib/uniswap-erc7683-solver.cjs +327 -0
  136. package/lib/uniswap-erc7683-solver.d.cts +201 -0
  137. package/lib/uniswap-lp-copilot.cjs +328 -0
  138. package/lib/uniswap-lp-copilot.d.cts +113 -0
  139. package/lib/uniswap-router.cjs +593 -0
  140. package/lib/uniswap-router.d.cts +335 -0
  141. package/lib/uniswap-token-factory-graduation.cjs +431 -0
  142. package/lib/uniswap-token-factory-graduation.d.cts +187 -0
  143. package/lib/uniswap-v4-hook.cjs +527 -0
  144. package/lib/uniswap-v4-hook.d.cts +173 -0
  145. package/package.json +11 -10
  146. package/esm/helpers/dedup-height.d.mts +0 -16
  147. package/esm/helpers/dedup-height.mjs +0 -61
  148. package/lib/helpers/dedup-height.cjs +0 -72
  149. package/lib/helpers/dedup-height.d.cts +0 -16
@@ -0,0 +1,201 @@
1
+ import { PendingTransferRecord, TwoPhaseTransferLedger } from "./transaction-block.mjs";
2
+
3
+ //#region src/uniswap-erc7683-solver.d.ts
4
+
5
+ /**
6
+ * Maximum number of OCAP blocks an ERC-7683 intent can lock Solver sub-vault funds (`<= 30` blocks).
7
+ */
8
+ declare const MAX_INTENT_TIMEOUT_BLOCKS = 30;
9
+ /**
10
+ * Maximum concurrent `PENDING` intents allowed per user address to prevent Solver liquidity exhaustion.
11
+ */
12
+ declare const MAX_ACTIVE_INTENTS_PER_USER = 3;
13
+ /**
14
+ * Default maximum number of expired intents swept per block (`<= 50`) to bound per-block GC gas/latency.
15
+ */
16
+ declare const DEFAULT_MAX_SWEEP_BATCH_SIZE = 50;
17
+ /**
18
+ * Minimum recommended Solver sub-vault shards for parallel Sealevel / 2PC execution.
19
+ */
20
+ declare const MIN_RECOMMENDED_SOLVER_SHARDS = 16;
21
+ /**
22
+ * Standard ERC-7683 Output specification (`maxSpent` / `minReceived` item).
23
+ */
24
+ interface Erc7683Output {
25
+ token: string;
26
+ amount: string;
27
+ recipient: string;
28
+ chainId: number;
29
+ }
30
+ /**
31
+ * Standard ERC-7683 FillInstruction item.
32
+ */
33
+ interface Erc7683FillInstruction {
34
+ destinationChainId: number;
35
+ destinationSettler: string;
36
+ originData: string;
37
+ }
38
+ /**
39
+ * Standard ERC-7683 `ResolvedCrossChainOrder` structure mapped between EVM (UniswapX / Base / Arbitrum)
40
+ * and OCAP (`TwoPhaseTransferLedger` + `#1169` Rollup Evidence).
41
+ */
42
+ interface Erc7683ResolvedCrossChainOrder {
43
+ orderId: string;
44
+ user: string;
45
+ originChainId: number;
46
+ openDeadline: number;
47
+ fillDeadline: number;
48
+ maxSpent: Erc7683Output[];
49
+ minReceived: Erc7683Output[];
50
+ fillInstructions: Erc7683FillInstruction[];
51
+ }
52
+ /**
53
+ * Proof that the user has already escrowed input tokens on the origin chain (`Permit2` / `InputSettler`)
54
+ * before the OCAP Solver locks destination sub-vault liquidity ("Source-Escrow First" anti-griefing rule).
55
+ */
56
+ interface OriginEscrowProof {
57
+ originChainId: number;
58
+ sourceEscrowTxHash: string;
59
+ escrowContractAddress: string;
60
+ escrowedToken: string;
61
+ escrowedAmount: string;
62
+ escrowRecipient?: string;
63
+ confirmations: number;
64
+ minRequiredConfirmations?: number;
65
+ }
66
+ /**
67
+ * Cryptographic settlement proof (`#1169` Rollup Evidence / Destination Settler Receipt)
68
+ * required to finalize (`POST`) a `PENDING` ERC-7683 transfer.
69
+ */
70
+ interface CrossChainSettlementProof {
71
+ orderId: string;
72
+ evidenceHash: string;
73
+ originEscrowTxHash: string;
74
+ destinationFillTxHash: string;
75
+ settledAmount: string;
76
+ settledRecipient: string;
77
+ settledToken: string;
78
+ rollupVerified: boolean;
79
+ }
80
+ type SolverExecutionMode = 'AGENCY_PASS_THROUGH' | 'EXTERNAL_THIRD_PARTY_FILLER';
81
+ interface SolverEngineConfig {
82
+ /** Open permissionless filler DID operating this Solver instance */
83
+ fillerDid: string;
84
+ /** Sharded sub-vault account addresses to eliminate 2PC single-account lock contention */
85
+ solverSubVaultShards: string[];
86
+ /** Execution mode: 'AGENCY_PASS_THROUGH' enforces 0 bps proprietary spread for ABT utility routing */
87
+ executionMode: SolverExecutionMode;
88
+ /** Optional ABT token address to strictly enforce AGENCY_PASS_THROUGH zero-spread rules */
89
+ abtTokenAddress?: string;
90
+ /** Maximum blocks an intent can stay PENDING before expiring (`<= 30`) */
91
+ maxTimeoutBlocks?: number;
92
+ /** Maximum concurrent PENDING intents per user (`<= 3`) */
93
+ maxActiveIntentsPerUser?: number;
94
+ /** Maximum intents swept per block in `sweepExpiredIntents` (`<= 50`) */
95
+ maxSweepBatchSize?: number;
96
+ /** `#1169` Canary net-inflow cap per epoch in base units */
97
+ maxEpochNetInflowCap: string;
98
+ /** Minimum origin-chain confirmations before locking Solver liquidity */
99
+ minOriginConfirmations?: number;
100
+ ofacBlocklist?: Iterable<string>;
101
+ }
102
+ interface ManagedIntentRecord {
103
+ orderId: string;
104
+ user: string;
105
+ fillerDid: string;
106
+ shardAddress: string;
107
+ destinationRecipient: string;
108
+ destinationToken: string;
109
+ destinationAmount: string;
110
+ originChainId: number;
111
+ originEscrowTxHash: string;
112
+ createdAtHeight: number;
113
+ timeoutHeight: number;
114
+ executionMode: SolverExecutionMode;
115
+ solverSpreadBps: number;
116
+ status: 'PENDING' | 'POSTED' | 'VOIDED';
117
+ settlementEvidenceHash?: string;
118
+ }
119
+ /**
120
+ * Deterministically selects a Solver sub-vault shard (`0 .. shards.length - 1`) for an `orderId`
121
+ * so concurrent ERC-7683 fills touch disjoint account state keys in `OverlayStateDB` / `2PC`.
122
+ */
123
+ declare function selectSolverSubVaultShard(orderId: string, shards: string[]): {
124
+ shardIndex: number;
125
+ shardAddress: string;
126
+ };
127
+ /**
128
+ * Non-Custodial UniswapX / ERC-7683 Cross-Chain Intent Solver Engine (`OcapErc7683SolverEngine`).
129
+ *
130
+ * Security, Anti-Vampire & Regulatory Guarantees:
131
+ * 1. **Sharded Solver Vaults**: Routes intents across independent sub-vault shards to eliminate
132
+ * single-vault `LOCK_CONFLICT` bottlenecks during parallel block execution.
133
+ * 2. **Source-Escrow First & Short Timeout Cap (`<= 30` blocks)**: Requires verified origin-chain
134
+ * escrow proof before locking destination liquidity, caps per-user active intents (`<= 3`),
135
+ * and provides paginated `sweepExpiredIntents` rollback (`VOID`).
136
+ * 3. **Canary Net-Inflow Circuit Breaker**: Enforces `#1169` epoch net-inflow watermark limits.
137
+ * 4. **SEC Section 15(a)(2) Dealer Rule & FinCEN Safe Harbor**: Supports open permissionless external
138
+ * fillers and enforces `0 bps` proprietary spread in `AGENCY_PASS_THROUGH` mode (especially for `ABT`).
139
+ */
140
+ declare class OcapErc7683SolverEngine {
141
+ readonly config: Required<Pick<SolverEngineConfig, 'fillerDid' | 'solverSubVaultShards' | 'executionMode' | 'maxTimeoutBlocks' | 'maxActiveIntentsPerUser' | 'maxSweepBatchSize' | 'maxEpochNetInflowCap' | 'minOriginConfirmations'>> & {
142
+ abtTokenAddress?: string;
143
+ };
144
+ private readonly ledger;
145
+ private readonly intents;
146
+ private readonly usedOriginEscrowTxs;
147
+ private readonly usedSettlementEvidences;
148
+ private readonly usedDestinationFillTxs;
149
+ private readonly ofacSet;
150
+ private currentEpochNetInflow;
151
+ constructor(config: SolverEngineConfig, ledger?: TwoPhaseTransferLedger);
152
+ /**
153
+ * Phase 1 (`PREPARE / PENDING`):
154
+ * Validates an ERC-7683 `ResolvedCrossChainOrder` and its origin-chain escrow proof, checks OFAC,
155
+ * SEC Dealer / Agency pass-through rules, per-user active intent quota, and Canary net-inflow cap,
156
+ * then locks destination funds in the selected Solver sub-vault shard via `TwoPhaseTransferLedger`.
157
+ */
158
+ prepareIntentFill(params: {
159
+ order: Erc7683ResolvedCrossChainOrder;
160
+ originEscrowProof: OriginEscrowProof;
161
+ currentHeight: number;
162
+ timeoutBlocks?: number;
163
+ currentUnixTimestamp?: number;
164
+ solverSpreadBps?: number;
165
+ ofacBlocklist?: Iterable<string>;
166
+ }, statedb: Record<string, any>): Promise<{
167
+ intent: ManagedIntentRecord;
168
+ pendingTransfer: PendingTransferRecord;
169
+ }>;
170
+ /**
171
+ * Phase 2A (`POST / SETTLE`):
172
+ * Verifies `#1169` cross-chain Rollup settlement evidence and posts the `PENDING` transfer
173
+ * from the Solver sub-vault shard to the destination recipient.
174
+ */
175
+ settleIntentFill(params: {
176
+ settlementProof: CrossChainSettlementProof;
177
+ currentHeight: number;
178
+ }, statedb: Record<string, any>): Promise<{
179
+ intent: ManagedIntentRecord;
180
+ postedTransfer: PendingTransferRecord;
181
+ }>;
182
+ /**
183
+ * Phase 2B (`VOID / PAGINATED ROLLBACK SWEEP`):
184
+ * Sweeps up to `maxBatchSize` expired `PENDING` intents (`currentHeight > intent.timeoutHeight`),
185
+ * returning locked `pendingTokens` back to the Solver sub-vault shard's available `tokens`
186
+ * and releasing the reserved Canary net-inflow quota.
187
+ */
188
+ sweepExpiredIntents(params: {
189
+ currentHeight: number;
190
+ maxBatchSize?: number;
191
+ }, statedb: Record<string, any>): Promise<{
192
+ sweptOrderIds: string[];
193
+ failedOrderIds: string[];
194
+ remainingExpiredCount: number;
195
+ }>;
196
+ getIntent(orderId: string): ManagedIntentRecord | undefined;
197
+ getCurrentEpochNetInflow(): string;
198
+ resetEpochNetInflow(): void;
199
+ }
200
+ //#endregion
201
+ export { CrossChainSettlementProof, DEFAULT_MAX_SWEEP_BATCH_SIZE, Erc7683FillInstruction, Erc7683Output, Erc7683ResolvedCrossChainOrder, MAX_ACTIVE_INTENTS_PER_USER, MAX_INTENT_TIMEOUT_BLOCKS, MIN_RECOMMENDED_SOLVER_SHARDS, ManagedIntentRecord, OcapErc7683SolverEngine, OriginEscrowProof, SolverEngineConfig, SolverExecutionMode, selectSolverSubVaultShard };
@@ -0,0 +1,321 @@
1
+ import { assertNotOfacSanctioned, normalizeScreeningAddress } from "./ofac-screening.mjs";
2
+ import "./uniswap-router.mjs";
3
+ import { TwoPhaseTransferLedger } from "./transaction-block.mjs";
4
+ import { Hasher } from "@ocap/mcrypto";
5
+ import { BN } from "@ocap/util";
6
+ import { CustomError } from "@ocap/util/lib/error";
7
+
8
+ //#region src/uniswap-erc7683-solver.ts
9
+ /**
10
+ * Maximum number of OCAP blocks an ERC-7683 intent can lock Solver sub-vault funds (`<= 30` blocks).
11
+ */
12
+ const MAX_INTENT_TIMEOUT_BLOCKS = 30;
13
+ /**
14
+ * Maximum concurrent `PENDING` intents allowed per user address to prevent Solver liquidity exhaustion.
15
+ */
16
+ const MAX_ACTIVE_INTENTS_PER_USER = 3;
17
+ /**
18
+ * Default maximum number of expired intents swept per block (`<= 50`) to bound per-block GC gas/latency.
19
+ */
20
+ const DEFAULT_MAX_SWEEP_BATCH_SIZE = 50;
21
+ /**
22
+ * Minimum recommended Solver sub-vault shards for parallel Sealevel / 2PC execution.
23
+ */
24
+ const MIN_RECOMMENDED_SOLVER_SHARDS = 16;
25
+ const FORBIDDEN_KEYS = new Set([
26
+ "__proto__",
27
+ "constructor",
28
+ "prototype"
29
+ ]);
30
+ const CANONICAL_UINT_REGEX = /^\d+$/;
31
+ const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
32
+ function assertSafeId(val, label) {
33
+ if (typeof val !== "string") throw new CustomError("INVALID_ERC7683_ORDER", `${label} must be a non-empty string`);
34
+ const trimmed = val.trim();
35
+ if (!trimmed || FORBIDDEN_KEYS.has(trimmed)) throw new CustomError("INVALID_ERC7683_ORDER", `Invalid or unsafe ${label}`);
36
+ return trimmed;
37
+ }
38
+ function parsePositiveBn(val, label) {
39
+ if (typeof val !== "string" || !CANONICAL_UINT_REGEX.test(val)) throw new CustomError("INVALID_ERC7683_ORDER", `${label} must be a canonical base-10 integer string`);
40
+ const bn = new BN(val, 10);
41
+ if (bn.lte(new BN(0))) throw new CustomError("INVALID_ERC7683_ORDER", `${label} must be strictly positive`);
42
+ return bn;
43
+ }
44
+ function parseNonNegativeBn(val, label) {
45
+ if (typeof val !== "string" || !CANONICAL_UINT_REGEX.test(val)) throw new CustomError("INVALID_ERC7683_ORDER", `${label} must be a canonical non-negative integer string`);
46
+ return new BN(val, 10);
47
+ }
48
+ /**
49
+ * Deterministically selects a Solver sub-vault shard (`0 .. shards.length - 1`) for an `orderId`
50
+ * so concurrent ERC-7683 fills touch disjoint account state keys in `OverlayStateDB` / `2PC`.
51
+ */
52
+ function selectSolverSubVaultShard(orderId, shards) {
53
+ const safeOrderId = assertSafeId(orderId, "orderId");
54
+ if (!Array.isArray(shards) || shards.length === 0) throw new CustomError("INVALID_ERC7683_SOLVER", "solverSubVaultShards must be a non-empty array");
55
+ const digest = Hasher.SHA3.hash256(Buffer.from(safeOrderId, "utf8")).replace(/^0x/, "");
56
+ const shardIndex = Number.parseInt(digest.slice(0, 8), 16) % shards.length;
57
+ return {
58
+ shardIndex,
59
+ shardAddress: assertSafeId(shards[shardIndex], `solverSubVaultShards[${shardIndex}]`)
60
+ };
61
+ }
62
+ /**
63
+ * Non-Custodial UniswapX / ERC-7683 Cross-Chain Intent Solver Engine (`OcapErc7683SolverEngine`).
64
+ *
65
+ * Security, Anti-Vampire & Regulatory Guarantees:
66
+ * 1. **Sharded Solver Vaults**: Routes intents across independent sub-vault shards to eliminate
67
+ * single-vault `LOCK_CONFLICT` bottlenecks during parallel block execution.
68
+ * 2. **Source-Escrow First & Short Timeout Cap (`<= 30` blocks)**: Requires verified origin-chain
69
+ * escrow proof before locking destination liquidity, caps per-user active intents (`<= 3`),
70
+ * and provides paginated `sweepExpiredIntents` rollback (`VOID`).
71
+ * 3. **Canary Net-Inflow Circuit Breaker**: Enforces `#1169` epoch net-inflow watermark limits.
72
+ * 4. **SEC Section 15(a)(2) Dealer Rule & FinCEN Safe Harbor**: Supports open permissionless external
73
+ * fillers and enforces `0 bps` proprietary spread in `AGENCY_PASS_THROUGH` mode (especially for `ABT`).
74
+ */
75
+ var OcapErc7683SolverEngine = class {
76
+ constructor(config, ledger) {
77
+ this.intents = /* @__PURE__ */ new Map();
78
+ this.usedOriginEscrowTxs = /* @__PURE__ */ new Set();
79
+ this.usedSettlementEvidences = /* @__PURE__ */ new Set();
80
+ this.usedDestinationFillTxs = /* @__PURE__ */ new Set();
81
+ this.ofacSet = /* @__PURE__ */ new Set();
82
+ this.currentEpochNetInflow = new BN(0);
83
+ if (!config || typeof config !== "object") throw new CustomError("INVALID_ERC7683_SOLVER", "Missing SolverEngineConfig");
84
+ const fillerDid = normalizeScreeningAddress(assertSafeId(config.fillerDid, "fillerDid"));
85
+ if (!Array.isArray(config.solverSubVaultShards) || config.solverSubVaultShards.length === 0) throw new CustomError("INVALID_ERC7683_SOLVER", "solverSubVaultShards must contain at least 1 shard address");
86
+ const normalizedShards = config.solverSubVaultShards.map((s, idx) => normalizeScreeningAddress(assertSafeId(s, `solverSubVaultShards[${idx}]`)));
87
+ if (new Set(normalizedShards).size !== normalizedShards.length) throw new CustomError("INVALID_ERC7683_SOLVER", "solverSubVaultShards must not contain duplicate shard addresses");
88
+ if (config.executionMode !== "AGENCY_PASS_THROUGH" && config.executionMode !== "EXTERNAL_THIRD_PARTY_FILLER") throw new CustomError("INVALID_ERC7683_SOLVER", `Unsupported executionMode: ${String(config.executionMode)}`);
89
+ const maxTimeoutBlocks = config.maxTimeoutBlocks ?? MAX_INTENT_TIMEOUT_BLOCKS;
90
+ if (typeof maxTimeoutBlocks !== "number" || !Number.isSafeInteger(maxTimeoutBlocks) || maxTimeoutBlocks <= 0 || maxTimeoutBlocks > MAX_INTENT_TIMEOUT_BLOCKS) throw new CustomError("INVALID_ERC7683_SOLVER", `maxTimeoutBlocks must be an integer between 1 and ${MAX_INTENT_TIMEOUT_BLOCKS}`);
91
+ const maxActiveIntentsPerUser = config.maxActiveIntentsPerUser ?? MAX_ACTIVE_INTENTS_PER_USER;
92
+ if (typeof maxActiveIntentsPerUser !== "number" || !Number.isSafeInteger(maxActiveIntentsPerUser) || maxActiveIntentsPerUser <= 0 || maxActiveIntentsPerUser > MAX_ACTIVE_INTENTS_PER_USER) throw new CustomError("INVALID_ERC7683_SOLVER", `maxActiveIntentsPerUser must be an integer between 1 and ${MAX_ACTIVE_INTENTS_PER_USER}`);
93
+ const maxSweepBatchSize = config.maxSweepBatchSize ?? DEFAULT_MAX_SWEEP_BATCH_SIZE;
94
+ if (typeof maxSweepBatchSize !== "number" || !Number.isSafeInteger(maxSweepBatchSize) || maxSweepBatchSize <= 0 || maxSweepBatchSize > 500) throw new CustomError("INVALID_ERC7683_SOLVER", "maxSweepBatchSize must be an integer between 1 and 500");
95
+ const maxEpochNetInflowCapBn = parsePositiveBn(config.maxEpochNetInflowCap, "maxEpochNetInflowCap");
96
+ const minOriginConfirmations = config.minOriginConfirmations ?? 2;
97
+ if (typeof minOriginConfirmations !== "number" || !Number.isSafeInteger(minOriginConfirmations) || minOriginConfirmations < 1) throw new CustomError("INVALID_ERC7683_SOLVER", "minOriginConfirmations must be an integer >= 1");
98
+ if (config.ofacBlocklist) for (const item of config.ofacBlocklist) this.ofacSet.add(normalizeScreeningAddress(item));
99
+ const abtTokenAddress = config.abtTokenAddress ? normalizeScreeningAddress(assertSafeId(config.abtTokenAddress, "abtTokenAddress")) : void 0;
100
+ assertNotOfacSanctioned([
101
+ fillerDid,
102
+ ...normalizedShards,
103
+ ...abtTokenAddress ? [abtTokenAddress] : []
104
+ ], this.ofacSet);
105
+ this.config = {
106
+ fillerDid,
107
+ solverSubVaultShards: normalizedShards,
108
+ executionMode: config.executionMode,
109
+ abtTokenAddress,
110
+ maxTimeoutBlocks,
111
+ maxActiveIntentsPerUser,
112
+ maxSweepBatchSize,
113
+ maxEpochNetInflowCap: maxEpochNetInflowCapBn.toString(10),
114
+ minOriginConfirmations
115
+ };
116
+ this.ledger = ledger || new TwoPhaseTransferLedger();
117
+ }
118
+ /**
119
+ * Phase 1 (`PREPARE / PENDING`):
120
+ * Validates an ERC-7683 `ResolvedCrossChainOrder` and its origin-chain escrow proof, checks OFAC,
121
+ * SEC Dealer / Agency pass-through rules, per-user active intent quota, and Canary net-inflow cap,
122
+ * then locks destination funds in the selected Solver sub-vault shard via `TwoPhaseTransferLedger`.
123
+ */
124
+ async prepareIntentFill(params, statedb) {
125
+ if (!params || typeof params !== "object" || !params.order || !params.originEscrowProof) throw new CustomError("INVALID_ERC7683_ORDER", "Missing order or originEscrowProof");
126
+ const { order, originEscrowProof } = params;
127
+ const orderId = assertSafeId(order.orderId, "order.orderId");
128
+ if (this.intents.has(orderId)) throw new CustomError("DUPLICATE_ERC7683_ORDER", `ERC-7683 order ${orderId} is already registered`);
129
+ const user = normalizeScreeningAddress(assertSafeId(order.user, "order.user"));
130
+ if (typeof order.originChainId !== "number" || !Number.isSafeInteger(order.originChainId) || order.originChainId <= 0) throw new CustomError("INVALID_ERC7683_ORDER", "order.originChainId must be a positive safe integer");
131
+ if (typeof order.openDeadline !== "number" || !Number.isSafeInteger(order.openDeadline) || order.openDeadline <= 0 || typeof order.fillDeadline !== "number" || !Number.isSafeInteger(order.fillDeadline) || order.fillDeadline < order.openDeadline) throw new CustomError("INVALID_ERC7683_ORDER", "order.openDeadline and order.fillDeadline must be positive safe integers with fillDeadline >= openDeadline");
132
+ if (!Array.isArray(order.maxSpent) || order.maxSpent.length !== 1) throw new CustomError("INVALID_ERC7683_ORDER", "order.maxSpent must contain exactly 1 atomic output");
133
+ if (!Array.isArray(order.minReceived) || order.minReceived.length !== 1) throw new CustomError("INVALID_ERC7683_ORDER", "order.minReceived must contain exactly 1 atomic output");
134
+ if (!Array.isArray(order.fillInstructions) || order.fillInstructions.length !== 1) throw new CustomError("INVALID_ERC7683_ORDER", "order.fillInstructions must contain exactly 1 instruction");
135
+ const spentSpec = order.maxSpent[0];
136
+ const receivedSpec = order.minReceived[0];
137
+ const fillInstruction = order.fillInstructions[0];
138
+ if (spentSpec.chainId !== order.originChainId) throw new CustomError("INVALID_ERC7683_ORDER", `maxSpent[0].chainId (${spentSpec.chainId}) must match order.originChainId (${order.originChainId})`);
139
+ if (typeof receivedSpec.chainId !== "number" || !Number.isSafeInteger(receivedSpec.chainId) || receivedSpec.chainId <= 0 || receivedSpec.chainId !== fillInstruction.destinationChainId || receivedSpec.chainId === order.originChainId) throw new CustomError("INVALID_ERC7683_ORDER", "minReceived[0].chainId must match fillInstructions[0].destinationChainId and differ from originChainId");
140
+ const destinationSettler = normalizeScreeningAddress(assertSafeId(fillInstruction.destinationSettler, "fillInstructions[0].destinationSettler"));
141
+ const spentToken = normalizeScreeningAddress(assertSafeId(spentSpec.token, "maxSpent[0].token"));
142
+ const spentRecipient = normalizeScreeningAddress(assertSafeId(spentSpec.recipient, "maxSpent[0].recipient"));
143
+ const maxSpentAmountBn = parsePositiveBn(spentSpec.amount, "maxSpent[0].amount");
144
+ if (spentRecipient !== this.config.fillerDid && !this.config.solverSubVaultShards.includes(spentRecipient)) throw new CustomError("INVALID_ORIGIN_ESCROW_RECIPIENT", `maxSpent[0].recipient (${spentRecipient}) must be bound to Solver fillerDid (${this.config.fillerDid}) or an authorized Solver shard`);
145
+ const destToken = normalizeScreeningAddress(assertSafeId(receivedSpec.token, "minReceived[0].token"));
146
+ const destRecipient = normalizeScreeningAddress(assertSafeId(receivedSpec.recipient, "minReceived[0].recipient"));
147
+ const destAmountBn = parsePositiveBn(receivedSpec.amount, "minReceived[0].amount");
148
+ if (destRecipient === this.config.fillerDid || this.config.solverSubVaultShards.includes(destRecipient)) throw new CustomError("INVALID_DESTINATION_RECIPIENT", `minReceived[0].recipient (${destRecipient}) cannot be a Solver fillerDid or sub-vault shard`);
149
+ const combinedOfac = new Set(this.ofacSet);
150
+ if (params.ofacBlocklist) for (const a of params.ofacBlocklist) combinedOfac.add(normalizeScreeningAddress(a));
151
+ assertNotOfacSanctioned([
152
+ user,
153
+ spentToken,
154
+ spentRecipient,
155
+ destToken,
156
+ destRecipient,
157
+ destinationSettler,
158
+ originEscrowProof.escrowContractAddress,
159
+ originEscrowProof.escrowedToken,
160
+ ...originEscrowProof.escrowRecipient ? [originEscrowProof.escrowRecipient] : []
161
+ ], combinedOfac);
162
+ if (params.currentUnixTimestamp !== void 0) {
163
+ if (typeof params.currentUnixTimestamp !== "number" || !Number.isSafeInteger(params.currentUnixTimestamp) || params.currentUnixTimestamp <= 0) throw new CustomError("INVALID_ERC7683_ORDER", "currentUnixTimestamp must be a positive integer");
164
+ if (params.currentUnixTimestamp > order.fillDeadline) throw new CustomError("EXPIRED_ERC7683_ORDER", `Order ${orderId} fillDeadline (${order.fillDeadline}) has passed`);
165
+ }
166
+ const solverSpreadBps = params.solverSpreadBps ?? 0;
167
+ if (typeof solverSpreadBps !== "number" || !Number.isSafeInteger(solverSpreadBps) || solverSpreadBps < 0 || solverSpreadBps > 500) throw new CustomError("INVALID_ERC7683_ORDER", "solverSpreadBps must be an integer between 0 and 500");
168
+ const isAbtTarget = this.config.abtTokenAddress !== void 0 && destToken === this.config.abtTokenAddress;
169
+ if ((this.config.executionMode === "AGENCY_PASS_THROUGH" || isAbtTarget) && solverSpreadBps !== 0) throw new CustomError("ILLEGAL_DEALER_SPREAD", "Proprietary dealer spread (solverSpreadBps > 0) is strictly prohibited in AGENCY_PASS_THROUGH mode or when settling ABT utility tokens (SEC Section 15(a)(2) Safe Harbor)");
170
+ if (originEscrowProof.originChainId !== order.originChainId) throw new CustomError("INVALID_ORIGIN_ESCROW_PROOF", `originEscrowProof.originChainId (${originEscrowProof.originChainId}) does not match order.originChainId (${order.originChainId})`);
171
+ if (!originEscrowProof.escrowRecipient) throw new CustomError("INVALID_ORIGIN_ESCROW_PROOF", "originEscrowProof.escrowRecipient is required");
172
+ const proofRecipient = normalizeScreeningAddress(assertSafeId(originEscrowProof.escrowRecipient, "originEscrowProof.escrowRecipient"));
173
+ if (proofRecipient !== spentRecipient) throw new CustomError("INVALID_ORIGIN_ESCROW_PROOF", `originEscrowProof.escrowRecipient (${proofRecipient}) does not match order maxSpent[0].recipient (${spentRecipient})`);
174
+ if (typeof originEscrowProof.sourceEscrowTxHash !== "string" || !BYTES32_HEX_REGEX.test(originEscrowProof.sourceEscrowTxHash)) throw new CustomError("INVALID_ORIGIN_ESCROW_PROOF", "sourceEscrowTxHash must be a 32-byte 0x hex string");
175
+ const normalizedEscrowTx = originEscrowProof.sourceEscrowTxHash.toLowerCase();
176
+ const scopedEscrowKey = `${order.originChainId}:${normalizedEscrowTx}`;
177
+ if (this.usedOriginEscrowTxs.has(scopedEscrowKey)) throw new CustomError("REPLAYED_ORIGIN_ESCROW", `sourceEscrowTxHash ${normalizedEscrowTx} on chain ${order.originChainId} has already been used for another intent`);
178
+ const escrowedToken = normalizeScreeningAddress(assertSafeId(originEscrowProof.escrowedToken, "originEscrowProof.escrowedToken"));
179
+ if (escrowedToken !== spentToken) throw new CustomError("INVALID_ORIGIN_ESCROW_PROOF", `Escrowed token (${escrowedToken}) does not match order maxSpent token (${spentToken})`);
180
+ const escrowedAmountBn = parsePositiveBn(originEscrowProof.escrowedAmount, "originEscrowProof.escrowedAmount");
181
+ if (escrowedAmountBn.lt(maxSpentAmountBn)) throw new CustomError("INSUFFICIENT_ORIGIN_ESCROW", `Origin escrowed amount (${escrowedAmountBn.toString(10)}) is less than order maxSpent (${maxSpentAmountBn.toString(10)})`);
182
+ const requiredConfirmations = Math.max(this.config.minOriginConfirmations, originEscrowProof.minRequiredConfirmations ?? 0);
183
+ if (typeof originEscrowProof.confirmations !== "number" || !Number.isSafeInteger(originEscrowProof.confirmations) || originEscrowProof.confirmations < requiredConfirmations) throw new CustomError("INSUFFICIENT_ORIGIN_CONFIRMATIONS", `Origin escrow has ${originEscrowProof.confirmations} confirmations (minimum required: ${requiredConfirmations})`);
184
+ let activeUserIntents = 0;
185
+ for (const rec of this.intents.values()) if (rec.user === user && rec.status === "PENDING") activeUserIntents += 1;
186
+ if (activeUserIntents >= this.config.maxActiveIntentsPerUser) throw new CustomError("USER_ACTIVE_INTENT_LIMIT_EXCEEDED", `User ${user} already has ${activeUserIntents} active PENDING intents (max allowed: ${this.config.maxActiveIntentsPerUser})`);
187
+ if (typeof params.currentHeight !== "number" || !Number.isSafeInteger(params.currentHeight) || params.currentHeight <= 0) throw new CustomError("INVALID_ERC7683_ORDER", "currentHeight must be a positive safe integer");
188
+ const timeoutBlocks = params.timeoutBlocks ?? this.config.maxTimeoutBlocks;
189
+ if (typeof timeoutBlocks !== "number" || !Number.isSafeInteger(timeoutBlocks) || timeoutBlocks <= 0 || timeoutBlocks > this.config.maxTimeoutBlocks) throw new CustomError("INTENT_TIMEOUT_TOO_LONG", `Intent timeoutBlocks (${timeoutBlocks}) must be between 1 and ${this.config.maxTimeoutBlocks} blocks`);
190
+ const timeoutHeight = params.currentHeight + timeoutBlocks;
191
+ const maxCapBn = new BN(this.config.maxEpochNetInflowCap, 10);
192
+ const projectedInflowBn = this.currentEpochNetInflow.add(destAmountBn);
193
+ if (projectedInflowBn.gt(maxCapBn)) throw new CustomError("CANARY_WATERMARK_EXCEEDED", `Cross-chain intent fill (${destAmountBn.toString(10)}) would push epoch net inflow (${projectedInflowBn.toString(10)}) above Canary watermark cap (${maxCapBn.toString(10)})`);
194
+ const primarySelection = selectSolverSubVaultShard(orderId, this.config.solverSubVaultShards);
195
+ let selectedShardAddress = primarySelection.shardAddress;
196
+ const shardCount = this.config.solverSubVaultShards.length;
197
+ for (let offset = 0; offset < shardCount; offset++) {
198
+ const candidateIdx = (primarySelection.shardIndex + offset) % shardCount;
199
+ const candidateAddr = this.config.solverSubVaultShards[candidateIdx];
200
+ if (new BN((await statedb?.account?.get?.(candidateAddr))?.tokens?.[destToken] || "0", 10).gte(destAmountBn)) {
201
+ selectedShardAddress = candidateAddr;
202
+ break;
203
+ }
204
+ }
205
+ const pendingTransfer = await this.ledger.createPendingTransfer({
206
+ id: orderId,
207
+ debitAddress: selectedShardAddress,
208
+ creditAddress: destRecipient,
209
+ tokenAddress: destToken,
210
+ amount: destAmountBn.toString(10),
211
+ currentHeight: params.currentHeight,
212
+ timeoutHeight
213
+ }, statedb);
214
+ this.usedOriginEscrowTxs.add(scopedEscrowKey);
215
+ this.currentEpochNetInflow = projectedInflowBn;
216
+ const intent = {
217
+ orderId,
218
+ user,
219
+ fillerDid: this.config.fillerDid,
220
+ shardAddress: selectedShardAddress,
221
+ destinationRecipient: destRecipient,
222
+ destinationToken: destToken,
223
+ destinationAmount: destAmountBn.toString(10),
224
+ originChainId: order.originChainId,
225
+ originEscrowTxHash: normalizedEscrowTx,
226
+ createdAtHeight: params.currentHeight,
227
+ timeoutHeight,
228
+ executionMode: this.config.executionMode,
229
+ solverSpreadBps,
230
+ status: "PENDING"
231
+ };
232
+ this.intents.set(orderId, intent);
233
+ return {
234
+ intent: { ...intent },
235
+ pendingTransfer
236
+ };
237
+ }
238
+ /**
239
+ * Phase 2A (`POST / SETTLE`):
240
+ * Verifies `#1169` cross-chain Rollup settlement evidence and posts the `PENDING` transfer
241
+ * from the Solver sub-vault shard to the destination recipient.
242
+ */
243
+ async settleIntentFill(params, statedb) {
244
+ if (!params || typeof params !== "object" || !params.settlementProof) throw new CustomError("INVALID_SETTLEMENT_PROOF", "Missing CrossChainSettlementProof");
245
+ const { settlementProof, currentHeight } = params;
246
+ if (typeof currentHeight !== "number" || !Number.isSafeInteger(currentHeight) || currentHeight <= 0) throw new CustomError("INVALID_SETTLEMENT_PROOF", "currentHeight must be a positive safe integer");
247
+ const orderId = assertSafeId(settlementProof.orderId, "settlementProof.orderId");
248
+ const intent = this.intents.get(orderId);
249
+ if (!intent) throw new CustomError("NOT_FOUND", `ERC-7683 intent ${orderId} not found`);
250
+ if (intent.status !== "PENDING") throw new CustomError("INVALID_INTENT_STATE", `ERC-7683 intent ${orderId} is already ${intent.status}`);
251
+ if (currentHeight > intent.timeoutHeight) throw new CustomError("EXPIRED_ERC7683_INTENT", `ERC-7683 intent ${orderId} expired at height ${intent.timeoutHeight} (currentHeight: ${currentHeight})`);
252
+ if (settlementProof.rollupVerified !== true) throw new CustomError("UNVERIFIED_ROLLUP_EVIDENCE", `Settlement proof for order ${orderId} is not verified by #1169 Rollup Validator consensus`);
253
+ if (typeof settlementProof.evidenceHash !== "string" || !BYTES32_HEX_REGEX.test(settlementProof.evidenceHash)) throw new CustomError("INVALID_SETTLEMENT_PROOF", "evidenceHash must be a 32-byte 0x hex string");
254
+ const normalizedEvidence = settlementProof.evidenceHash.toLowerCase();
255
+ if (this.usedSettlementEvidences.has(normalizedEvidence)) throw new CustomError("REPLAYED_SETTLEMENT_EVIDENCE", `Evidence ${normalizedEvidence} has already been consumed`);
256
+ if (typeof settlementProof.destinationFillTxHash !== "string" || !BYTES32_HEX_REGEX.test(settlementProof.destinationFillTxHash)) throw new CustomError("INVALID_SETTLEMENT_PROOF", "destinationFillTxHash must be a 32-byte 0x hex string");
257
+ const normalizedDestFillTx = settlementProof.destinationFillTxHash.toLowerCase();
258
+ if (this.usedDestinationFillTxs.has(normalizedDestFillTx)) throw new CustomError("REPLAYED_DESTINATION_FILL_TX", `destinationFillTxHash ${normalizedDestFillTx} has already been consumed`);
259
+ if (typeof settlementProof.originEscrowTxHash !== "string" || settlementProof.originEscrowTxHash.toLowerCase() !== intent.originEscrowTxHash) throw new CustomError("INVALID_SETTLEMENT_PROOF", "settlementProof.originEscrowTxHash does not match intent originEscrowTxHash");
260
+ const settledRecipient = normalizeScreeningAddress(assertSafeId(settlementProof.settledRecipient, "settlementProof.settledRecipient"));
261
+ const settledToken = normalizeScreeningAddress(assertSafeId(settlementProof.settledToken, "settlementProof.settledToken"));
262
+ const settledAmountBn = parsePositiveBn(settlementProof.settledAmount, "settlementProof.settledAmount");
263
+ if (settledRecipient !== intent.destinationRecipient || settledToken !== intent.destinationToken) throw new CustomError("INVALID_SETTLEMENT_PROOF", "Settlement recipient or token does not match prepared intent");
264
+ if (settledAmountBn.lt(new BN(intent.destinationAmount, 10))) throw new CustomError("INSUFFICIENT_SETTLEMENT_AMOUNT", `Settled amount (${settledAmountBn.toString(10)}) is less than guaranteed destinationAmount (${intent.destinationAmount})`);
265
+ const postedTransfer = await this.ledger.postPendingTransfer({
266
+ id: orderId,
267
+ currentHeight
268
+ }, statedb);
269
+ this.usedSettlementEvidences.add(normalizedEvidence);
270
+ this.usedDestinationFillTxs.add(normalizedDestFillTx);
271
+ intent.status = "POSTED";
272
+ intent.settlementEvidenceHash = normalizedEvidence;
273
+ return {
274
+ intent: { ...intent },
275
+ postedTransfer
276
+ };
277
+ }
278
+ /**
279
+ * Phase 2B (`VOID / PAGINATED ROLLBACK SWEEP`):
280
+ * Sweeps up to `maxBatchSize` expired `PENDING` intents (`currentHeight > intent.timeoutHeight`),
281
+ * returning locked `pendingTokens` back to the Solver sub-vault shard's available `tokens`
282
+ * and releasing the reserved Canary net-inflow quota.
283
+ */
284
+ async sweepExpiredIntents(params, statedb) {
285
+ if (!params || typeof params.currentHeight !== "number" || !Number.isSafeInteger(params.currentHeight) || params.currentHeight <= 0) throw new CustomError("INVALID_ERC7683_SOLVER", "currentHeight must be a positive safe integer");
286
+ const batchCap = Math.min(params.maxBatchSize ?? this.config.maxSweepBatchSize, this.config.maxSweepBatchSize);
287
+ if (!Number.isSafeInteger(batchCap) || batchCap <= 0) throw new CustomError("INVALID_ERC7683_SOLVER", "maxBatchSize must be a positive integer");
288
+ const expiredIntents = [];
289
+ for (const intent of this.intents.values()) if (intent.status === "PENDING" && params.currentHeight > intent.timeoutHeight) expiredIntents.push(intent);
290
+ const toSweep = expiredIntents.slice(0, batchCap);
291
+ const sweptOrderIds = [];
292
+ const failedOrderIds = [];
293
+ for (const intent of toSweep) try {
294
+ await this.ledger.voidPendingTransfer({ id: intent.orderId }, statedb);
295
+ intent.status = "VOIDED";
296
+ const amtBn = parseNonNegativeBn(intent.destinationAmount, "destinationAmount");
297
+ this.currentEpochNetInflow = this.currentEpochNetInflow.gt(amtBn) ? this.currentEpochNetInflow.sub(amtBn) : new BN(0);
298
+ sweptOrderIds.push(intent.orderId);
299
+ } catch {
300
+ failedOrderIds.push(intent.orderId);
301
+ }
302
+ return {
303
+ sweptOrderIds,
304
+ failedOrderIds,
305
+ remainingExpiredCount: Math.max(0, expiredIntents.length - sweptOrderIds.length - failedOrderIds.length)
306
+ };
307
+ }
308
+ getIntent(orderId) {
309
+ const rec = this.intents.get(orderId);
310
+ return rec ? { ...rec } : void 0;
311
+ }
312
+ getCurrentEpochNetInflow() {
313
+ return this.currentEpochNetInflow.toString(10);
314
+ }
315
+ resetEpochNetInflow() {
316
+ this.currentEpochNetInflow = new BN(0);
317
+ }
318
+ };
319
+
320
+ //#endregion
321
+ export { DEFAULT_MAX_SWEEP_BATCH_SIZE, MAX_ACTIVE_INTENTS_PER_USER, MAX_INTENT_TIMEOUT_BLOCKS, MIN_RECOMMENDED_SOLVER_SHARDS, OcapErc7683SolverEngine, selectSolverSubVaultShard };
@@ -0,0 +1,113 @@
1
+ import { ContractNftPayload, StatementExecutor, TransactionBlockResult } from "./transaction-block.mjs";
2
+
3
+ //#region src/uniswap-lp-copilot.d.ts
4
+
5
+ /**
6
+ * Uniswap V3 / V4 absolute tick bounds.
7
+ */
8
+ declare const MIN_UNISWAP_TICK = -887272;
9
+ declare const MAX_UNISWAP_TICK = 887272;
10
+ /**
11
+ * Maximum allowed LP rebalance slippage in basis points (1.00% = 100 bps).
12
+ */
13
+ declare const MAX_LP_REBALANCE_SLIPPAGE_BPS = 100;
14
+ /**
15
+ * Default minimum cooldown blocks between automated LP rebalances to prevent rebalance storms.
16
+ */
17
+ declare const DEFAULT_LP_REBALANCE_COOLDOWN_BLOCKS = 20;
18
+ /**
19
+ * Default deterministic jitter window (in blocks) to spread multi-agent rebalances across blocks.
20
+ */
21
+ declare const DEFAULT_LP_JITTER_WINDOW_BLOCKS = 16;
22
+ interface NonCustodialLpGuardSpec {
23
+ contractNftAddress: string;
24
+ ownerDid: string;
25
+ /** Optional single beneficiary DID — MUST equal ownerDid (zero commingling) */
26
+ beneficiaryDids?: string[];
27
+ /** Must ALWAYS be false or omitted (1940 Investment Company Act Safe Harbor) */
28
+ commingledPool?: boolean;
29
+ /** Authorized AIGNE Copilot session key / agent DID allowed to submit bounded rebalance proposals */
30
+ copilotAgentDid: string;
31
+ /** Allowlisted Uniswap V3/V4 32-byte Pool IDs */
32
+ allowedPoolIds: string[];
33
+ /** Maximum allowed NAV slippage per rebalance in bps (must be <= 100 bps = 1.00%) */
34
+ maxSlippageBps: number;
35
+ /** Minimum tick range width (`newTickUpper - newTickLower >= minTickWidth`) */
36
+ minTickWidth: number;
37
+ /** Maximum allowed spot-vs-TWAP tick divergence before volatility circuit breaker trips */
38
+ maxTwapTickDeviation: number;
39
+ /** Minimum block interval between rebalances (`currentHeight - lastRebalanceHeight >= minCooldownBlocks`) */
40
+ minCooldownBlocks?: number;
41
+ /** Fixed SaaS / AIGNE compute fee in ABT per rebalance (not % of AUM or % of profit) */
42
+ fixedAbtComputeFee: string;
43
+ abtTokenAddress: string;
44
+ computeFeeRecipientDid: string;
45
+ /** Must ALWAYS be 0 or omitted (Investment Advisers Act Safe Harbor) */
46
+ managementFeeBps?: number;
47
+ /** Must ALWAYS be 0 or omitted (Investment Advisers Act Safe Harbor) */
48
+ performanceFeeBps?: number;
49
+ /** Must ALWAYS be 0 or omitted (SEC Section 15(a) Broker-Dealer Safe Harbor) */
50
+ swapCommissionBps?: number;
51
+ ofacBlocklist?: Iterable<string>;
52
+ }
53
+ interface NonCustodialLpContractNftAsset {
54
+ address: string;
55
+ owner: string;
56
+ consumedTime?: string;
57
+ data: {
58
+ type: 'json';
59
+ value: ContractNftPayload;
60
+ };
61
+ guardSpec: NonCustodialLpGuardSpec;
62
+ }
63
+ /**
64
+ * Computes a deterministic block slot offset `[0, jitterWindowBlocks - 1]` for a given
65
+ * `contractNftAddress` and volatility epoch so thousands of AIGNE LP Copilots never fire
66
+ * in the exact same block during market spikes (Thundering Herd / Self-DDoS mitigation).
67
+ */
68
+ declare function computeDeterministicRebalanceSlot(contractNftAddress: string, epoch: number, jitterWindowBlocks?: number): number;
69
+ /**
70
+ * Builds a 100% Non-Custodial `ContractNFT` asset with deterministic on-chain guardrails
71
+ * for managing a single user's Uniswap V3/V4 concentrated liquidity position.
72
+ *
73
+ * Legal & Security Invariants:
74
+ * 1. Strictly prohibits pooled / commingled multi-user funds (`commingledPool: false`, single `ownerDid`).
75
+ * 2. Strictly prohibits `% AUM` management fees, `% Performance` fees, and `% Swap` commissions.
76
+ * 3. Encodes hard declarative guards for `allowedPoolIds`, `maxSlippageBps`, `minTickWidth`,
77
+ * `maxTwapTickDeviation`, `minCooldownBlocks`, and post-rebalance NAV conservation.
78
+ */
79
+ declare function buildNonCustodialLpContractNft(spec: NonCustodialLpGuardSpec): NonCustodialLpContractNftAsset;
80
+ interface LpRebalanceProposalInput {
81
+ contractNft: NonCustodialLpContractNftAsset;
82
+ callerDid: string;
83
+ poolId: string;
84
+ positionId: string;
85
+ newTickLower: number;
86
+ newTickUpper: number;
87
+ spotTick: number;
88
+ twapTick: number;
89
+ preRebalanceNavUsd: string;
90
+ postRebalanceNavUsd: string;
91
+ currentBlockHeight: number;
92
+ lastRebalanceHeight?: number;
93
+ enforceJitterSlot?: boolean;
94
+ jitterWindowBlocks?: number;
95
+ statedb: Record<string, any>;
96
+ executeStatement: StatementExecutor;
97
+ dryRun?: boolean;
98
+ ofacBlocklist?: Iterable<string>;
99
+ }
100
+ /**
101
+ * Validates and executes a non-custodial LP rebalance proposal through the user's personal `ContractNFT`:
102
+ * 1. Verifies OFAC sanctions screening.
103
+ * 2. Enforces `minCooldownBlocks` and optional deterministic jitter slot to prevent automated rebalance storms.
104
+ * 3. Trips the Volatility Circuit Breaker if `|spotTick - twapTick| > maxTwapTickDeviation`.
105
+ * 4. Enforces post-condition NAV conservation (`postRebalanceNavUsd >= minRequiredPostNavUsd`).
106
+ * 5. Runs a mandatory pre-flight `dryRun: true` check on the overlay before committing.
107
+ */
108
+ declare function executeNonCustodialLpRebalance(input: LpRebalanceProposalInput): Promise<TransactionBlockResult & {
109
+ nextAllowedRebalanceHeight: number;
110
+ jitterSlot: number;
111
+ }>;
112
+ //#endregion
113
+ export { DEFAULT_LP_JITTER_WINDOW_BLOCKS, DEFAULT_LP_REBALANCE_COOLDOWN_BLOCKS, LpRebalanceProposalInput, MAX_LP_REBALANCE_SLIPPAGE_BPS, MAX_UNISWAP_TICK, MIN_UNISWAP_TICK, NonCustodialLpContractNftAsset, NonCustodialLpGuardSpec, buildNonCustodialLpContractNft, computeDeterministicRebalanceSlot, executeNonCustodialLpRebalance };