@ocap/tx-pipeline 1.30.25 → 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,517 @@
1
+ import { CHAINALYSIS_OFAC_ORACLE_ADDRESS, assertNotOfacSanctioned, normalizeScreeningAddress } from "./ofac-screening.mjs";
2
+ import "./uniswap-router.mjs";
3
+ import { Hasher } from "@ocap/mcrypto";
4
+ import { BN } from "@ocap/util";
5
+ import { CustomError } from "@ocap/util/lib/error";
6
+ import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
7
+ import { fromPublicKey } from "@ocap/wallet";
8
+
9
+ //#region src/uniswap-v4-hook.ts
10
+ /**
11
+ * Maximum allowed TTL for stateless edge-signed Hook tickets (15 minutes = 900 seconds).
12
+ */
13
+ const MAX_HOOK_TICKET_TTL_SECONDS = 900;
14
+ /**
15
+ * Default minimum continuous holding blocks on OCAP to prevent flash-borrow VIP ticket abuse.
16
+ */
17
+ const DEFAULT_MIN_HOLDING_BLOCKS = 300;
18
+ /**
19
+ * Minimum percentage of MEV penalty surcharge that MUST be returned to Uniswap V4 LPs (80% = 8000 bps).
20
+ */
21
+ const MIN_LP_MEV_REBATE_SHARE_BPS = 8e3;
22
+ /**
23
+ * Maximum dynamic LP fee override in Uniswap V4 (5.00% = 500 bps).
24
+ */
25
+ const MAX_V4_DYNAMIC_FEE_BPS = 500;
26
+ const FORBIDDEN_KEYS = new Set([
27
+ "__proto__",
28
+ "constructor",
29
+ "prototype"
30
+ ]);
31
+ const CANONICAL_UINT_REGEX = /^\d+$/;
32
+ const EVM_HEX_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;
33
+ const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
34
+ const VALID_HOOK_TIERS = new Set([
35
+ "VIP_LOYALTY",
36
+ "ABT_STAKER",
37
+ "VERIFIED_DID",
38
+ "STANDARD_RETAIL",
39
+ "MEV_SURCHARGE"
40
+ ]);
41
+ /**
42
+ * Normalized lowercase PII key tokens and substrings that must NEVER appear in any ticket
43
+ * or on-chain hookData (GDPR Safe Harbor).
44
+ */
45
+ const FORBIDDEN_NORMALIZED_PII_KEYS = new Set([
46
+ "name",
47
+ "fullname",
48
+ "firstname",
49
+ "lastname",
50
+ "email",
51
+ "emailaddress",
52
+ "useremail",
53
+ "phone",
54
+ "phonenumber",
55
+ "passport",
56
+ "passportnumber",
57
+ "ssn",
58
+ "socialsecurity",
59
+ "socialsecuritynumber",
60
+ "taxid",
61
+ "nationalid",
62
+ "driverlicense",
63
+ "dateofbirth",
64
+ "dob",
65
+ "birthdate",
66
+ "physicaladdress",
67
+ "residentialaddress",
68
+ "homeaddress",
69
+ "ipaddress"
70
+ ]);
71
+ const FORBIDDEN_PII_SUBSTRINGS = [
72
+ "passport",
73
+ "ssn",
74
+ "socialsecurity",
75
+ "taxid",
76
+ "nationalid",
77
+ "driverlicense",
78
+ "dateofbirth",
79
+ "email",
80
+ "phonenumber",
81
+ "residentialaddress",
82
+ "physicaladdress",
83
+ "ipaddress"
84
+ ];
85
+ function assertSafeString(val, label) {
86
+ if (typeof val !== "string") throw new CustomError("INVALID_V4_HOOK", `${label} must be a non-empty string`);
87
+ const trimmed = val.trim();
88
+ if (!trimmed || FORBIDDEN_KEYS.has(trimmed)) throw new CustomError("INVALID_V4_HOOK", `Unsafe or empty ${label}`);
89
+ return trimmed;
90
+ }
91
+ function assertEvmAddr(val, label) {
92
+ if (typeof val !== "string" || !EVM_HEX_ADDRESS_REGEX.test(val)) throw new CustomError("INVALID_V4_HOOK", `${label} must be a valid 20-byte 0x EVM address`);
93
+ return val.toLowerCase();
94
+ }
95
+ function assertPoolId(val) {
96
+ if (typeof val !== "string" || !BYTES32_HEX_REGEX.test(val)) throw new CustomError("INVALID_V4_HOOK", "poolId must be a 32-byte 0x hex string");
97
+ return val.toLowerCase();
98
+ }
99
+ function parsePositiveBn(val, label) {
100
+ if (typeof val !== "string" || !CANONICAL_UINT_REGEX.test(val)) throw new CustomError("INVALID_V4_HOOK", `${label} must be a canonical non-negative integer string`);
101
+ const bn = new BN(val, 10);
102
+ if (bn.lte(new BN(0))) throw new CustomError("INVALID_V4_HOOK", `${label} must be strictly positive`);
103
+ return bn;
104
+ }
105
+ function assertValidTimestamp(ts, label = "currentTimestamp") {
106
+ if (typeof ts !== "number" || !Number.isSafeInteger(ts) || ts < 0) throw new CustomError("INVALID_V4_HOOK", `${label} must be a non-negative safe integer`);
107
+ return ts;
108
+ }
109
+ /**
110
+ * Recursively scans an object or array for any forbidden PII field names (case/snake/hyphen-insensitive)
111
+ * and enforces a strict maximum nesting depth of 8 to guarantee Zero-PII On-Chain (GDPR Safe Harbor).
112
+ */
113
+ function assertZeroPiiInHookData(payload, depth = 0) {
114
+ if (depth > 8) throw new CustomError("MAX_HOOK_DATA_DEPTH_EXCEEDED", "Hook data nesting depth exceeds maximum allowed (8)");
115
+ if (!payload || typeof payload !== "object") return;
116
+ if (Array.isArray(payload)) {
117
+ for (const item of payload) assertZeroPiiInHookData(item, depth + 1);
118
+ return;
119
+ }
120
+ for (const [k, v] of Object.entries(payload)) {
121
+ if (FORBIDDEN_KEYS.has(k)) throw new CustomError("INVALID_V4_HOOK", `Forbidden prototype key ${k}`);
122
+ const normalizedKey = k.replace(/[_-\s]/g, "").toLowerCase();
123
+ if (FORBIDDEN_NORMALIZED_PII_KEYS.has(normalizedKey) || FORBIDDEN_PII_SUBSTRINGS.some((sub) => normalizedKey.includes(sub))) throw new CustomError("GDPR_PII_PROHIBITED", `Plaintext PII field '${k}' is strictly prohibited in on-chain Hook tickets (Zero-PII Safe Harbor)`);
124
+ if (v && typeof v === "object") assertZeroPiiInHookData(v, depth + 1);
125
+ }
126
+ }
127
+ /**
128
+ * Computes the canonical digest for an OCAP Uniswap V4 Hook attestation ticket.
129
+ */
130
+ function computeOcapHookTicketDigest(claims) {
131
+ assertZeroPiiInHookData(claims);
132
+ const chainId = assertSafeString(claims.chainId, "claims.chainId");
133
+ const poolId = assertPoolId(claims.poolId);
134
+ const hookAddress = assertEvmAddr(claims.hookAddress, "claims.hookAddress");
135
+ const traderAddress = assertEvmAddr(claims.traderAddress, "claims.traderAddress");
136
+ const holderDid = normalizeScreeningAddress(assertSafeString(claims.holderDid, "claims.holderDid"));
137
+ const maxAmountIn = parsePositiveBn(claims.maxAmountIn, "claims.maxAmountIn");
138
+ const nonce = assertSafeString(claims.nonce, "claims.nonce");
139
+ if (!VALID_HOOK_TIERS.has(claims.tier)) throw new CustomError("INVALID_V4_HOOK", `Unsupported HookFeeTierName: ${String(claims.tier)}`);
140
+ if (typeof claims.feeBpsOverride !== "number" || !Number.isSafeInteger(claims.feeBpsOverride) || claims.feeBpsOverride < 0 || claims.feeBpsOverride > MAX_V4_DYNAMIC_FEE_BPS) throw new CustomError("INVALID_V4_HOOK", `claims.feeBpsOverride must be an integer between 0 and ${MAX_V4_DYNAMIC_FEE_BPS}`);
141
+ if (typeof claims.holdingBlocks !== "number" || !Number.isSafeInteger(claims.holdingBlocks) || claims.holdingBlocks < 0) throw new CustomError("INVALID_V4_HOOK", "claims.holdingBlocks must be a non-negative integer");
142
+ if (typeof claims.issuedAt !== "number" || !Number.isSafeInteger(claims.issuedAt) || typeof claims.validUntil !== "number" || !Number.isSafeInteger(claims.validUntil) || claims.validUntil <= claims.issuedAt) throw new CustomError("INVALID_V4_HOOK", "claims.validUntil must be strictly greater than claims.issuedAt");
143
+ if (claims.validUntil - claims.issuedAt > MAX_HOOK_TICKET_TTL_SECONDS) throw new CustomError("HOOK_TICKET_TTL_EXCEEDED", `Ticket TTL (${claims.validUntil - claims.issuedAt}s) exceeds maximum allowed ${MAX_HOOK_TICKET_TTL_SECONDS}s`);
144
+ const kycIssuerDid = claims.kycIssuerDid ? normalizeScreeningAddress(assertSafeString(claims.kycIssuerDid, "claims.kycIssuerDid")) : "";
145
+ const canonical = JSON.stringify({
146
+ domain: "OCAP_UNISWAP_V4_VERIFIED_HOOK_V1",
147
+ chainId,
148
+ poolId,
149
+ hookAddress,
150
+ traderAddress,
151
+ holderDid,
152
+ tier: claims.tier,
153
+ feeBpsOverride: claims.feeBpsOverride,
154
+ maxAmountIn: maxAmountIn.toString(10),
155
+ holdingBlocks: claims.holdingBlocks,
156
+ kycVerified: Boolean(claims.kycVerified),
157
+ kycIssuerDid,
158
+ issuedAt: claims.issuedAt,
159
+ validUntil: claims.validUntil,
160
+ nonce
161
+ });
162
+ return Hasher.SHA3.hash256(Buffer.from(canonical, "utf8"));
163
+ }
164
+ /**
165
+ * Edge Attestation Signer: Issues a short-lived, stateless Hook ticket from an OCAP Read-Replica.
166
+ * Enforces:
167
+ * - Zero PII on-chain (GDPR Safe Harbor)
168
+ * - Time-weighted holding guard (`holdingBlocks >= minHoldingBlocks`) to block flash-borrow VIP abuse
169
+ * - Maximum TTL cap (`<= 900` seconds)
170
+ * - OFAC sanctions screening
171
+ */
172
+ async function issueOcapHookTicket(claimsInput, signerWallet, options) {
173
+ assertZeroPiiInHookData(claimsInput);
174
+ if (!VALID_HOOK_TIERS.has(claimsInput.tier)) throw new CustomError("INVALID_V4_HOOK", `Unsupported HookFeeTierName: ${String(claimsInput.tier)}`);
175
+ const minHoldingBlocks = options?.minHoldingBlocks ?? DEFAULT_MIN_HOLDING_BLOCKS;
176
+ if ((claimsInput.tier === "VIP_LOYALTY" || claimsInput.tier === "ABT_STAKER") && claimsInput.holdingBlocks < minHoldingBlocks) throw new CustomError("FLASH_BORROW_HOLDING_TOO_SHORT", `Tier ${claimsInput.tier} requires at least ${minHoldingBlocks} continuous holding blocks on OCAP (actual: ${claimsInput.holdingBlocks})`);
177
+ if (claimsInput.kycVerified) {
178
+ if (!claimsInput.kycIssuerDid || !claimsInput.kycIssuerDid.trim()) throw new CustomError("INVALID_V4_HOOK", "kycVerified ticket must specify kycIssuerDid");
179
+ if (options?.trustedKycIssuerDids && options.trustedKycIssuerDids.length > 0) {
180
+ const normalizedTrusted = new Set(options.trustedKycIssuerDids.map((d) => normalizeScreeningAddress(d)));
181
+ const normalizedIssuer = normalizeScreeningAddress(claimsInput.kycIssuerDid);
182
+ if (!normalizedTrusted.has(normalizedIssuer)) throw new CustomError("UNTRUSTED_KYC_ISSUER", `KYC issuer ${claimsInput.kycIssuerDid} is not in trusted list`);
183
+ }
184
+ }
185
+ assertNotOfacSanctioned([
186
+ claimsInput.traderAddress,
187
+ claimsInput.holderDid,
188
+ claimsInput.kycIssuerDid,
189
+ signerWallet.address
190
+ ], options?.ofacBlocklist);
191
+ const normalizedClaims = {
192
+ ...claimsInput,
193
+ chainId: assertSafeString(claimsInput.chainId, "claims.chainId"),
194
+ poolId: assertPoolId(claimsInput.poolId),
195
+ hookAddress: assertEvmAddr(claimsInput.hookAddress, "claims.hookAddress"),
196
+ traderAddress: assertEvmAddr(claimsInput.traderAddress, "claims.traderAddress"),
197
+ holderDid: normalizeScreeningAddress(assertSafeString(claimsInput.holderDid, "claims.holderDid")),
198
+ kycIssuerDid: claimsInput.kycIssuerDid ? normalizeScreeningAddress(assertSafeString(claimsInput.kycIssuerDid, "claims.kycIssuerDid")) : void 0,
199
+ nonce: assertSafeString(claimsInput.nonce, "claims.nonce")
200
+ };
201
+ const digest = computeOcapHookTicketDigest(normalizedClaims);
202
+ const sig = await signerWallet.sign(Buffer.from(digest.replace(/^0x/, ""), "hex"), false);
203
+ return {
204
+ claims: normalizedClaims,
205
+ signerDid: normalizeScreeningAddress(signerWallet.address),
206
+ signerPk: signerWallet.publicKey,
207
+ signature: sig,
208
+ digest
209
+ };
210
+ }
211
+ /**
212
+ * Verifies a signed OcapHookTicket purely from its cryptographic signature and claims
213
+ * (0 synchronous network/RPC calls to OCAP nodes).
214
+ */
215
+ async function verifyOcapHookTicketSignature(ticket) {
216
+ if (!ticket || typeof ticket !== "object" || !ticket.claims) return false;
217
+ assertZeroPiiInHookData(ticket);
218
+ const signerDid = normalizeScreeningAddress(assertSafeString(ticket.signerDid, "ticket.signerDid"));
219
+ const signerPk = assertSafeString(ticket.signerPk, "ticket.signerPk");
220
+ const signature = assertSafeString(ticket.signature, "ticket.signature");
221
+ if (!isFromPublicKey(signerDid, signerPk)) return false;
222
+ const expectedDigest = computeOcapHookTicketDigest(ticket.claims);
223
+ if (ticket.digest && ticket.digest !== expectedDigest) return false;
224
+ const verifier = fromPublicKey(signerPk, toTypeInfo(signerDid));
225
+ const msgBytes = Buffer.from(expectedDigest.replace(/^0x/, ""), "hex");
226
+ return Boolean(await verifier.verify(msgBytes, signature, false));
227
+ }
228
+ /**
229
+ * Deterministic `OcapVerifiedHook` Engine modeling the on-chain Uniswap V4 Hook lifecycle:
230
+ * - `beforeInitialize`: Protects pool creation against tick-sniping front-running
231
+ * - `beforeAddLiquidity`: Enforces OFAC sanctions screening + RWA KYC permissioning
232
+ * - `beforeSwap`: Purely stateless ticket verification + graceful router-friendly fallback + anti-MEV LP rebate split
233
+ */
234
+ var OcapVerifiedHookEngine = class {
235
+ constructor(config) {
236
+ this.consumedNonces = /* @__PURE__ */ new Map();
237
+ this.rwaAllowlistCache = /* @__PURE__ */ new Map();
238
+ if (!config || typeof config !== "object") throw new CustomError("INVALID_V4_HOOK", "Missing V4PoolHookConfig");
239
+ const lpRebateBps = config.lpMevRebateShareBps ?? MIN_LP_MEV_REBATE_SHARE_BPS;
240
+ if (typeof lpRebateBps !== "number" || !Number.isSafeInteger(lpRebateBps) || lpRebateBps < MIN_LP_MEV_REBATE_SHARE_BPS || lpRebateBps > 1e4) throw new CustomError("VAMPIRE_FEE_SKIMMING_PROHIBITED", `lpMevRebateShareBps (${lpRebateBps}) must be between ${MIN_LP_MEV_REBATE_SHARE_BPS} (80%) and 10000 (100%) to align with Uniswap LPs`);
241
+ if (!Array.isArray(config.authorizedSignerDids) || config.authorizedSignerDids.length === 0) throw new CustomError("INVALID_V4_HOOK", "authorizedSignerDids must contain at least one OCAP signer DID");
242
+ if (config.poolMode !== "LOYALTY_PUBLIC" && config.poolMode !== "PERMISSIONED_RWA") throw new CustomError("INVALID_V4_HOOK", `Unsupported poolMode: ${String(config.poolMode)}`);
243
+ if (config.poolMode === "PERMISSIONED_RWA" && (!Array.isArray(config.trustedKycIssuerDids) || config.trustedKycIssuerDids.length === 0)) throw new CustomError("INVALID_V4_HOOK", "PERMISSIONED_RWA poolMode requires at least one trustedKycIssuerDid");
244
+ for (const fee of [
245
+ config.baseFeeBps,
246
+ config.vipFeeBps,
247
+ config.abtStakerFeeBps,
248
+ config.verifiedDidFeeBps,
249
+ config.mevPenaltyFeeBps
250
+ ]) if (typeof fee !== "number" || !Number.isSafeInteger(fee) || fee < 0 || fee > MAX_V4_DYNAMIC_FEE_BPS) throw new CustomError("INVALID_V4_HOOK", `Invalid fee tier bps: ${String(fee)}`);
251
+ if (config.vipFeeBps > config.abtStakerFeeBps || config.abtStakerFeeBps > config.verifiedDidFeeBps || config.verifiedDidFeeBps > config.baseFeeBps || config.baseFeeBps > config.mevPenaltyFeeBps) throw new CustomError("INVALID_V4_HOOK", "Fee tiers must satisfy vipFeeBps <= abtStakerFeeBps <= verifiedDidFeeBps <= baseFeeBps <= mevPenaltyFeeBps");
252
+ parsePositiveBn(config.unverifiedMevThresholdAmountIn, "config.unverifiedMevThresholdAmountIn");
253
+ this.config = {
254
+ ...config,
255
+ chainId: assertSafeString(config.chainId, "config.chainId"),
256
+ poolId: assertPoolId(config.poolId),
257
+ hookAddress: assertEvmAddr(config.hookAddress, "config.hookAddress"),
258
+ authorizedSignerDids: config.authorizedSignerDids.map((d) => normalizeScreeningAddress(assertSafeString(d, "authorizedSignerDid"))),
259
+ trustedKycIssuerDids: config.trustedKycIssuerDids?.map((d) => normalizeScreeningAddress(assertSafeString(d, "trustedKycIssuerDid"))),
260
+ authorizedPoolCreator: config.authorizedPoolCreator ? assertEvmAddr(config.authorizedPoolCreator, "config.authorizedPoolCreator") : void 0,
261
+ minHoldingBlocks: config.minHoldingBlocks ?? DEFAULT_MIN_HOLDING_BLOCKS,
262
+ lpMevRebateShareBps: lpRebateBps
263
+ };
264
+ }
265
+ pruneExpiredCaches(currentTimestamp) {
266
+ for (const [k, exp] of this.consumedNonces.entries()) if (exp < currentTimestamp) this.consumedNonces.delete(k);
267
+ for (const [addr, entry] of this.rwaAllowlistCache.entries()) if (entry.validUntil <= currentTimestamp) this.rwaAllowlistCache.delete(addr);
268
+ }
269
+ /**
270
+ * `beforeInitialize`: Protects newly graduating or official pools from front-running bots
271
+ * initializing the same V4 PoolKey at a manipulated initial tick/sqrtPriceX96.
272
+ */
273
+ beforeInitialize(params) {
274
+ const caller = assertEvmAddr(params.callerAddress, "callerAddress");
275
+ assertNotOfacSanctioned([caller], this.config.ofacBlocklist);
276
+ if (this.config.authorizedPoolCreator && caller !== this.config.authorizedPoolCreator) throw new CustomError("UNAUTHORIZED_POOL_INITIALIZER", `Caller ${caller} is not authorized to initialize pool ${this.config.poolId} (expected ${this.config.authorizedPoolCreator})`);
277
+ return { allowed: true };
278
+ }
279
+ /**
280
+ * `beforeAddLiquidity`: Screens LPs against OFAC sanctions and enforces KYC VC for PERMISSIONED_RWA pools.
281
+ */
282
+ async beforeAddLiquidity(params) {
283
+ const lpAddress = assertEvmAddr(params.lpAddress, "lpAddress");
284
+ const currentTimestamp = assertValidTimestamp(params.currentTimestamp, "currentTimestamp");
285
+ this.pruneExpiredCaches(currentTimestamp);
286
+ assertNotOfacSanctioned([
287
+ lpAddress,
288
+ params.ticket?.claims?.holderDid,
289
+ params.ticket?.claims?.kycIssuerDid,
290
+ params.ticket?.signerDid
291
+ ], this.config.ofacBlocklist);
292
+ if (this.config.poolMode === "LOYALTY_PUBLIC") {
293
+ if (params.ticket) assertZeroPiiInHookData(params.ticket);
294
+ return { allowed: true };
295
+ }
296
+ if (!params.ticket) {
297
+ const cached = this.rwaAllowlistCache.get(lpAddress);
298
+ if (cached && cached.validUntil > currentTimestamp) return {
299
+ allowed: true,
300
+ cachedRwaValidUntil: cached.validUntil
301
+ };
302
+ throw new CustomError("RWA_KYC_REQUIRED", `Pool ${this.config.poolId} is in PERMISSIONED_RWA mode and requires a valid KYC-verified OCAP ticket`);
303
+ }
304
+ const validation = await this.validateTicketInternal(params.ticket, lpAddress, "1", currentTimestamp, true);
305
+ if (!validation.valid || !params.ticket.claims.kycVerified) throw new CustomError("RWA_KYC_REQUIRED", `Pool ${this.config.poolId} is in PERMISSIONED_RWA mode and requires a valid KYC-verified OCAP ticket (${validation.reason || "missing kycVerified"})`);
306
+ this.rwaAllowlistCache.set(lpAddress, {
307
+ validUntil: params.ticket.claims.validUntil,
308
+ maxAmountIn: params.ticket.claims.maxAmountIn
309
+ });
310
+ return {
311
+ allowed: true,
312
+ cachedRwaValidUntil: params.ticket.claims.validUntil
313
+ };
314
+ }
315
+ /**
316
+ * `beforeSwap`: Evaluates swap permissions, dynamic fee overrides, and anti-MEV LP rebates.
317
+ *
318
+ * Key Guarantees:
319
+ * 1. Zero synchronous cross-chain RPC calls (`synchronousCrossChainRpcCalls: 0`).
320
+ * 2. Hard-reverts ONLY on OFAC sanctions, GDPR PII violations, or unverified callers in `PERMISSIONED_RWA` pools.
321
+ * 3. In `LOYALTY_PUBLIC` pools, missing/expired/invalid tickets NEVER revert standard router swaps —
322
+ * they gracefully fall back to `baseFeeBps` (or `mevPenaltyFeeBps` for large unverified arbitrage orders).
323
+ */
324
+ async beforeSwap(params) {
325
+ const traderAddress = assertEvmAddr(params.traderAddress, "traderAddress");
326
+ const amountInBn = parsePositiveBn(params.amountIn, "amountIn");
327
+ const currentTimestamp = assertValidTimestamp(params.currentTimestamp, "currentTimestamp");
328
+ this.pruneExpiredCaches(currentTimestamp);
329
+ assertNotOfacSanctioned([
330
+ traderAddress,
331
+ params.ticket?.claims?.holderDid,
332
+ params.ticket?.claims?.kycIssuerDid,
333
+ params.ticket?.signerDid
334
+ ], this.config.ofacBlocklist);
335
+ const validation = await this.validateTicketInternal(params.ticket, traderAddress, amountInBn.toString(10), currentTimestamp, true);
336
+ if (this.config.poolMode === "PERMISSIONED_RWA") if (params.ticket) {
337
+ if (!validation.valid || !params.ticket.claims.kycVerified) throw new CustomError("RWA_KYC_REQUIRED", `Swap rejected in PERMISSIONED_RWA pool: ${validation.reason || "ticket lacks kycVerified"}`);
338
+ this.rwaAllowlistCache.set(traderAddress, {
339
+ validUntil: params.ticket.claims.validUntil,
340
+ maxAmountIn: params.ticket.claims.maxAmountIn
341
+ });
342
+ } else {
343
+ const cached = this.rwaAllowlistCache.get(traderAddress);
344
+ if (!cached || cached.validUntil <= currentTimestamp) throw new CustomError("RWA_KYC_REQUIRED", `Swap rejected in PERMISSIONED_RWA pool: ${validation.reason || "unverified trader"}`);
345
+ const cachedMaxBn = parsePositiveBn(cached.maxAmountIn, "cached.maxAmountIn");
346
+ if (amountInBn.gt(cachedMaxBn)) throw new CustomError("RWA_KYC_REQUIRED", `Swap amount ${amountInBn.toString(10)} exceeds cached RWA KYC cap ${cachedMaxBn.toString(10)}`);
347
+ const remainingAllowanceBn = cachedMaxBn.sub(amountInBn);
348
+ if (remainingAllowanceBn.isZero()) this.rwaAllowlistCache.delete(traderAddress);
349
+ else this.rwaAllowlistCache.set(traderAddress, {
350
+ validUntil: cached.validUntil,
351
+ maxAmountIn: remainingAllowanceBn.toString(10)
352
+ });
353
+ }
354
+ let appliedTier = "STANDARD_RETAIL";
355
+ let lpFeeBpsOverride = this.config.baseFeeBps;
356
+ let usedFallbackBaseFee = false;
357
+ let fallbackReason;
358
+ if (validation.valid && params.ticket) {
359
+ appliedTier = params.ticket.claims.tier;
360
+ lpFeeBpsOverride = params.ticket.claims.feeBpsOverride;
361
+ } else {
362
+ usedFallbackBaseFee = true;
363
+ fallbackReason = validation.reason;
364
+ const mevThresholdBn = parsePositiveBn(this.config.unverifiedMevThresholdAmountIn, "unverifiedMevThresholdAmountIn");
365
+ if (amountInBn.gte(mevThresholdBn)) {
366
+ appliedTier = "MEV_SURCHARGE";
367
+ lpFeeBpsOverride = this.config.mevPenaltyFeeBps;
368
+ } else {
369
+ appliedTier = "STANDARD_RETAIL";
370
+ lpFeeBpsOverride = this.config.baseFeeBps;
371
+ }
372
+ }
373
+ const totalFeeAmount = amountInBn.mul(new BN(lpFeeBpsOverride)).div(new BN(1e4));
374
+ let baseLpFeeAmount = totalFeeAmount;
375
+ let mevSurchargeAmount = new BN(0);
376
+ let lpMevRebateAmount = new BN(0);
377
+ let protocolEcosystemShareAmount = new BN(0);
378
+ if (lpFeeBpsOverride > this.config.baseFeeBps) {
379
+ baseLpFeeAmount = amountInBn.mul(new BN(this.config.baseFeeBps)).div(new BN(1e4));
380
+ mevSurchargeAmount = totalFeeAmount.sub(baseLpFeeAmount);
381
+ lpMevRebateAmount = mevSurchargeAmount.mul(new BN(this.config.lpMevRebateShareBps)).div(new BN(1e4));
382
+ protocolEcosystemShareAmount = mevSurchargeAmount.sub(lpMevRebateAmount);
383
+ }
384
+ return {
385
+ allowed: true,
386
+ appliedTier,
387
+ lpFeeBpsOverride,
388
+ usedFallbackBaseFee,
389
+ synchronousCrossChainRpcCalls: 0,
390
+ feeBreakdown: {
391
+ totalFeeAmount: totalFeeAmount.toString(10),
392
+ baseLpFeeAmount: baseLpFeeAmount.toString(10),
393
+ mevSurchargeAmount: mevSurchargeAmount.toString(10),
394
+ lpMevRebateAmount: lpMevRebateAmount.toString(10),
395
+ protocolEcosystemShareAmount: protocolEcosystemShareAmount.toString(10),
396
+ lpMevRebateShareBps: this.config.lpMevRebateShareBps
397
+ },
398
+ ...fallbackReason ? { fallbackReason } : {}
399
+ };
400
+ }
401
+ async validateTicketInternal(ticket, expectedTrader, amountInStr, currentTimestamp, consumeNonce) {
402
+ assertValidTimestamp(currentTimestamp, "currentTimestamp");
403
+ if (!ticket) return {
404
+ valid: false,
405
+ reason: "NO_TICKET_PROVIDED"
406
+ };
407
+ assertZeroPiiInHookData(ticket);
408
+ try {
409
+ const { claims } = ticket;
410
+ if (!claims || typeof claims !== "object") return {
411
+ valid: false,
412
+ reason: "MALFORMED_CLAIMS"
413
+ };
414
+ if (typeof claims.chainId !== "string" || typeof claims.poolId !== "string" || typeof claims.hookAddress !== "string" || typeof claims.traderAddress !== "string" || typeof claims.holderDid !== "string" || typeof claims.nonce !== "string" || typeof ticket.signerDid !== "string") return {
415
+ valid: false,
416
+ reason: "MALFORMED_CLAIMS"
417
+ };
418
+ const holderDidNorm = normalizeScreeningAddress(assertSafeString(claims.holderDid, "claims.holderDid"));
419
+ const nonceSafe = assertSafeString(claims.nonce, "claims.nonce");
420
+ if (!VALID_HOOK_TIERS.has(claims.tier)) return {
421
+ valid: false,
422
+ reason: "UNSUPPORTED_FEE_TIER"
423
+ };
424
+ if (claims.chainId !== this.config.chainId) return {
425
+ valid: false,
426
+ reason: "CHAIN_ID_MISMATCH"
427
+ };
428
+ if (claims.poolId.toLowerCase() !== this.config.poolId) return {
429
+ valid: false,
430
+ reason: "POOL_ID_MISMATCH"
431
+ };
432
+ if (claims.hookAddress.toLowerCase() !== this.config.hookAddress) return {
433
+ valid: false,
434
+ reason: "HOOK_ADDRESS_MISMATCH"
435
+ };
436
+ if (claims.traderAddress.toLowerCase() !== expectedTrader) return {
437
+ valid: false,
438
+ reason: "TRADER_ADDRESS_MISMATCH"
439
+ };
440
+ if (typeof claims.issuedAt !== "number" || !Number.isSafeInteger(claims.issuedAt) || typeof claims.validUntil !== "number" || !Number.isSafeInteger(claims.validUntil) || claims.validUntil <= claims.issuedAt) return {
441
+ valid: false,
442
+ reason: "MALFORMED_CLAIMS"
443
+ };
444
+ if (currentTimestamp < claims.issuedAt || currentTimestamp > claims.validUntil) return {
445
+ valid: false,
446
+ reason: "TICKET_EXPIRED_OR_NOT_YET_VALID"
447
+ };
448
+ if (claims.validUntil - claims.issuedAt > MAX_HOOK_TICKET_TTL_SECONDS) return {
449
+ valid: false,
450
+ reason: "TICKET_TTL_EXCEEDED"
451
+ };
452
+ const nonceKey = `${expectedTrader}:${holderDidNorm}:${nonceSafe}`;
453
+ if (this.consumedNonces.has(nonceKey)) return {
454
+ valid: false,
455
+ reason: "TICKET_NONCE_ALREADY_USED"
456
+ };
457
+ const maxAmountBn = parsePositiveBn(claims.maxAmountIn, "claims.maxAmountIn");
458
+ if (parsePositiveBn(amountInStr, "amountIn").gt(maxAmountBn)) return {
459
+ valid: false,
460
+ reason: "AMOUNT_EXCEEDS_TICKET_CAP"
461
+ };
462
+ const minHoldingBlocks = this.config.minHoldingBlocks ?? DEFAULT_MIN_HOLDING_BLOCKS;
463
+ if ((claims.tier === "VIP_LOYALTY" || claims.tier === "ABT_STAKER") && claims.holdingBlocks < minHoldingBlocks) return {
464
+ valid: false,
465
+ reason: "HOLDING_DURATION_TOO_SHORT"
466
+ };
467
+ const expectedTierFee = claims.tier === "VIP_LOYALTY" ? this.config.vipFeeBps : claims.tier === "ABT_STAKER" ? this.config.abtStakerFeeBps : claims.tier === "VERIFIED_DID" ? this.config.verifiedDidFeeBps : claims.tier === "MEV_SURCHARGE" ? this.config.mevPenaltyFeeBps : this.config.baseFeeBps;
468
+ if (claims.feeBpsOverride < expectedTierFee) return {
469
+ valid: false,
470
+ reason: "FEE_OVERRIDE_BELOW_TIER_FLOOR"
471
+ };
472
+ if (claims.kycVerified) {
473
+ const issuerNorm = normalizeScreeningAddress(claims.kycIssuerDid || "");
474
+ if (!issuerNorm) return {
475
+ valid: false,
476
+ reason: "MISSING_KYC_ISSUER"
477
+ };
478
+ if (this.config.trustedKycIssuerDids && this.config.trustedKycIssuerDids.length > 0) {
479
+ if (!this.config.trustedKycIssuerDids.includes(issuerNorm)) return {
480
+ valid: false,
481
+ reason: "UNTRUSTED_KYC_ISSUER"
482
+ };
483
+ }
484
+ }
485
+ const normalizedSigner = normalizeScreeningAddress(ticket.signerDid);
486
+ if (!this.config.authorizedSignerDids.includes(normalizedSigner)) return {
487
+ valid: false,
488
+ reason: "UNAUTHORIZED_TICKET_SIGNER"
489
+ };
490
+ if (!await verifyOcapHookTicketSignature(ticket)) return {
491
+ valid: false,
492
+ reason: "INVALID_TICKET_SIGNATURE"
493
+ };
494
+ if (consumeNonce) this.consumedNonces.set(nonceKey, claims.validUntil);
495
+ return { valid: true };
496
+ } catch {
497
+ return {
498
+ valid: false,
499
+ reason: "MALFORMED_CLAIMS"
500
+ };
501
+ }
502
+ }
503
+ };
504
+ const OCAP_VERIFIED_HOOK_SOLIDITY_SPEC = {
505
+ contractName: "OcapVerifiedHook",
506
+ uniswapVersion: "v4-core",
507
+ implementedHooks: [
508
+ "beforeInitialize",
509
+ "beforeAddLiquidity",
510
+ "beforeSwap"
511
+ ],
512
+ ofacOracleAddress: CHAINALYSIS_OFAC_ORACLE_ADDRESS,
513
+ synchronousCrossChainRpcDependency: false
514
+ };
515
+
516
+ //#endregion
517
+ export { DEFAULT_MIN_HOLDING_BLOCKS, MAX_HOOK_TICKET_TTL_SECONDS, MAX_V4_DYNAMIC_FEE_BPS, MIN_LP_MEV_REBATE_SHARE_BPS, OCAP_VERIFIED_HOOK_SOLIDITY_SPEC, OcapVerifiedHookEngine, assertZeroPiiInHookData, computeOcapHookTicketDigest, issueOcapHookTicket, verifyOcapHookTicketSignature };