@ocap/util 1.30.26 → 1.31.1

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 (39) hide show
  1. package/esm/amm.d.mts +158 -0
  2. package/esm/amm.mjs +269 -0
  3. package/esm/arcade.d.mts +217 -0
  4. package/esm/arcade.mjs +484 -0
  5. package/esm/bonding-reserve-aup.d.mts +125 -0
  6. package/esm/bonding-reserve-aup.mjs +230 -0
  7. package/esm/composable-container.d.mts +141 -0
  8. package/esm/composable-container.mjs +264 -0
  9. package/esm/conditional-market.d.mts +151 -0
  10. package/esm/conditional-market.mjs +376 -0
  11. package/esm/curve.d.mts +43 -5
  12. package/esm/curve.mjs +71 -9
  13. package/esm/foreign-receipt.d.mts +126 -0
  14. package/esm/foreign-receipt.mjs +388 -0
  15. package/esm/index.d.mts +8 -1
  16. package/esm/index.mjs +8 -1
  17. package/esm/node_modules/@noble/hashes/_md.mjs +168 -0
  18. package/esm/node_modules/@noble/hashes/sha2.mjs +185 -0
  19. package/esm/node_modules/@noble/hashes/utils.mjs +175 -0
  20. package/lib/amm.cjs +279 -0
  21. package/lib/amm.d.cts +158 -0
  22. package/lib/arcade.cjs +491 -0
  23. package/lib/arcade.d.cts +217 -0
  24. package/lib/bonding-reserve-aup.cjs +232 -0
  25. package/lib/bonding-reserve-aup.d.cts +125 -0
  26. package/lib/composable-container.cjs +270 -0
  27. package/lib/composable-container.d.cts +141 -0
  28. package/lib/conditional-market.cjs +377 -0
  29. package/lib/conditional-market.d.cts +151 -0
  30. package/lib/curve.cjs +73 -9
  31. package/lib/curve.d.cts +43 -5
  32. package/lib/foreign-receipt.cjs +396 -0
  33. package/lib/foreign-receipt.d.cts +126 -0
  34. package/lib/index.cjs +57 -1
  35. package/lib/index.d.cts +8 -1
  36. package/lib/node_modules/@noble/hashes/_md.cjs +171 -0
  37. package/lib/node_modules/@noble/hashes/sha2.cjs +185 -0
  38. package/lib/node_modules/@noble/hashes/utils.cjs +183 -0
  39. package/package.json +2 -2
package/lib/curve.d.cts CHANGED
@@ -29,7 +29,7 @@ declare function calcConstantCost({
29
29
  fixedPrice: string;
30
30
  decimal: number;
31
31
  direction?: Direction;
32
- }): bn_js0;
32
+ }): BN;
33
33
  /**
34
34
  * linear Curve
35
35
  * Price = basePrice + slope * currentSupply
@@ -57,7 +57,7 @@ declare function calcLinearCost(params: {
57
57
  slope: string;
58
58
  decimal: number;
59
59
  direction: Direction;
60
- }): bn_js0;
60
+ }): BN;
61
61
  /**
62
62
  * Quadratic Curve
63
63
  * Price = basePrice + currentSupply ** 2 / constant
@@ -81,7 +81,7 @@ declare function calcQuadraticCost(params: {
81
81
  constant: string;
82
82
  decimal: number;
83
83
  direction: Direction;
84
- }): bn_js0;
84
+ }): BN;
85
85
  declare function calcFee({
86
86
  reserveAmount,
87
87
  feeRate
@@ -110,6 +110,44 @@ declare function calcCost({
110
110
  currentSupply: string;
111
111
  curve: any;
112
112
  direction: Direction;
113
- }): bn_js0;
113
+ }): BN;
114
+ /**
115
+ * 3-Token Model Prepaid Quota Minting & Revenue Split (#1168).
116
+ *
117
+ * Separates ABT reserve payment for consumable `Quota` (CreditToken) from `ArcKey` (BondingCurveToken)
118
+ * reserve pool so service consumption never drains the bonding curve redemption reserve.
119
+ */
120
+ declare function calcQuotaMintFromPayment(params: {
121
+ reservePaid: string | number | BN;
122
+ unitPrice: string | number | BN;
123
+ decimal?: number;
124
+ creatorFeeBps?: number;
125
+ protocolFeeBps?: number;
126
+ }): {
127
+ quotaMinted: BN;
128
+ effectiveReserveCost: BN;
129
+ refundReserve: BN;
130
+ creatorRevenue: BN;
131
+ protocolFee: BN;
132
+ serviceEscrow: BN;
133
+ };
134
+ /**
135
+ * 3-Token Model Prepaid Quota Consumption & ArcKey Gating Check (#1168).
136
+ *
137
+ * Verifies the caller holds the required indivisible `ArcKey` balance (without burning `ArcKey`),
138
+ * enforces `Quota` expiration, and burns `consumeAmount` of prepaid `Quota`.
139
+ */
140
+ declare function consumePrepaidQuota(params: {
141
+ availableQuota: string | number | BN;
142
+ consumeAmount: string | number | BN;
143
+ userArcKeyBalance?: string | number | BN;
144
+ minArcKeyBalance?: string | number | BN;
145
+ expiresAt?: number;
146
+ now?: number;
147
+ }): {
148
+ burnedQuota: BN;
149
+ remainingQuota: BN;
150
+ arcKeyBalanceAfter: BN;
151
+ };
114
152
  //#endregion
