@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,376 @@
1
+ import { 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
+
7
+ //#region src/arcvault-external-adapter.ts
8
+ const FORBIDDEN_KEYS = new Set([
9
+ "__proto__",
10
+ "constructor",
11
+ "prototype"
12
+ ]);
13
+ const CANONICAL_UINT_REGEX = /^\d+$/;
14
+ const SELECTOR_HEX_REGEX = /^0x[0-9a-fA-F]{8}$/;
15
+ const ACC_PRECISION = new BN("1000000000000000000", 10);
16
+ /** Forbidden raw ERC-20 / Permit2 selectors that could drain vault funds if called on an arbitrary target */
17
+ const FORBIDDEN_EXTERNAL_CALL_SELECTORS = new Set([
18
+ "0x095ea7b3",
19
+ "0xa9059cbb",
20
+ "0x23b872dd",
21
+ "0xd505accf",
22
+ "0x39509351",
23
+ "0xa457c2d7",
24
+ "0x36c78516",
25
+ "0x0d58b1db",
26
+ "0x87517c45",
27
+ "0x2b67b570",
28
+ "0x2a2d80d1",
29
+ "0x30f28b7a",
30
+ "0xedd9444b"
31
+ ]);
32
+ const MIN_VAULT_LIQUID_BUFFER_BPS = 2e3;
33
+ const MAX_VAULT_STRATEGY_DEPLOYED_BPS = 8e3;
34
+ const MAX_ZAP_PRICE_IMPACT_BPS = 500;
35
+ const MAX_HARVEST_YIELD_BPS = 5e3;
36
+ const MAX_ZAP_ABT_PER_SETTLEMENT_SCALAR = new BN("100000000000000", 10);
37
+ function assertSafeId(val, label) {
38
+ if (typeof val !== "string") throw new CustomError("INVALID_ARCVAULT_ADAPTER", `${label} must be a non-empty string`);
39
+ const trimmed = val.trim();
40
+ if (!trimmed || FORBIDDEN_KEYS.has(trimmed)) throw new CustomError("INVALID_ARCVAULT_ADAPTER", `Invalid or unsafe ${label}`);
41
+ return trimmed;
42
+ }
43
+ function parsePositiveBn(val, label) {
44
+ if (typeof val !== "string" || !CANONICAL_UINT_REGEX.test(val)) throw new CustomError("INVALID_ARCVAULT_ADAPTER", `${label} must be a canonical base-10 integer string`);
45
+ const bn = new BN(val, 10);
46
+ if (bn.lte(new BN(0))) throw new CustomError("INVALID_ARCVAULT_ADAPTER", `${label} must be strictly positive`);
47
+ return bn;
48
+ }
49
+ function parseNonNegativeBn(val, label) {
50
+ if (typeof val !== "string" || !CANONICAL_UINT_REGEX.test(val)) throw new CustomError("INVALID_ARCVAULT_ADAPTER", `${label} must be a canonical non-negative integer string`);
51
+ return new BN(val, 10);
52
+ }
53
+ /**
54
+ * ArcVault External Swap Hook + ERC-4626 Non-Commingled Yield Adapter + Universal ABT Zap-In Engine (#1170).
55
+ */
56
+ var OcapArcVaultExternalAdapterEngine = class {
57
+ constructor(options) {
58
+ this.allowlistedRouters = /* @__PURE__ */ new Set();
59
+ this.allowlistedSelectors = /* @__PURE__ */ new Set();
60
+ this.consumedSwapIds = /* @__PURE__ */ new Set();
61
+ this.consumedZapIds = /* @__PURE__ */ new Set();
62
+ this.ofacSet = /* @__PURE__ */ new Set();
63
+ this.liquidBufferBn = new BN(0);
64
+ this.strategyDeployedBn = new BN(0);
65
+ this.totalPrincipalSharesBn = new BN(0);
66
+ this.accYieldPerShareScaledBn = new BN(0);
67
+ this.unclaimedYieldReserveBn = new BN(0);
68
+ this.shareholders = /* @__PURE__ */ new Map();
69
+ if (!options || typeof options !== "object") throw new CustomError("INVALID_ARCVAULT_ADAPTER", "Missing OcapArcVaultExternalAdapterEngine options");
70
+ this.vaultId = assertSafeId(options.vaultId, "vaultId");
71
+ this.settlementToken = normalizeScreeningAddress(assertSafeId(options.settlementToken, "settlementToken"));
72
+ this.abtTokenAddress = normalizeScreeningAddress(assertSafeId(options.abtTokenAddress, "abtTokenAddress"));
73
+ this.erc4626StrategyVault = normalizeScreeningAddress(assertSafeId(options.erc4626StrategyVault, "erc4626StrategyVault"));
74
+ if (this.settlementToken === this.erc4626StrategyVault || this.settlementToken === this.abtTokenAddress || this.abtTokenAddress === this.erc4626StrategyVault) throw new CustomError("INVALID_ARCVAULT_ADAPTER", "settlementToken, abtTokenAddress, and erc4626StrategyVault must be pairwise distinct");
75
+ if (!Array.isArray(options.allowlistedRouters) || options.allowlistedRouters.length === 0) throw new CustomError("INVALID_ARCVAULT_ADAPTER", "allowlistedRouters must be a non-empty array");
76
+ for (const r of options.allowlistedRouters) {
77
+ const norm = normalizeScreeningAddress(assertSafeId(r, "allowlistedRouter"));
78
+ if (norm === this.settlementToken || norm === this.abtTokenAddress || norm === this.erc4626StrategyVault) throw new CustomError("INVALID_ARCVAULT_ADAPTER", `Router ${norm} cannot be a protected token or strategy vault address`);
79
+ this.allowlistedRouters.add(norm);
80
+ }
81
+ if (!Array.isArray(options.allowlistedSelectors) || options.allowlistedSelectors.length === 0) throw new CustomError("INVALID_ARCVAULT_ADAPTER", "allowlistedSelectors must be a non-empty array");
82
+ for (const sel of options.allowlistedSelectors) {
83
+ if (typeof sel !== "string" || !SELECTOR_HEX_REGEX.test(sel)) throw new CustomError("INVALID_ARCVAULT_ADAPTER", `Invalid 4-byte function selector: ${String(sel)}`);
84
+ const lower = sel.toLowerCase();
85
+ if (FORBIDDEN_EXTERNAL_CALL_SELECTORS.has(lower)) throw new CustomError("FORBIDDEN_SELECTOR", `Selector ${lower} is forbidden on external swap routers to prevent arbitrary token drains`);
86
+ this.allowlistedSelectors.add(lower);
87
+ }
88
+ if (options.ofacBlocklist) for (const a of options.ofacBlocklist) this.ofacSet.add(normalizeScreeningAddress(a));
89
+ assertNotOfacSanctioned([
90
+ this.settlementToken,
91
+ this.abtTokenAddress,
92
+ this.erc4626StrategyVault,
93
+ ...Array.from(this.allowlistedRouters)
94
+ ], this.ofacSet);
95
+ }
96
+ assertNotProtectedProtocolAddress(addr, label) {
97
+ if (addr === this.erc4626StrategyVault || addr === this.settlementToken || addr === this.abtTokenAddress || this.allowlistedRouters.has(addr)) throw new CustomError("SELF_DEALING_ADDRESS_FORBIDDEN", `${label} (${addr}) cannot equal a protected vault, token, or router address`);
98
+ }
99
+ mergeOfacSet(extra) {
100
+ const combined = new Set(this.ofacSet);
101
+ if (extra) for (const a of extra) combined.add(normalizeScreeningAddress(a));
102
+ return combined;
103
+ }
104
+ /**
105
+ * Executes an allowlisted external DEX swap (`executeExternalSwap`) with:
106
+ * - Strict router & selector allowlist enforcement (blocking ERC-20 & Permit2 `approve`/`transferFrom`)
107
+ * - Token pair anchor verification (at least one leg must be `settlementToken` or `abtTokenAddress`, and neither leg can be `erc4626StrategyVault` or a router)
108
+ * - Transient exact-amount approval (`amountIn` before call, `0` immediately after call)
109
+ * - Pre/post balance snapshot verification (`actualAmountOut >= minAmountOut` and exact `amountIn` debit)
110
+ */
111
+ executeExternalSwap(input) {
112
+ if (!input || typeof input !== "object") throw new CustomError("INVALID_EXTERNAL_SWAP", "Missing ExternalSwapHookInput");
113
+ const swapId = assertSafeId(input.swapId, "swapId");
114
+ if (this.consumedSwapIds.has(swapId)) throw new CustomError("REPLAYED_EXTERNAL_SWAP", `External swap ${swapId} has already been executed`);
115
+ const router = normalizeScreeningAddress(assertSafeId(input.routerAddress, "routerAddress"));
116
+ if (!this.allowlistedRouters.has(router)) throw new CustomError("UNAUTHORIZED_SWAP_ROUTER", `Router ${router} is not in allowlistedRouters`);
117
+ if (typeof input.callSelector !== "string" || !SELECTOR_HEX_REGEX.test(input.callSelector)) throw new CustomError("INVALID_EXTERNAL_SWAP", "callSelector must be a 4-byte 0x hex string");
118
+ const selector = input.callSelector.toLowerCase();
119
+ if (FORBIDDEN_EXTERNAL_CALL_SELECTORS.has(selector) || !this.allowlistedSelectors.has(selector)) throw new CustomError("UNAUTHORIZED_SWAP_SELECTOR", `Selector ${selector} is not allowlisted for external swap`);
120
+ const tokenIn = normalizeScreeningAddress(assertSafeId(input.tokenIn, "tokenIn"));
121
+ const tokenOut = normalizeScreeningAddress(assertSafeId(input.tokenOut, "tokenOut"));
122
+ if (tokenIn === tokenOut) throw new CustomError("INVALID_EXTERNAL_SWAP", "tokenIn and tokenOut must be distinct");
123
+ if (tokenIn === this.erc4626StrategyVault || tokenOut === this.erc4626StrategyVault || this.allowlistedRouters.has(tokenIn) || this.allowlistedRouters.has(tokenOut)) throw new CustomError("UNAUTHORIZED_SWAP_TOKEN", "External swap cannot touch erc4626StrategyVault shares or router addresses");
124
+ if (!(tokenIn === this.settlementToken || tokenOut === this.settlementToken || tokenIn === this.abtTokenAddress || tokenOut === this.abtTokenAddress)) throw new CustomError("UNANCHORED_SWAP_PAIR", `External swap (${tokenIn} -> ${tokenOut}) must anchor to settlementToken (${this.settlementToken}) or abtTokenAddress (${this.abtTokenAddress})`);
125
+ assertNotOfacSanctioned([
126
+ router,
127
+ tokenIn,
128
+ tokenOut
129
+ ], this.mergeOfacSet(input.ofacBlocklist));
130
+ const amountInBn = parsePositiveBn(input.amountIn, "amountIn");
131
+ const minAmountOutBn = parsePositiveBn(input.minAmountOut, "minAmountOut");
132
+ const preInBn = parseNonNegativeBn(input.preBalanceIn, "preBalanceIn");
133
+ const postInBn = parseNonNegativeBn(input.postBalanceIn, "postBalanceIn");
134
+ const preOutBn = parseNonNegativeBn(input.preBalanceOut, "preBalanceOut");
135
+ const postOutBn = parseNonNegativeBn(input.postBalanceOut, "postBalanceOut");
136
+ if (tokenIn === this.settlementToken) {
137
+ if (amountInBn.gt(this.liquidBufferBn)) throw new CustomError("SWAP_EXCEEDS_LIQUID_BUFFER", `Swap amountIn (${amountInBn.toString(10)}) exceeds available vault liquidBufferBalance (${this.liquidBufferBn.toString(10)})`);
138
+ const postBackingBn = this.liquidBufferBn.sub(amountInBn).add(this.strategyDeployedBn);
139
+ if (postBackingBn.lt(this.totalPrincipalSharesBn)) throw new CustomError("SWAP_BREACHES_PRINCIPAL_BACKING", `Swap amountIn (${amountInBn.toString(10)}) would reduce total vault backing (${postBackingBn.toString(10)}) below totalPrincipalShares (${this.totalPrincipalSharesBn.toString(10)})`);
140
+ }
141
+ if (preInBn.lt(amountInBn)) throw new CustomError("INSUFFICIENT_SWAP_INPUT", "preBalanceIn is less than amountIn");
142
+ if (postInBn.gt(preInBn)) throw new CustomError("INVALID_SWAP_BALANCE_DELTA", "postBalanceIn cannot exceed preBalanceIn");
143
+ const exactSpentBn = preInBn.sub(postInBn);
144
+ if (!exactSpentBn.eq(amountInBn)) throw new CustomError("UNEXPECTED_INPUT_DEBIT", `External swap spent ${exactSpentBn.toString(10)} of tokenIn, expected exact amountIn (${amountInBn.toString(10)})`);
145
+ if (postOutBn.lt(preOutBn)) throw new CustomError("INVALID_SWAP_BALANCE_DELTA", "postBalanceOut cannot be less than preBalanceOut");
146
+ const actualReceivedBn = postOutBn.sub(preOutBn);
147
+ if (actualReceivedBn.lt(minAmountOutBn)) throw new CustomError("SWAP_SLIPPAGE_EXCEEDED", `Actual output received (${actualReceivedBn.toString(10)}) is less than minAmountOut (${minAmountOutBn.toString(10)})`);
148
+ if (tokenIn === this.settlementToken) this.liquidBufferBn = this.liquidBufferBn.sub(exactSpentBn);
149
+ if (tokenOut === this.settlementToken) this.liquidBufferBn = this.liquidBufferBn.add(actualReceivedBn);
150
+ this.consumedSwapIds.add(swapId);
151
+ const digestPayload = `ocap:arcvault-swap:v1:${this.vaultId.length}:${this.vaultId}:${swapId.length}:${swapId}:${router}:${selector}:${tokenIn}:${tokenOut}:${exactSpentBn.toString(10)}:${actualReceivedBn.toString(10)}`;
152
+ const balanceInvariantDigest = `0x${Hasher.SHA3.hash256(Buffer.from(digestPayload, "utf8")).replace(/^0x/, "").toLowerCase()}`;
153
+ return {
154
+ swapId,
155
+ routerAddress: router,
156
+ tokenIn,
157
+ tokenOut,
158
+ exactAmountSpent: exactSpentBn.toString(10),
159
+ actualAmountReceived: actualReceivedBn.toString(10),
160
+ transientApprovalBeforeCall: amountInBn.toString(10),
161
+ transientApprovalAfterCall: "0",
162
+ balanceInvariantDigest
163
+ };
164
+ }
165
+ /**
166
+ * Deposits settlement tokens directly into ArcVault, minting 1:1 principal shares for `holderDid`
167
+ * and routing liquidity according to the 20% Liquid Buffer / 80% ERC-4626 Strategy policy.
168
+ */
169
+ depositAndAllocate(params) {
170
+ const holder = normalizeScreeningAddress(assertSafeId(params.holderDid, "holderDid"));
171
+ this.assertNotProtectedProtocolAddress(holder, "holderDid");
172
+ assertNotOfacSanctioned([holder], this.mergeOfacSet(params.ofacBlocklist));
173
+ const amountBn = parsePositiveBn(params.amount, "amount");
174
+ const existing = this.shareholders.get(holder) || {
175
+ holderDid: holder,
176
+ principalShares: "0",
177
+ yieldDebtScaled: "0",
178
+ accruedUnclaimedYield: "0"
179
+ };
180
+ const prevSharesBn = new BN(existing.principalShares, 10);
181
+ const prevDebtScaledBn = new BN(existing.yieldDebtScaled, 10);
182
+ const prevAccruedBn = new BN(existing.accruedUnclaimedYield, 10);
183
+ const pendingYieldBn = prevSharesBn.mul(this.accYieldPerShareScaledBn).sub(prevDebtScaledBn).div(ACC_PRECISION);
184
+ const nextSharesBn = prevSharesBn.add(amountBn);
185
+ const nextDebtScaledBn = nextSharesBn.mul(this.accYieldPerShareScaledBn);
186
+ this.shareholders.set(holder, {
187
+ holderDid: holder,
188
+ principalShares: nextSharesBn.toString(10),
189
+ yieldDebtScaled: nextDebtScaledBn.toString(10),
190
+ accruedUnclaimedYield: prevAccruedBn.add(pendingYieldBn).toString(10)
191
+ });
192
+ this.totalPrincipalSharesBn = this.totalPrincipalSharesBn.add(amountBn);
193
+ this.liquidBufferBn = this.liquidBufferBn.add(amountBn);
194
+ if (params.autoDeployToStrategy !== false) this.rebalanceToTargetAllocation();
195
+ return this.getVaultState();
196
+ }
197
+ /**
198
+ * Enforces the 20% Liquid Buffer / 80% Allowlisted ERC-4626 Strategy allocation invariant.
199
+ * Uses ceiling division for the 20% minimum liquid buffer so `liquidBufferBalance` is NEVER
200
+ * even 1 wei below 20% of total backing (`liquidBufferBalance + strategyDeployedBalance`).
201
+ */
202
+ rebalanceToTargetAllocation() {
203
+ const totalBackingBn = this.liquidBufferBn.add(this.strategyDeployedBn);
204
+ if (totalBackingBn.isZero()) return this.getVaultState();
205
+ const minLiquidBn = totalBackingBn.muln(MIN_VAULT_LIQUID_BUFFER_BPS).addn(9999).divn(1e4);
206
+ const maxStrategyBn = totalBackingBn.sub(minLiquidBn);
207
+ this.liquidBufferBn = minLiquidBn;
208
+ this.strategyDeployedBn = maxStrategyBn;
209
+ return this.getVaultState();
210
+ }
211
+ /**
212
+ * Withdraws principal shares for `holderDid`. If `withdrawAmount > liquidBufferBalance`,
213
+ * automatically recalls the shortfall from the ERC-4626 strategy adapter AND restores the 20%
214
+ * minimum liquid buffer on the remaining vault backing.
215
+ */
216
+ withdrawWithAutoRecall(params) {
217
+ const holder = normalizeScreeningAddress(assertSafeId(params.holderDid, "holderDid"));
218
+ assertNotOfacSanctioned([holder], this.mergeOfacSet(params.ofacBlocklist));
219
+ const withdrawBn = parsePositiveBn(params.withdrawAmount, "withdrawAmount");
220
+ const existing = this.shareholders.get(holder);
221
+ if (!existing) throw new CustomError("NOT_FOUND", `Shareholder ${holder} not found in vault ${this.vaultId}`);
222
+ const prevSharesBn = new BN(existing.principalShares, 10);
223
+ if (prevSharesBn.lt(withdrawBn)) throw new CustomError("INSUFFICIENT_VAULT_SHARES", `Shareholder ${holder} has ${prevSharesBn.toString(10)} shares, cannot withdraw ${withdrawBn.toString(10)}`);
224
+ const totalBackingBn = this.liquidBufferBn.add(this.strategyDeployedBn);
225
+ if (totalBackingBn.lt(withdrawBn)) throw new CustomError("VAULT_INSOLVENT", "Total vault backing is insufficient for withdrawal");
226
+ const prevDebtScaledBn = new BN(existing.yieldDebtScaled, 10);
227
+ const prevAccruedBn = new BN(existing.accruedUnclaimedYield, 10);
228
+ const pendingYieldBn = prevSharesBn.mul(this.accYieldPerShareScaledBn).sub(prevDebtScaledBn).div(ACC_PRECISION);
229
+ const nextSharesBn = prevSharesBn.sub(withdrawBn);
230
+ const nextDebtScaledBn = nextSharesBn.mul(this.accYieldPerShareScaledBn);
231
+ this.shareholders.set(holder, {
232
+ holderDid: holder,
233
+ principalShares: nextSharesBn.toString(10),
234
+ yieldDebtScaled: nextDebtScaledBn.toString(10),
235
+ accruedUnclaimedYield: prevAccruedBn.add(pendingYieldBn).toString(10)
236
+ });
237
+ this.totalPrincipalSharesBn = this.totalPrincipalSharesBn.sub(withdrawBn);
238
+ const requiredPostLiquidBn = totalBackingBn.sub(withdrawBn).muln(MIN_VAULT_LIQUID_BUFFER_BPS).addn(9999).divn(1e4);
239
+ const totalLiquidNeededNowBn = withdrawBn.add(requiredPostLiquidBn);
240
+ let recalledBn = new BN(0);
241
+ if (this.liquidBufferBn.lt(totalLiquidNeededNowBn)) {
242
+ const neededRecallBn = totalLiquidNeededNowBn.sub(this.liquidBufferBn);
243
+ recalledBn = neededRecallBn.gt(this.strategyDeployedBn) ? this.strategyDeployedBn : neededRecallBn;
244
+ this.strategyDeployedBn = this.strategyDeployedBn.sub(recalledBn);
245
+ this.liquidBufferBn = this.liquidBufferBn.add(recalledBn);
246
+ }
247
+ this.liquidBufferBn = this.liquidBufferBn.sub(withdrawBn);
248
+ return {
249
+ withdrawnAmount: withdrawBn.toString(10),
250
+ recalledFromStrategy: recalledBn.toString(10),
251
+ vaultState: this.getVaultState()
252
+ };
253
+ }
254
+ /**
255
+ * Harvests yield generated by the allowlisted ERC-4626 strategy vault and distributes it
256
+ * in `O(1)` time via `accYieldPerShareScaled` backed 100% by `unclaimedYieldReserve`.
257
+ */
258
+ harvestVaultYield(yieldAmount) {
259
+ const yieldBn = parsePositiveBn(yieldAmount, "yieldAmount");
260
+ if (this.totalPrincipalSharesBn.isZero()) throw new CustomError("EMPTY_VAULT_SHARES", "Cannot harvest yield when totalPrincipalShares is 0");
261
+ if (this.strategyDeployedBn.isZero()) throw new CustomError("EMPTY_STRATEGY_DEPLOYMENT", "Cannot harvest ERC-4626 strategy yield when strategyDeployedBalance is 0");
262
+ const maxAllowedHarvestBn = this.strategyDeployedBn.muln(MAX_HARVEST_YIELD_BPS).divn(1e4);
263
+ if (yieldBn.gt(maxAllowedHarvestBn)) throw new CustomError("EXCESSIVE_YIELD_HARVEST", `Yield amount (${yieldBn.toString(10)}) exceeds maximum single-harvest cap (${maxAllowedHarvestBn.toString(10)}) on strategyDeployedBalance (${this.strategyDeployedBn.toString(10)})`);
264
+ const deltaAccScaled = yieldBn.mul(ACC_PRECISION).div(this.totalPrincipalSharesBn);
265
+ if (deltaAccScaled.isZero()) throw new CustomError("YIELD_TOO_SMALL_FOR_DISTRIBUTION", "Yield amount is too small relative to totalPrincipalShares and would round to 0 per share");
266
+ this.accYieldPerShareScaledBn = this.accYieldPerShareScaledBn.add(deltaAccScaled);
267
+ this.unclaimedYieldReserveBn = this.unclaimedYieldReserveBn.add(yieldBn);
268
+ return this.getVaultState();
269
+ }
270
+ /**
271
+ * Claims accrued ERC-4626 strategy yield for `holderDid` in `O(1)` time.
272
+ */
273
+ claimVaultYield(holderDid, ofacBlocklist) {
274
+ const holder = normalizeScreeningAddress(assertSafeId(holderDid, "holderDid"));
275
+ assertNotOfacSanctioned([holder], this.mergeOfacSet(ofacBlocklist));
276
+ const pos = this.shareholders.get(holder);
277
+ if (!pos) throw new CustomError("NOT_FOUND", `Shareholder ${holder} not found in vault ${this.vaultId}`);
278
+ const sharesBn = new BN(pos.principalShares, 10);
279
+ const debtScaledBn = new BN(pos.yieldDebtScaled, 10);
280
+ const accruedBn = new BN(pos.accruedUnclaimedYield, 10);
281
+ const newlyEarnedBn = sharesBn.mul(this.accYieldPerShareScaledBn).sub(debtScaledBn).div(ACC_PRECISION);
282
+ const totalClaimableBn = accruedBn.add(newlyEarnedBn);
283
+ if (this.unclaimedYieldReserveBn.lt(totalClaimableBn)) throw new CustomError("INSUFFICIENT_YIELD_RESERVE", "Insufficient unclaimed yield reserve");
284
+ this.unclaimedYieldReserveBn = this.unclaimedYieldReserveBn.sub(totalClaimableBn);
285
+ pos.yieldDebtScaled = sharesBn.mul(this.accYieldPerShareScaledBn).toString(10);
286
+ pos.accruedUnclaimedYield = "0";
287
+ return {
288
+ claimedYield: totalClaimableBn.toString(10),
289
+ shareholderPosition: { ...pos }
290
+ };
291
+ }
292
+ /**
293
+ * Universal `ABT` Zap-In Funnel (`zapInAndBridge`):
294
+ * Converts arbitrary origin-chain `tokenIn` -> `settlementToken` (deposited & allocated into ArcVault)
295
+ * -> `OCAP ABT` for `recipientDid` with router/selector allowlist, slippage caps, exchange-rate bounds, and OFAC screening.
296
+ */
297
+ zapInAndBridge(input) {
298
+ if (!input || typeof input !== "object") throw new CustomError("INVALID_ZAP_IN", "Missing UniversalAbtZapInInput");
299
+ const zapId = assertSafeId(input.zapId, "zapId");
300
+ if (this.consumedZapIds.has(zapId)) throw new CustomError("REPLAYED_ZAP_IN", `Zap-In ${zapId} has already been processed`);
301
+ const sender = normalizeScreeningAddress(assertSafeId(input.senderAddress, "senderAddress"));
302
+ const recipient = normalizeScreeningAddress(assertSafeId(input.recipientDid, "recipientDid"));
303
+ const router = normalizeScreeningAddress(assertSafeId(input.routerAddress, "routerAddress"));
304
+ const tokenIn = normalizeScreeningAddress(assertSafeId(input.tokenIn, "tokenIn"));
305
+ this.assertNotProtectedProtocolAddress(sender, "senderAddress");
306
+ this.assertNotProtectedProtocolAddress(recipient, "recipientDid");
307
+ if (tokenIn === this.erc4626StrategyVault || tokenIn === this.abtTokenAddress || this.allowlistedRouters.has(tokenIn)) throw new CustomError("INVALID_ZAP_TOKEN_IN", `tokenIn (${tokenIn}) cannot be erc4626StrategyVault, abtTokenAddress, or a router address`);
308
+ if (!this.allowlistedRouters.has(router)) throw new CustomError("UNAUTHORIZED_SWAP_ROUTER", `Router ${router} is not in allowlistedRouters`);
309
+ if (typeof input.callSelector !== "string" || !SELECTOR_HEX_REGEX.test(input.callSelector)) throw new CustomError("INVALID_ZAP_IN", "callSelector must be a 4-byte 0x hex string");
310
+ const selector = input.callSelector.toLowerCase();
311
+ if (FORBIDDEN_EXTERNAL_CALL_SELECTORS.has(selector) || !this.allowlistedSelectors.has(selector)) throw new CustomError("UNAUTHORIZED_SWAP_SELECTOR", `Selector ${selector} is not allowlisted`);
312
+ if (!Number.isSafeInteger(input.slippageBps) || input.slippageBps <= 0 || input.slippageBps > MAX_ZAP_PRICE_IMPACT_BPS) throw new CustomError("EXCESSIVE_ZAP_SLIPPAGE", `slippageBps (${input.slippageBps}) must be an integer between 1 and ${MAX_ZAP_PRICE_IMPACT_BPS}`);
313
+ const combinedOfac = this.mergeOfacSet(input.ofacBlocklist);
314
+ assertNotOfacSanctioned([
315
+ sender,
316
+ recipient,
317
+ router,
318
+ tokenIn
319
+ ], combinedOfac);
320
+ const amountInBn = parsePositiveBn(input.amountIn, "amountIn");
321
+ const quotedSettlementBn = parsePositiveBn(input.quotedSettlementOut, "quotedSettlementOut");
322
+ const minSettlementBn = parsePositiveBn(input.minSettlementOut, "minSettlementOut");
323
+ const quotedAbtBn = parsePositiveBn(input.quotedAbtOut, "quotedAbtOut");
324
+ const minAbtBn = parsePositiveBn(input.minAbtOut, "minAbtOut");
325
+ if (tokenIn === this.settlementToken && !quotedSettlementBn.eq(amountInBn)) throw new CustomError("INVALID_ZAP_IN", "When tokenIn equals settlementToken, quotedSettlementOut must equal amountIn");
326
+ const maxAllowedSettlementBn = amountInBn.mul(MAX_ZAP_ABT_PER_SETTLEMENT_SCALAR);
327
+ if (quotedSettlementBn.gt(maxAllowedSettlementBn)) throw new CustomError("EXCESSIVE_ZAP_EXCHANGE_RATE", `quotedSettlementOut (${quotedSettlementBn.toString(10)}) exceeds maximum allowed exchange rate ratio against amountIn (${amountInBn.toString(10)})`);
328
+ const maxAllowedAbtBn = quotedSettlementBn.mul(MAX_ZAP_ABT_PER_SETTLEMENT_SCALAR);
329
+ if (quotedAbtBn.gt(maxAllowedAbtBn)) throw new CustomError("EXCESSIVE_ZAP_EXCHANGE_RATE", `quotedAbtOut (${quotedAbtBn.toString(10)}) exceeds maximum allowed exchange rate ratio against quotedSettlementOut (${quotedSettlementBn.toString(10)})`);
330
+ const minRequiredSettlementFloorBn = quotedSettlementBn.muln(1e4 - input.slippageBps).addn(9999).divn(1e4);
331
+ if (minSettlementBn.lt(minRequiredSettlementFloorBn) || quotedSettlementBn.lt(minSettlementBn)) throw new CustomError("ZAP_SLIPPAGE_FLOOR_VIOLATION", `minSettlementOut (${minSettlementBn.toString(10)}) violates slippage floor (${minRequiredSettlementFloorBn.toString(10)}) or exceeds quotedSettlementOut`);
332
+ let verifiedSettlementOutBn = quotedSettlementBn;
333
+ if (input.preSettlementBalance !== void 0 || input.postSettlementBalance !== void 0) {
334
+ if (input.preSettlementBalance === void 0 || input.postSettlementBalance === void 0) throw new CustomError("INVALID_ZAP_IN", "Both preSettlementBalance and postSettlementBalance must be provided together");
335
+ const preSettleBn = parseNonNegativeBn(input.preSettlementBalance, "preSettlementBalance");
336
+ const postSettleBn = parseNonNegativeBn(input.postSettlementBalance, "postSettlementBalance");
337
+ if (postSettleBn.lt(preSettleBn)) throw new CustomError("INVALID_ZAP_BALANCE_DELTA", "postSettlementBalance cannot be less than preSettlementBalance");
338
+ verifiedSettlementOutBn = postSettleBn.sub(preSettleBn);
339
+ if (verifiedSettlementOutBn.lt(minSettlementBn)) throw new CustomError("ZAP_SLIPPAGE_FLOOR_VIOLATION", `Actual settlement received (${verifiedSettlementOutBn.toString(10)}) is less than minSettlementOut (${minSettlementBn.toString(10)})`);
340
+ }
341
+ const minRequiredAbtFloorBn = quotedAbtBn.muln(1e4 - input.slippageBps).addn(9999).divn(1e4);
342
+ if (minAbtBn.lt(minRequiredAbtFloorBn) || quotedAbtBn.lt(minAbtBn)) throw new CustomError("ZAP_SLIPPAGE_FLOOR_VIOLATION", `minAbtOut (${minAbtBn.toString(10)}) violates slippage floor (${minRequiredAbtFloorBn.toString(10)}) or exceeds quotedAbtOut`);
343
+ this.consumedZapIds.add(zapId);
344
+ const vaultState = this.depositAndAllocate({
345
+ holderDid: recipient,
346
+ amount: verifiedSettlementOutBn.toString(10),
347
+ autoDeployToStrategy: true,
348
+ ofacBlocklist: combinedOfac
349
+ });
350
+ return {
351
+ zapId,
352
+ recipientDid: recipient,
353
+ settlementDepositedToVault: verifiedSettlementOutBn.toString(10),
354
+ abtMintedOnOcap: quotedAbtBn.toString(10),
355
+ vaultState
356
+ };
357
+ }
358
+ getVaultState() {
359
+ const shareholdersObj = {};
360
+ for (const [k, v] of this.shareholders.entries()) shareholdersObj[k] = { ...v };
361
+ return {
362
+ vaultId: this.vaultId,
363
+ settlementToken: this.settlementToken,
364
+ erc4626StrategyVault: this.erc4626StrategyVault,
365
+ liquidBufferBalance: this.liquidBufferBn.toString(10),
366
+ strategyDeployedBalance: this.strategyDeployedBn.toString(10),
367
+ totalPrincipalShares: this.totalPrincipalSharesBn.toString(10),
368
+ accYieldPerShareScaled: this.accYieldPerShareScaledBn.toString(10),
369
+ unclaimedYieldReserve: this.unclaimedYieldReserveBn.toString(10),
370
+ shareholders: shareholdersObj
371
+ };
372
+ }
373
+ };
374
+
375
+ //#endregion
376
+ export { FORBIDDEN_EXTERNAL_CALL_SELECTORS, MAX_HARVEST_YIELD_BPS, MAX_VAULT_STRATEGY_DEPLOYED_BPS, MAX_ZAP_ABT_PER_SETTLEMENT_SCALAR, MAX_ZAP_PRICE_IMPACT_BPS, MIN_VAULT_LIQUID_BUFFER_BPS, OcapArcVaultExternalAdapterEngine };
@@ -0,0 +1,172 @@
1
+ //#region src/encrypted-nft-envelope.d.ts
2
+ declare const ENCRYPTED_NFT_SCHEMA_VERSION: "ocap.nft.encrypted.v1";
3
+ declare const MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS = 8192;
4
+ declare const MAX_ENCRYPTED_NFT_TAGS = 16;
5
+ declare const MAX_ENCRYPTED_NFT_TAG_LENGTH = 64;
6
+ declare const MAX_ENCRYPTED_NFT_CATEGORY_LENGTH = 64;
7
+ declare const MAX_ENCRYPTED_NFT_SUMMARY_LENGTH = 512;
8
+ declare const MAX_ENCRYPTED_NFT_URI_LENGTH = 512;
9
+ type EncryptedNftAlgorithm = 'X25519-XSalsa20-Poly1305' | 'ECIES-Secp256k1-AES256GCM' | 'OCAP-ECDH-HKDF-SHA256';
10
+ declare const VALID_ENCRYPTED_NFT_ALGORITHMS: Set<EncryptedNftAlgorithm>;
11
+ interface EncryptedNftPrivateMetadata {
12
+ /** Private full listing/asset title visible only to current owner after decryption */
13
+ title: string;
14
+ /** Optional detailed specification, prompt recipe, or workflow blueprint */
15
+ description?: string;
16
+ /** Optional AI prompt / workflow recipe or structured configuration */
17
+ recipePayload?: Record<string, unknown>;
18
+ /** Optional ArcSpace access token or signed delivery credential */
19
+ arcSpaceAccessCredential?: string;
20
+ /** Optional high-resolution preview or deliverable sub-path inside ArcSpace */
21
+ arcSpaceDeliverablePath?: string;
22
+ /** Optional custom key-value attributes visible only to the owner */
23
+ privateAttributes?: Record<string, string | number | boolean>;
24
+ }
25
+ interface EncryptedNftPublicDiscoveryHeader {
26
+ schemaVersion: typeof ENCRYPTED_NFT_SCHEMA_VERSION;
27
+ /** Public discovery category (e.g. 'AI_SKILL', 'PLAYWRIGHT_SCRAPER', 'TRANSLATION', 'VECTOR_ASSET') */
28
+ category: string;
29
+ /** Bounded public discovery tags (e.g. ['#AI-Skill', '#Playwright-Scraper']) */
30
+ tags: string[];
31
+ /** Safe public non-alpha summary displayed to external chain scanners */
32
+ publicSummary: string;
33
+ /** Canonical SHA-256 commitment of the decrypted plaintext metadata (`computeEncryptedNftPlaintextHash`) */
34
+ plaintextHash: string;
35
+ /** Canonical SHA-256 commitment of the 32-byte Content Encryption Key (`computeEncryptedNftCekCommitmentHash`) */
36
+ cekCommitmentHash: string;
37
+ /** Compressed 33-byte (66-hex) secp256k1 public key derived from `CEK` (`P_cek = cek * G`) for handover proof verification */
38
+ cekPublicKeyHex: string;
39
+ /** Optional pointer to the encrypted large payload stored in Creator/Holder ArcSpace (`arcspace://...`) */
40
+ arcSpaceUri?: string;
41
+ }
42
+ interface EncryptedNftOwnerCipherEnvelope {
43
+ alg: EncryptedNftAlgorithm;
44
+ /** Current owner DID authorized to decrypt this envelope */
45
+ ownerDid: string;
46
+ /** Normalized 33-byte (66-hex) compressed secp256k1 public key of the current owner */
47
+ recipientPk: string;
48
+ /** Normalized 33-byte (66-hex) compressed secp256k1 ephemeral public key used to wrap `encryptedCek` */
49
+ ephemeralPk: string;
50
+ /** 12-byte (24 hex chars) AES-256-GCM IV used for `ciphertextMetadata` */
51
+ nonce: string;
52
+ /** 32-byte (64 hex chars) wrapped Content Encryption Key (`CEK`) */
53
+ encryptedCek: string;
54
+ /** 16-byte (32 hex chars) authentication tag binding `(ownerDid, recipientPk, ephemeralPk, nonce, cekCommitmentHash)` */
55
+ cekWrapTag: string;
56
+ /** Hex-encoded AES-256-GCM ciphertext of canonical `EncryptedNftPrivateMetadata` */
57
+ ciphertextMetadata: string;
58
+ /** 16-byte (32 hex chars) AES-256-GCM authentication tag with `public` header bound as AAD */
59
+ ciphertextTag: string;
60
+ /** Cryptographic handover digest binding `cekCommitmentHash` and `handoverCount` */
61
+ handoverProofHash: string;
62
+ /** Secp256k1 digital signature over `handoverProofHash` signed by `CEK` (verified against `public.cekPublicKeyHex`) */
63
+ handoverSignature: string;
64
+ /** Monotonic handover counter (`0` on primary mint, incremented by `+1` on every secondary transfer) */
65
+ handoverCount: number;
66
+ }
67
+ interface EncryptedAssetEnvelope {
68
+ public: EncryptedNftPublicDiscoveryHeader;
69
+ encrypted: EncryptedNftOwnerCipherEnvelope;
70
+ }
71
+ interface SealEncryptedNftForOwnerInput {
72
+ ownerDid: string;
73
+ recipientPublicKeyHex: string;
74
+ category: string;
75
+ tags?: string[];
76
+ publicSummary: string;
77
+ arcSpaceUri?: string;
78
+ alg?: EncryptedNftAlgorithm;
79
+ privateMetadata: EncryptedNftPrivateMetadata;
80
+ /** Optional deterministic 32-byte hex CEK (generated via CSPRNG if omitted) */
81
+ cekHex?: string;
82
+ /** Optional deterministic 32-byte hex ephemeral secret key (generated via CSPRNG if omitted) */
83
+ ephemeralSecretKeyHex?: string;
84
+ /** Optional deterministic 12-byte hex AES-GCM nonce (generated via CSPRNG if omitted) */
85
+ nonceHex?: string;
86
+ ofacSanctionedSet?: ReadonlySet<string>;
87
+ }
88
+ interface OpenEncryptedNftAsOwnerInput {
89
+ envelope: EncryptedAssetEnvelope;
90
+ viewerDid: string;
91
+ ownerSecretKeyHex: string;
92
+ /** Actual current `asset.owner` from `statedb.asset` to enforce strict owner-only decryption */
93
+ currentAssetOwnerDid?: string;
94
+ }
95
+ interface OpenEncryptedNftAsOwnerResult {
96
+ ownerDid: string;
97
+ recipientPk: string;
98
+ cekHex: string;
99
+ plaintextHash: string;
100
+ cekCommitmentHash: string;
101
+ privateMetadata: EncryptedNftPrivateMetadata;
102
+ publicHeader: EncryptedNftPublicDiscoveryHeader;
103
+ }
104
+ interface RewrapEncryptedNftForNewOwnerInput {
105
+ envelope: EncryptedAssetEnvelope;
106
+ currentOwnerDid: string;
107
+ currentOwnerSecretKeyHex: string;
108
+ newOwnerDid: string;
109
+ newOwnerPublicKeyHex: string;
110
+ /** Optional deterministic 32-byte hex ephemeral secret key for re-wrapping */
111
+ ephemeralSecretKeyHex?: string;
112
+ ofacSanctionedSet?: ReadonlySet<string>;
113
+ }
114
+ interface VerifyEncryptedNftHandoverInput {
115
+ beforeEnvelope: EncryptedAssetEnvelope;
116
+ afterEnvelope: EncryptedAssetEnvelope;
117
+ expectedPreviousOwnerDid: string;
118
+ expectedNewOwnerDid: string;
119
+ expectedNewOwnerPublicKeyHex: string;
120
+ /**
121
+ * Optional buyer/new-owner secret key or re-wrap ephemeral secret key for interactive/atomic
122
+ * handover verification. When provided, `verifyEncryptedNftHandover` cryptographically unwraps
123
+ * `afterEnvelope.encrypted.encryptedCek` and verifies `computeEncryptedNftCekCommitmentHash(unwrappedCek) === afterEnvelope.public.cekCommitmentHash`,
124
+ * preventing a malicious seller from wrapping a garbage key while signing `handoverSignature` with the old `cekHex`.
125
+ */
126
+ newOwnerSecretKeyHex?: string;
127
+ ephemeralSecretKeyHex?: string;
128
+ }
129
+ declare function canonicalizeEncryptedNftMetadata(metadata: EncryptedNftPrivateMetadata): string;
130
+ /**
131
+ * Deterministic Owner Public Key derivation from a 32-byte hex secret key for `ocap.nft.encrypted.v1` envelopes.
132
+ * Uses `elliptic` `secp256k1` to derive the compressed 33-byte (66-hex) secp256k1 public key.
133
+ */
134
+ declare function deriveOwnerPublicKeyHexFromSecretKey(secretKeyHex: string): string;
135
+ declare function computeEncryptedNftPlaintextHash(metadata: EncryptedNftPrivateMetadata | string): string;
136
+ declare function computeEncryptedNftCekCommitmentHash(cekHex: string): string;
137
+ declare function computeEncryptedNftPublicHeaderAad(header: EncryptedNftPublicDiscoveryHeader): Buffer;
138
+ declare function validateEncryptedAssetEnvelope(envelope: unknown): EncryptedAssetEnvelope;
139
+ /**
140
+ * 1. Direct-to-Buyer Encrypted Mint / Primary SKU Purchase (`sealEncryptedNftForOwner`):
141
+ * - Encrypts `privateMetadata` under a 32-byte symmetric `CEK` using AES-256-GCM with `public` header bound as AAD;
142
+ * - Wraps `CEK` exclusively to `recipientPublicKeyHex` (`buyerPk`);
143
+ * - Commits `plaintextHash`, `cekCommitmentHash`, and `cekPublicKeyHex` in `public`.
144
+ */
145
+ declare function sealEncryptedNftForOwner(input: SealEncryptedNftForOwnerInput): EncryptedAssetEnvelope;
146
+ /**
147
+ * 2. DID Wallet / AI Agent Owner Auto-Decryption (`openEncryptedNftAsOwner`):
148
+ * - Verifies viewer is the current NFT owner (`viewerDid === envelope.encrypted.ownerDid` and `currentAssetOwnerDid`);
149
+ * - Unwraps `CEK` using `ownerSecretKeyHex` and verifies `cekCommitmentHash` and `cekPublicKeyHex`;
150
+ * - Decrypts `ciphertextMetadata` with AES-256-GCM + `public` header AAD and verifies `plaintextHash`.
151
+ */
152
+ declare function openEncryptedNftAsOwner(input: OpenEncryptedNftAsOwnerInput): OpenEncryptedNftAsOwnerResult;
153
+ /**
154
+ * 3. Secondary Market Transfer / Sale Key-Wrap Handover (`rewrapEncryptedNftForNewOwner`):
155
+ * - Decrypts and verifies the existing `CEK` and `ciphertextMetadata` with `currentOwnerSecretKeyHex`
156
+ * (preventing garbage-key swap attacks);
157
+ * - Re-wraps the exact same `CEK` to `newOwnerPublicKeyHex` without re-encrypting `ciphertextMetadata`
158
+ * or re-uploading `ArcSpace` blobs.
159
+ */
160
+ declare function rewrapEncryptedNftForNewOwner(input: RewrapEncryptedNftForNewOwnerInput): EncryptedAssetEnvelope;
161
+ /**
162
+ * Deterministic On-Chain Handover Verifier (`verifyEncryptedNftHandover`):
163
+ * - Verifies on-chain that a secondary transfer / sale handover:
164
+ * 1. Preserved `public` discovery headers (`plaintextHash`, `cekCommitmentHash`, `cekPublicKeyHex`, `arcSpaceUri`, `category`, `tags`, `publicSummary`) 100% unchanged;
165
+ * 2. Preserved `ciphertextMetadata`, `ciphertextTag`, and `nonce` 100% unchanged;
166
+ * 3. Transitioned `ownerDid` from `expectedPreviousOwnerDid` to `expectedNewOwnerDid` and bound `recipientPk = expectedNewOwnerPublicKeyHex`;
167
+ * 4. Incremented `handoverCount` by exactly `+1` with a valid `handoverProofHash` and `handoverSignature` verified against `public.cekPublicKeyHex`;
168
+ * 5. When `newOwnerSecretKeyHex` or `ephemeralSecretKeyHex` is provided (interactive/atomic buyer verification), unwraps `encryptedCek` and verifies `computeEncryptedNftCekCommitmentHash(unwrappedCek) === after.public.cekCommitmentHash`.
169
+ */
170
+ declare function verifyEncryptedNftHandover(input: VerifyEncryptedNftHandoverInput): boolean;
171
+ //#endregion
172
+ export { ENCRYPTED_NFT_SCHEMA_VERSION, EncryptedAssetEnvelope, EncryptedNftAlgorithm, EncryptedNftOwnerCipherEnvelope, EncryptedNftPrivateMetadata, EncryptedNftPublicDiscoveryHeader, MAX_ENCRYPTED_NFT_CATEGORY_LENGTH, MAX_ENCRYPTED_NFT_CIPHERTEXT_HEX_CHARS, MAX_ENCRYPTED_NFT_SUMMARY_LENGTH, MAX_ENCRYPTED_NFT_TAGS, MAX_ENCRYPTED_NFT_TAG_LENGTH, MAX_ENCRYPTED_NFT_URI_LENGTH, OpenEncryptedNftAsOwnerInput, OpenEncryptedNftAsOwnerResult, RewrapEncryptedNftForNewOwnerInput, SealEncryptedNftForOwnerInput, VALID_ENCRYPTED_NFT_ALGORITHMS, VerifyEncryptedNftHandoverInput, canonicalizeEncryptedNftMetadata, computeEncryptedNftCekCommitmentHash, computeEncryptedNftPlaintextHash, computeEncryptedNftPublicHeaderAad, deriveOwnerPublicKeyHexFromSecretKey, openEncryptedNftAsOwner, rewrapEncryptedNftForNewOwner, sealEncryptedNftForOwner, validateEncryptedAssetEnvelope, verifyEncryptedNftHandover };