115
- export { Direction, calcConstantCost, calcConstantPrice, calcCost, calcFee, calcLinearCost, calcLinearPrice, calcPrice, calcQuadraticCost, calcQuadraticPrice };
153
+ export { Direction, calcConstantCost, calcConstantPrice, calcCost, calcFee, calcLinearCost, calcLinearPrice, calcPrice, calcQuadraticCost, calcQuadraticPrice, calcQuotaMintFromPayment, consumePrepaidQuota };
@@ -0,0 +1,396 @@
1
+
2
+ //#region src/foreign-receipt.ts
3
+ const BPS_DENOMINATOR = 10000n;
4
+ const utf8Encoder = new TextEncoder();
5
+ const SHA256_K = new Uint32Array([
6
+ 1116352408,
7
+ 1899447441,
8
+ 3049323471,
9
+ 3921009573,
10
+ 961987163,
11
+ 1508970993,
12
+ 2453635748,
13
+ 2870763221,
14
+ 3624381080,
15
+ 310598401,
16
+ 607225278,
17
+ 1426881987,
18
+ 1925078388,
19
+ 2162078206,
20
+ 2614888103,
21
+ 3248222580,
22
+ 3835390401,
23
+ 4022224774,
24
+ 264347078,
25
+ 604807628,
26
+ 770255983,
27
+ 1249150122,
28
+ 1555081692,
29
+ 1996064986,
30
+ 2554220882,
31
+ 2821834349,
32
+ 2952996808,
33
+ 3210313671,
34
+ 3336571891,
35
+ 3584528711,
36
+ 113926993,
37
+ 338241895,
38
+ 666307205,
39
+ 773529912,
40
+ 1294757372,
41
+ 1396182291,
42
+ 1695183700,
43
+ 1986661051,
44
+ 2177026350,
45
+ 2456956037,
46
+ 2730485921,
47
+ 2820302411,
48
+ 3259730800,
49
+ 3345764771,
50
+ 3516065817,
51
+ 3600352804,
52
+ 4094571909,
53
+ 275423344,
54
+ 430227734,
55
+ 506948616,
56
+ 659060556,
57
+ 883997877,
58
+ 958139571,
59
+ 1322822218,
60
+ 1537002063,
61
+ 1747873779,
62
+ 1955562222,
63
+ 2024104815,
64
+ 2227730452,
65
+ 2361852424,
66
+ 2428436474,
67
+ 2756734187,
68
+ 3204031479,
69
+ 3329325298
70
+ ]);
71
+ function rotr(x, n) {
72
+ return x >>> n | x << 32 - n;
73
+ }
74
+ /**
75
+ * Pure-TS FIPS 180-4 SHA-256 implementation (uses `node:crypto` fast path when available).
76
+ */
77
+ function sha256Hex(data) {
78
+ const nodeCrypto = typeof process !== "undefined" ? process.getBuiltinModule?.("node:crypto") : void 0;
79
+ if (nodeCrypto?.createHash) return `0x${nodeCrypto.createHash("sha256").update(data).digest("hex")}`;
80
+ let h0 = 1779033703;
81
+ let h1 = 3144134277;
82
+ let h2 = 1013904242;
83
+ let h3 = 2773480762;
84
+ let h4 = 1359893119;
85
+ let h5 = 2600822924;
86
+ let h6 = 528734635;
87
+ let h7 = 1541459225;
88
+ const bitLenHi = Math.floor(data.byteLength / 536870912);
89
+ const bitLenLo = data.byteLength << 3 >>> 0;
90
+ const paddedLen = data.byteLength + 9 + 63 & -64;
91
+ const padded = new Uint8Array(paddedLen);
92
+ padded.set(data);
93
+ padded[data.byteLength] = 128;
94
+ const view = new DataView(padded.buffer);
95
+ view.setUint32(paddedLen - 8, bitLenHi, false);
96
+ view.setUint32(paddedLen - 4, bitLenLo, false);
97
+ const w = new Uint32Array(64);
98
+ for (let offset = 0; offset < paddedLen; offset += 64) {
99
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
100
+ for (let i = 16; i < 64; i++) {
101
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
102
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
103
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
104
+ }
105
+ let a = h0;
106
+ let b = h1;
107
+ let c = h2;
108
+ let d = h3;
109
+ let e = h4;
110
+ let f = h5;
111
+ let g = h6;
112
+ let h = h7;
113
+ for (let i = 0; i < 64; i++) {
114
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
115
+ const ch = e & f ^ ~e & g;
116
+ const temp1 = h + S1 + ch + SHA256_K[i] + w[i] >>> 0;
117
+ const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
118
+ h = g;
119
+ g = f;
120
+ f = e;
121
+ e = d + temp1 >>> 0;
122
+ d = c;
123
+ c = b;
124
+ b = a;
125
+ a = temp1 + temp2 >>> 0;
126
+ }
127
+ h0 = h0 + a >>> 0;
128
+ h1 = h1 + b >>> 0;
129
+ h2 = h2 + c >>> 0;
130
+ h3 = h3 + d >>> 0;
131
+ h4 = h4 + e >>> 0;
132
+ h5 = h5 + f >>> 0;
133
+ h6 = h6 + g >>> 0;
134
+ h7 = h7 + h >>> 0;
135
+ }
136
+ return `0x${[
137
+ h0,
138
+ h1,
139
+ h2,
140
+ h3,
141
+ h4,
142
+ h5,
143
+ h6,
144
+ h7
145
+ ].map((v) => (v >>> 0).toString(16).padStart(8, "0")).join("")}`;
146
+ }
147
+ function parsePositiveBigInt(value, label) {
148
+ let bn;
149
+ try {
150
+ bn = typeof value === "bigint" ? value : BigInt(String(value).trim());
151
+ } catch {
152
+ throw new Error(`Invalid ${label}: must be an integer`);
153
+ }
154
+ if (bn <= 0n) throw new Error(`Invalid ${label}: must be strictly positive`);
155
+ return bn;
156
+ }
157
+ function assertNonEmptyTrimmed(value, label) {
158
+ if (typeof value !== "string" || !value.trim()) throw new Error(`Invalid ${label}: must be a non-empty string`);
159
+ return value.trim();
160
+ }
161
+ function assertBpsRange(bps, label) {
162
+ if (!Number.isInteger(bps) || bps < 0 || bps > 1e4) throw new Error(`Invalid ${label}: must be an integer in [0, 10000]`);
163
+ }
164
+ function normalizeVaultOrTokenAddress(addr) {
165
+ return /^0x[0-9a-fA-F]+$/.test(addr) ? addr.toLowerCase() : addr;
166
+ }
167
+ /**
168
+ * Validate a `ForeignQuoteSpec` and compute its deterministic canonical SHA-256 digest (`0x...`).
169
+ */
170
+ function computeForeignQuoteDigest(quote, nowMs) {
171
+ const quoteId = assertNonEmptyTrimmed(quote.quoteId, "quoteId");
172
+ const sourceChainId = assertNonEmptyTrimmed(quote.sourceChainId, "sourceChainId").toLowerCase();
173
+ const vaultAddress = assertNonEmptyTrimmed(quote.vaultAddress, "vaultAddress");
174
+ const paymentToken = assertNonEmptyTrimmed(quote.paymentToken, "paymentToken");
175
+ const paymentAmount = parsePositiveBigInt(quote.paymentAmount, "paymentAmount").toString(10);
176
+ const targetChainId = assertNonEmptyTrimmed(quote.targetChainId, "targetChainId");
177
+ const targetFactoryAddress = assertNonEmptyTrimmed(quote.targetFactoryAddress, "targetFactoryAddress");
178
+ const buyerDid = assertNonEmptyTrimmed(quote.buyerDid, "buyerDid");
179
+ assertBpsRange(quote.maxSlippageBps, "maxSlippageBps");
180
+ assertBpsRange(quote.reserveBps, "reserveBps");
181
+ if (!Number.isSafeInteger(quote.expiresAt) || quote.expiresAt <= 0) throw new Error("Invalid expiresAt: must be a positive safe integer timestamp");
182
+ if (nowMs !== void 0) {
183
+ if (!Number.isSafeInteger(nowMs) || nowMs < 0) throw new Error("Invalid nowMs: must be a non-negative safe integer timestamp");
184
+ if (quote.expiresAt <= nowMs) throw new Error("Foreign quote has expired");
185
+ }
186
+ const canonicalPayload = {
187
+ version: 1,
188
+ quoteId,
189
+ sourceChainId,
190
+ vaultAddress: normalizeVaultOrTokenAddress(vaultAddress),
191
+ paymentToken: normalizeVaultOrTokenAddress(paymentToken),
192
+ paymentAmount,
193
+ targetChainId,
194
+ targetFactoryAddress,
195
+ buyerDid,
196
+ maxSlippageBps: quote.maxSlippageBps,
197
+ reserveBps: quote.reserveBps,
198
+ expiresAt: quote.expiresAt
199
+ };
200
+ return sha256Hex(utf8Encoder.encode(JSON.stringify(canonicalPayload)));
201
+ }
202
+ /**
203
+ * Build the canonical 4-tuple idempotency key string `(sourceChainId, vaultAddress, txHash, eventIndex)`.
204
+ */
205
+ function formatForeignReceiptKey(key) {
206
+ const sourceChainId = assertNonEmptyTrimmed(key.sourceChainId, "sourceChainId").toLowerCase();
207
+ const vaultAddress = normalizeVaultOrTokenAddress(assertNonEmptyTrimmed(key.vaultAddress, "vaultAddress"));
208
+ const rawTx = assertNonEmptyTrimmed(key.txHash, "txHash");
209
+ const txHash = /^0x[0-9a-fA-F]+$/.test(rawTx) ? rawTx.toLowerCase() : rawTx;
210
+ if (vaultAddress.includes(":") || txHash.includes(":")) throw new Error("Invalid ForeignReceiptKey: vaultAddress and txHash cannot contain \":\" delimiter");
211
+ if (!Number.isSafeInteger(key.eventIndex) || key.eventIndex < 0) throw new Error("Invalid eventIndex: must be a non-negative safe integer");
212
+ return `${sourceChainId}:${vaultAddress}:${txHash}:${key.eventIndex}`;
213
+ }
214
+ /**
215
+ * Compute a deterministic receipt ID (`0x...`) from the 4-tuple idempotency key.
216
+ */
217
+ function computeForeignReceiptId(key) {
218
+ const formatted = formatForeignReceiptKey(key);
219
+ return sha256Hex(utf8Encoder.encode(`arcblock:foreign-receipt:v1:${formatted}`));
220
+ }
221
+ /**
222
+ * Deterministically split an external payment into `reserveBucket` (locked for floor/payout redemptions),
223
+ * `protocolFeeBucket`, and `devBucket` (studio revenue).
224
+ * Guarantees exact conservation: `reserveBucket + protocolFeeBucket + devBucket === totalAmount`.
225
+ */
226
+ function splitForeignVaultPayment(paymentAmount, reserveBps, protocolFeeBps = 0) {
227
+ const totalAmount = parsePositiveBigInt(paymentAmount, "paymentAmount");
228
+ assertBpsRange(reserveBps, "reserveBps");
229
+ assertBpsRange(protocolFeeBps, "protocolFeeBps");
230
+ if (reserveBps + protocolFeeBps > 1e4) throw new Error("Invalid split: reserveBps + protocolFeeBps cannot exceed 10000");
231
+ const reserveBucket = totalAmount * BigInt(reserveBps) / BPS_DENOMINATOR;
232
+ const protocolFeeBucket = totalAmount * BigInt(protocolFeeBps) / BPS_DENOMINATOR;
233
+ return {
234
+ totalAmount,
235
+ reserveBucket,
236
+ protocolFeeBucket,
237
+ devBucket: totalAmount - reserveBucket - protocolFeeBucket,
238
+ reserveBps,
239
+ protocolFeeBps
240
+ };
241
+ }
242
+ /**
243
+ * Check whether an asset minted via a `ForeignReceiptRecord` is unlocked for secondary transfer,
244
+ * floor burn redemption, or external payout.
245
+ * Assets minted under `PROVISIONAL` confirmation are locked until promoted to `FINAL`.
246
+ */
247
+ function isAssetUnlockedByReceipt(record) {
248
+ return record.status === "FINAL";
249
+ }
250
+ /**
251
+ * In-memory deterministic registry for `ForeignReceipt` idempotency and two-stage (`PROVISIONAL -> FINAL`) finality.
252
+ */
253
+ var ForeignReceiptRegistry = class {
254
+ constructor() {
255
+ this.byReceiptId = /* @__PURE__ */ new Map();
256
+ this.byIdempotencyKey = /* @__PURE__ */ new Map();
257
+ this.byQuoteId = /* @__PURE__ */ new Map();
258
+ }
259
+ registerReceipt(params) {
260
+ const idempotencyKey = formatForeignReceiptKey(params.key);
261
+ if (this.byIdempotencyKey.has(idempotencyKey)) throw new Error(`Duplicate foreign receipt key: ${idempotencyKey}`);
262
+ const quoteDigest = computeForeignQuoteDigest(params.quote, params.nowMs);
263
+ const normalizedQuoteId = assertNonEmptyTrimmed(params.quote.quoteId, "quoteId");
264
+ if (this.byQuoteId.has(normalizedQuoteId)) throw new Error(`Duplicate quoteId consumption: ${normalizedQuoteId}`);
265
+ const keyChainId = params.key.sourceChainId.trim().toLowerCase();
266
+ const quoteChainId = params.quote.sourceChainId.trim().toLowerCase();
267
+ if (keyChainId !== quoteChainId) throw new Error(`Receipt sourceChainId (${keyChainId}) does not match quote sourceChainId (${quoteChainId})`);
268
+ const keyVault = normalizeVaultOrTokenAddress(params.key.vaultAddress.trim());
269
+ const quoteVault = normalizeVaultOrTokenAddress(params.quote.vaultAddress.trim());
270
+ if (keyVault !== quoteVault) throw new Error(`Receipt vaultAddress (${keyVault}) does not match quote vaultAddress (${quoteVault})`);
271
+ if (params.sourceBlockNumber !== void 0 && (!Number.isSafeInteger(params.sourceBlockNumber) || params.sourceBlockNumber < 0)) throw new Error("Invalid sourceBlockNumber: must be a non-negative safe integer");
272
+ const receiptId = computeForeignReceiptId(params.key);
273
+ const split = splitForeignVaultPayment(params.quote.paymentAmount, params.quote.reserveBps, params.protocolFeeBps ?? 0);
274
+ const status = params.status ?? "PROVISIONAL";
275
+ const record = {
276
+ receiptId,
277
+ idempotencyKey,
278
+ quoteId: normalizedQuoteId,
279
+ quoteDigest,
280
+ sourceChainId: keyChainId,
281
+ vaultAddress: params.key.vaultAddress.trim(),
282
+ txHash: params.key.txHash.trim(),
283
+ eventIndex: params.key.eventIndex,
284
+ buyerDid: params.quote.buyerDid.trim(),
285
+ targetFactoryAddress: params.quote.targetFactoryAddress.trim(),
286
+ paymentToken: params.quote.paymentToken.trim(),
287
+ paymentAmount: split.totalAmount.toString(10),
288
+ reserveBucket: split.reserveBucket.toString(10),
289
+ protocolFeeBucket: split.protocolFeeBucket.toString(10),
290
+ devBucket: split.devBucket.toString(10),
291
+ status,
292
+ sourceBlockNumber: params.sourceBlockNumber,
293
+ finalizedBlockNumber: status === "FINAL" ? params.sourceBlockNumber : void 0
294
+ };
295
+ this.byReceiptId.set(receiptId, record);
296
+ this.byIdempotencyKey.set(idempotencyKey, receiptId);
297
+ this.byQuoteId.set(normalizedQuoteId, receiptId);
298
+ return { ...record };
299
+ }
300
+ promoteToFinal(receiptId, finalizedBlockNumber) {
301
+ const existing = this.byReceiptId.get(receiptId);
302
+ if (!existing) throw new Error(`Unknown foreign receiptId: ${receiptId}`);
303
+ if (existing.status === "REORG_CANCELLED") throw new Error(`Cannot promote reorg-cancelled receipt: ${receiptId}`);
304
+ if (finalizedBlockNumber !== void 0) {
305
+ if (!Number.isSafeInteger(finalizedBlockNumber) || finalizedBlockNumber < 0) throw new Error("Invalid finalizedBlockNumber: must be a non-negative safe integer");
306
+ if (existing.sourceBlockNumber !== void 0 && finalizedBlockNumber < existing.sourceBlockNumber) throw new Error("finalizedBlockNumber cannot be less than sourceBlockNumber");
307
+ if (existing.status === "FINAL" && existing.finalizedBlockNumber !== void 0 && existing.finalizedBlockNumber !== finalizedBlockNumber) throw new Error(`Receipt ${receiptId} is already finalized at block ${existing.finalizedBlockNumber}`);
308
+ existing.finalizedBlockNumber = finalizedBlockNumber;
309
+ }
310
+ existing.status = "FINAL";
311
+ return { ...existing };
312
+ }
313
+ markReorgCancelled(receiptId, reason) {
314
+ const existing = this.byReceiptId.get(receiptId);
315
+ if (!existing) throw new Error(`Unknown foreign receiptId: ${receiptId}`);
316
+ if (existing.status === "FINAL") throw new Error(`Cannot cancel already finalized receipt: ${receiptId}`);
317
+ existing.status = "REORG_CANCELLED";
318
+ existing.reorgReason = reason;
319
+ return { ...existing };
320
+ }
321
+ getByReceiptId(receiptId) {
322
+ const rec = this.byReceiptId.get(receiptId);
323
+ return rec ? { ...rec } : void 0;
324
+ }
325
+ hasIdempotencyKey(key) {
326
+ return this.byIdempotencyKey.has(formatForeignReceiptKey(key));
327
+ }
328
+ };
329
+ /**
330
+ * 3-tier anti-griefing quota tracker for developer-sponsored cross-ecosystem sessions.
331
+ * - Tier 1: Unpaid new external wallet gets at most `prePayFreeOpsLimit` (default 3) sponsored ops (e.g. session delegate + trial).
332
+ * - Tier 2: Each verified `ForeignReceipt` unlocks `opsGrantedPerReceipt` (default 50) sponsored ops.
333
+ * - Tier 3: Once exhausted, rejects sponsored execution until a new receipt is registered.
334
+ */
335
+ var SponsoredQuotaTracker = class {
336
+ constructor(config = {}) {
337
+ this.globalCreditedReceipts = /* @__PURE__ */ new Map();
338
+ this.stateByDid = /* @__PURE__ */ new Map();
339
+ this.prePayFreeOpsLimit = config.prePayFreeOpsLimit ?? 3;
340
+ this.opsGrantedPerReceipt = config.opsGrantedPerReceipt ?? 50;
341
+ }
342
+ getOrCreate(did) {
343
+ const key = assertNonEmptyTrimmed(did, "did");
344
+ let entry = this.stateByDid.get(key);
345
+ if (!entry) {
346
+ entry = {
347
+ usedOps: 0,
348
+ grantedOps: this.prePayFreeOpsLimit,
349
+ creditedReceipts: /* @__PURE__ */ new Set()
350
+ };
351
+ this.stateByDid.set(key, entry);
352
+ }
353
+ return entry;
354
+ }
355
+ creditForeignReceipt(did, receipt) {
356
+ if (receipt.status === "REORG_CANCELLED") throw new Error("Cannot credit sponsored quota for reorg-cancelled receipt");
357
+ if (receipt.status !== "PROVISIONAL" && receipt.status !== "FINAL") throw new Error("Invalid receipt status for sponsored quota credit");
358
+ const key = assertNonEmptyTrimmed(did, "did");
359
+ const receiptId = assertNonEmptyTrimmed(receipt.receiptId, "receiptId");
360
+ if (receipt.buyerDid !== void 0 && receipt.buyerDid.trim() !== key) throw new Error(`Receipt buyerDid (${receipt.buyerDid.trim()}) does not match credited DID (${key})`);
361
+ const existingOwner = this.globalCreditedReceipts.get(receiptId);
362
+ if (existingOwner !== void 0 && existingOwner !== key) throw new Error(`Foreign receipt ${receiptId} was already credited to another DID (${existingOwner})`);
363
+ const entry = this.getOrCreate(key);
364
+ if (entry.creditedReceipts.has(receiptId)) return entry.grantedOps - entry.usedOps;
365
+ this.globalCreditedReceipts.set(receiptId, key);
366
+ entry.creditedReceipts.add(receiptId);
367
+ entry.grantedOps += this.opsGrantedPerReceipt;
368
+ return entry.grantedOps - entry.usedOps;
369
+ }
370
+ consumeSponsoredOp(did, count = 1) {
371
+ if (!Number.isInteger(count) || count <= 0) throw new Error("Invalid op count: must be a positive integer");
372
+ const entry = this.getOrCreate(did);
373
+ if (entry.usedOps + count > entry.grantedOps) throw new Error(`Sponsored op quota exhausted for ${did} (${entry.usedOps}/${entry.grantedOps})`);
374
+ entry.usedOps += count;
375
+ return {
376
+ remainingOps: entry.grantedOps - entry.usedOps,
377
+ totalUsedOps: entry.usedOps
378
+ };
379
+ }
380
+ getRemainingOps(did) {
381
+ const key = assertNonEmptyTrimmed(did, "did");
382
+ const entry = this.stateByDid.get(key);
383
+ if (!entry) return this.prePayFreeOpsLimit;
384
+ return entry.grantedOps - entry.usedOps;
385
+ }
386
+ };
387
+
388
+ //#endregion
389
+ exports.ForeignReceiptRegistry = ForeignReceiptRegistry;
390
+ exports.SponsoredQuotaTracker = SponsoredQuotaTracker;
391
+ exports.computeForeignQuoteDigest = computeForeignQuoteDigest;
392
+ exports.computeForeignReceiptId = computeForeignReceiptId;
393
+ exports.formatForeignReceiptKey = formatForeignReceiptKey;
394
+ exports.isAssetUnlockedByReceipt = isAssetUnlockedByReceipt;
395
+ exports.sha256Hex = sha256Hex;
396
+ exports.splitForeignVaultPayment = splitForeignVaultPayment;
@@ -0,0 +1,126 @@
1
+ //#region src/foreign-receipt.d.ts
2
+ /**
3
+ * Pure-TS FIPS 180-4 SHA-256 implementation (uses `node:crypto` fast path when available).
4
+ */
5
+ declare function sha256Hex(data: Uint8Array): string;
6
+ type ForeignReceiptStatus = 'PROVISIONAL' | 'FINAL' | 'REORG_CANCELLED';
7
+ interface ForeignQuoteSpec {
8
+ quoteId: string;
9
+ sourceChainId: string;
10
+ vaultAddress: string;
11
+ paymentToken: string;
12
+ paymentAmount: string | bigint;
13
+ targetChainId: string;
14
+ targetFactoryAddress: string;
15
+ buyerDid: string;
16
+ maxSlippageBps: number;
17
+ reserveBps: number;
18
+ expiresAt: number;
19
+ }
20
+ interface ForeignReceiptKey {
21
+ sourceChainId: string;
22
+ vaultAddress: string;
23
+ txHash: string;
24
+ eventIndex: number;
25
+ }
26
+ interface ForeignVaultSplitResult {
27
+ totalAmount: bigint;
28
+ reserveBucket: bigint;
29
+ protocolFeeBucket: bigint;
30
+ devBucket: bigint;
31
+ reserveBps: number;
32
+ protocolFeeBps: number;
33
+ }
34
+ interface ForeignReceiptRecord {
35
+ receiptId: string;
36
+ idempotencyKey: string;
37
+ quoteId: string;
38
+ quoteDigest: string;
39
+ sourceChainId: string;
40
+ vaultAddress: string;
41
+ txHash: string;
42
+ eventIndex: number;
43
+ buyerDid: string;
44
+ targetFactoryAddress: string;
45
+ paymentToken: string;
46
+ paymentAmount: string;
47
+ reserveBucket: string;
48
+ protocolFeeBucket: string;
49
+ devBucket: string;
50
+ status: ForeignReceiptStatus;
51
+ sourceBlockNumber?: number;
52
+ finalizedBlockNumber?: number;
53
+ reorgReason?: string;
54
+ }
55
+ /**
56
+ * Validate a `ForeignQuoteSpec` and compute its deterministic canonical SHA-256 digest (`0x...`).
57
+ */
58
+ declare function computeForeignQuoteDigest(quote: ForeignQuoteSpec, nowMs?: number): string;
59
+ /**
60
+ * Build the canonical 4-tuple idempotency key string `(sourceChainId, vaultAddress, txHash, eventIndex)`.
61
+ */
62
+ declare function formatForeignReceiptKey(key: ForeignReceiptKey): string;
63
+ /**
64
+ * Compute a deterministic receipt ID (`0x...`) from the 4-tuple idempotency key.
65
+ */
66
+ declare function computeForeignReceiptId(key: ForeignReceiptKey): string;
67
+ /**
68
+ * Deterministically split an external payment into `reserveBucket` (locked for floor/payout redemptions),
69
+ * `protocolFeeBucket`, and `devBucket` (studio revenue).
70
+ * Guarantees exact conservation: `reserveBucket + protocolFeeBucket + devBucket === totalAmount`.
71
+ */
72
+ declare function splitForeignVaultPayment(paymentAmount: string | bigint, reserveBps: number, protocolFeeBps?: number): ForeignVaultSplitResult;
73
+ /**
74
+ * Check whether an asset minted via a `ForeignReceiptRecord` is unlocked for secondary transfer,
75
+ * floor burn redemption, or external payout.
76
+ * Assets minted under `PROVISIONAL` confirmation are locked until promoted to `FINAL`.
77
+ */
78
+ declare function isAssetUnlockedByReceipt(record: Pick<ForeignReceiptRecord, 'status'>): boolean;
79
+ /**
80
+ * In-memory deterministic registry for `ForeignReceipt` idempotency and two-stage (`PROVISIONAL -> FINAL`) finality.
81
+ */
82
+ declare class ForeignReceiptRegistry {
83
+ private readonly byReceiptId;
84
+ private readonly byIdempotencyKey;
85
+ private readonly byQuoteId;
86
+ registerReceipt(params: {
87
+ key: ForeignReceiptKey;
88
+ quote: ForeignQuoteSpec;
89
+ status?: 'PROVISIONAL' | 'FINAL';
90
+ protocolFeeBps?: number;
91
+ sourceBlockNumber?: number;
92
+ nowMs?: number;
93
+ }): ForeignReceiptRecord;
94
+ promoteToFinal(receiptId: string, finalizedBlockNumber?: number): ForeignReceiptRecord;
95
+ markReorgCancelled(receiptId: string, reason: string): ForeignReceiptRecord;
96
+ getByReceiptId(receiptId: string): ForeignReceiptRecord | undefined;
97
+ hasIdempotencyKey(key: ForeignReceiptKey): boolean;
98
+ }
99
+ interface SponsoredQuotaConfig {
100
+ prePayFreeOpsLimit?: number;
101
+ opsGrantedPerReceipt?: number;
102
+ }
103
+ /**
104
+ * 3-tier anti-griefing quota tracker for developer-sponsored cross-ecosystem sessions.
105
+ * - Tier 1: Unpaid new external wallet gets at most `prePayFreeOpsLimit` (default 3) sponsored ops (e.g. session delegate + trial).
106
+ * - Tier 2: Each verified `ForeignReceipt` unlocks `opsGrantedPerReceipt` (default 50) sponsored ops.
107
+ * - Tier 3: Once exhausted, rejects sponsored execution until a new receipt is registered.
108
+ */
109
+ declare class SponsoredQuotaTracker {
110
+ private readonly prePayFreeOpsLimit;
111
+ private readonly opsGrantedPerReceipt;
112
+ private readonly globalCreditedReceipts;
113
+ private readonly stateByDid;
114
+ constructor(config?: SponsoredQuotaConfig);
115
+ private getOrCreate;
116
+ creditForeignReceipt(did: string, receipt: Pick<ForeignReceiptRecord, 'receiptId' | 'status'> & {
117
+ buyerDid?: string;
118
+ }): number;
119
+ consumeSponsoredOp(did: string, count?: number): {
120
+ remainingOps: number;
121
+ totalUsedOps: number;
122
+ };
123
+ getRemainingOps(did: string): number;
124
+ }
125
+ //#endregion
126
+ export { ForeignQuoteSpec, ForeignReceiptKey, ForeignReceiptRecord, ForeignReceiptRegistry, ForeignReceiptStatus, ForeignVaultSplitResult, SponsoredQuotaConfig, SponsoredQuotaTracker, computeForeignQuoteDigest, computeForeignReceiptId, formatForeignReceiptKey, isAssetUnlockedByReceipt, sha256Hex, splitForeignVaultPayment };
package/lib/index.cjs CHANGED
@@ -1,6 +1,13 @@
1
1
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
2
  const require_bn = require('./bn.cjs');
3
3
  const require_scope_match = require('./scope-match.cjs');
4
+ const require_arcade = require('./arcade.cjs');
5
+ const require_bonding_reserve_aup = require('./bonding-reserve-aup.cjs');
6
+ const require_composable_container = require('./composable-container.cjs');
7
+ const require_conditional_market = require('./conditional-market.cjs');
8
+ const require_foreign_receipt = require('./foreign-receipt.cjs');
9
+ const require_curve = require('./curve.cjs');
10
+ const require_amm = require('./amm.cjs');
4
11
  let bn_js = require("bn.js");
5
12
  bn_js = require_rolldown_runtime.__toESM(bn_js);
6
13
  let base64_url = require("base64-url");
@@ -484,17 +491,55 @@ function formatTxType(type) {
484
491
 
485
492
  //#endregion
486
493
  exports.BN = require_bn.BN;
494
+ exports.BondingReserveVault = require_bonding_reserve_aup.BondingReserveVault;
495
+ exports.ConditionalMarketPool = require_conditional_market.ConditionalMarketPool;
496
+ exports.Direction = require_curve.Direction;
497
+ exports.ForeignReceiptRegistry = require_foreign_receipt.ForeignReceiptRegistry;
498
+ exports.MAX_TOTAL_FEE_BPS = require_amm.MAX_TOTAL_FEE_BPS;
499
+ exports.MINIMUM_LIQUIDITY = require_amm.MINIMUM_LIQUIDITY;
500
+ exports.RevenueSharePool = require_arcade.RevenueSharePool;
501
+ exports.SponsoredQuotaTracker = require_foreign_receipt.SponsoredQuotaTracker;
487
502
  exports.UUID = UUID;
503
+ exports.assertAssetRedeemableOrTransferable = require_composable_container.assertAssetRedeemableOrTransferable;
504
+ exports.assertMachineBankrollSolvency = require_arcade.assertMachineBankrollSolvency;
505
+ exports.assertNoContainerCycle = require_composable_container.assertNoContainerCycle;
506
+ exports.buildAupMultiViewManifest = require_bonding_reserve_aup.buildAupMultiViewManifest;
488
507
  exports.bytesToHex = bytesToHex;
508
+ exports.calcAddLiquidity = require_amm.calcAddLiquidity;
509
+ exports.calcConstantCost = require_curve.calcConstantCost;
510
+ exports.calcConstantPrice = require_curve.calcConstantPrice;
511
+ exports.calcCost = require_curve.calcCost;
512
+ exports.calcFee = require_curve.calcFee;
513
+ exports.calcGraduationSettlement = require_amm.calcGraduationSettlement;
514
+ exports.calcGraduationSupplySplit = require_amm.calcGraduationSupplySplit;
515
+ exports.calcInitialLiquidity = require_amm.calcInitialLiquidity;
516
+ exports.calcLimitOrderFill = require_amm.calcLimitOrderFill;
517
+ exports.calcLinearCost = require_curve.calcLinearCost;
518
+ exports.calcLinearPrice = require_curve.calcLinearPrice;
519
+ exports.calcPrice = require_curve.calcPrice;
520
+ exports.calcQuadraticCost = require_curve.calcQuadraticCost;
521
+ exports.calcQuadraticPrice = require_curve.calcQuadraticPrice;
522
+ exports.calcQuotaMintFromPayment = require_curve.calcQuotaMintFromPayment;
523
+ exports.calcRemoveLiquidity = require_amm.calcRemoveLiquidity;
524
+ exports.calcSwapExactIn = require_amm.calcSwapExactIn;
525
+ exports.calcSwapExactOut = require_amm.calcSwapExactOut;
526
+ exports.computeForeignQuoteDigest = require_foreign_receipt.computeForeignQuoteDigest;
527
+ exports.computeForeignReceiptId = require_foreign_receipt.computeForeignReceiptId;
528
+ exports.consumePrepaidQuota = require_curve.consumePrepaidQuota;
529
+ exports.createComposableAssetNode = require_composable_container.createComposableAssetNode;
530
+ exports.deriveProvablyFairRoll = require_arcade.deriveProvablyFairRoll;
489
531
  exports.extractMethod = extractMethod;
532
+ exports.formatForeignReceiptKey = require_foreign_receipt.formatForeignReceiptKey;
490
533
  exports.formatTxType = formatTxType;
491
534
  exports.fromBase58 = fromBase58;
492
535
  exports.fromBase64 = fromBase64;
493
536
  exports.fromTokenToUnit = fromTokenToUnit;
494
537
  exports.fromUnitToToken = fromUnitToToken;
538
+ exports.generateHashChain = require_arcade.generateHashChain;
495
539
  exports.hexToBytes = hexToBytes;
496
540
  exports.hexToNumber = hexToNumber;
497
541
  exports.hexToUtf8 = hexToUtf8;
542
+ exports.isAssetUnlockedByReceipt = require_foreign_receipt.isAssetUnlockedByReceipt;
498
543
  exports.isBN = isBN;
499
544
  exports.isBase58btc = isBase58btc;
500
545
  exports.isBigNumber = isBigNumber;
@@ -504,14 +549,23 @@ exports.isHexStrict = isHexStrict;
504
549
  exports.isSameDid = isSameDid;
505
550
  exports.isUUID = isUUID;
506
551
  exports.isUint8Array = isUint8Array;
552
+ exports.isqrt = require_amm.isqrt;
507
553
  exports.leftPad = leftPad;
554
+ exports.mountContainerSlotItem = require_composable_container.mountContainerSlotItem;
508
555
  exports.numberToBN = numberToBN;
509
556
  exports.numberToHex = numberToHex;
510
557
  exports.numberToString = numberToString;
558
+ exports.quoteBondingCurveMint = require_bonding_reserve_aup.quoteBondingCurveMint;
559
+ exports.resolveHierarchicalSplitDag = require_arcade.resolveHierarchicalSplitDag;
560
+ exports.resolveWeightedLootTable = require_arcade.resolveWeightedLootTable;
511
561
  exports.rightPad = rightPad;
512
562
  exports.scopeMatch = require_scope_match.scopeMatch;
513
563
  exports.scopeMatchAny = require_scope_match.scopeMatchAny;
564
+ exports.settleArcadeMachinePlay = require_arcade.settleArcadeMachinePlay;
565
+ exports.sha256Hex = require_foreign_receipt.sha256Hex;
566
+ exports.splitForeignVaultPayment = require_foreign_receipt.splitForeignVaultPayment;
514
567
  exports.stripHexPrefix = stripHexPrefix;
568
+ exports.synthesizeContainerRecipe = require_composable_container.synthesizeContainerRecipe;
515
569
  exports.toAddress = toAddress;
516
570
  exports.toBN = toBN;
517
571
  exports.toBase58 = toBase58;
@@ -520,4 +574,6 @@ exports.toBuffer = toBuffer;
520
574
  exports.toDid = toDid;
521
575
  exports.toHex = toHex;
522
576
  exports.toUint8Array = toUint8Array;
523
- exports.utf8ToHex = utf8ToHex;
577
+ exports.unmountContainerSlotItem = require_composable_container.unmountContainerSlotItem;
578
+ exports.utf8ToHex = utf8ToHex;
579
+ exports.verifyHashChainStep = require_arcade.verifyHashChainStep;