@ocap/util 1.30.26 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
@@ -0,0 +1,377 @@
1
+
2
+ //#region src/conditional-market.ts
3
+ const BPS_DENOMINATOR = 10000n;
4
+ const MAX_OUTCOMES = 32;
5
+ const MAX_TOTAL_FEE_BPS = 2500;
6
+ function assertNonEmptyTrimmed(value, label) {
7
+ if (typeof value !== "string" || value.trim().length === 0) throw new Error(`INVALID_${label}: must be a non-empty string`);
8
+ return value.trim();
9
+ }
10
+ function assertPositiveBigInt(value, label) {
11
+ if (typeof value !== "bigint" || value <= 0n) throw new Error(`INVALID_${label}: must be a positive bigint`);
12
+ return value;
13
+ }
14
+ function assertNonNegativeSafeInteger(value, label) {
15
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`INVALID_${label}: must be a non-negative safe integer`);
16
+ return value;
17
+ }
18
+ /**
19
+ * Polymarket / Gnosis CTF-style Conditional Prediction Market Pool:
20
+ * - 100% collateralized Complete-Set Split & Merge (`splitPosition`, `mergePositions`)
21
+ * - Complete-Set Constant Product Automated Market Maker (`seedInitialLiquidity`, `quoteBuyOutcomeShares`, `buyOutcomeShares`)
22
+ * - 4-way trading fee split (`lpFeeBucket`, `creatorFeeBucket`, `hostFeeBucket`, `protocolFeeBucket`)
23
+ * - Optimistic resolution with challenge window, dispute bond slashing, and 1:1 winning share redemption
24
+ */
25
+ var ConditionalMarketPool = class {
26
+ constructor(config) {
27
+ this.status = "OPEN";
28
+ this.winningOutcomeId = null;
29
+ this.collateralVaultBalance = 0n;
30
+ this.totalCompleteSetsMinted = 0n;
31
+ this.lpFeeBucket = 0n;
32
+ this.creatorFeeBucket = 0n;
33
+ this.hostFeeBucket = 0n;
34
+ this.protocolFeeBucket = 0n;
35
+ this.ammOutcomeReserves = /* @__PURE__ */ new Map();
36
+ this.outcomeHolderBalances = /* @__PURE__ */ new Map();
37
+ this.proposal = null;
38
+ this.challenge = null;
39
+ const marketId = assertNonEmptyTrimmed(config.marketId, "MARKET_ID");
40
+ const question = assertNonEmptyTrimmed(config.question, "QUESTION");
41
+ const arbiterDid = assertNonEmptyTrimmed(config.arbiterDid, "ARBITER_DID");
42
+ assertPositiveBigInt(config.requiredDisputeBond, "REQUIRED_DISPUTE_BOND");
43
+ if (typeof config.challengeWindowSeconds !== "number" || !Number.isSafeInteger(config.challengeWindowSeconds) || config.challengeWindowSeconds <= 0) throw new Error("INVALID_CHALLENGE_WINDOW: must be a positive safe integer");
44
+ if (!Array.isArray(config.outcomes) || config.outcomes.length < 2 || config.outcomes.length > MAX_OUTCOMES) throw new Error(`INVALID_OUTCOMES: must contain between 2 and ${MAX_OUTCOMES} outcomes`);
45
+ const normalizedOutcomes = [];
46
+ const seenOutcomes = /* @__PURE__ */ new Set();
47
+ for (const rawOutcome of config.outcomes) {
48
+ const outcome = assertNonEmptyTrimmed(rawOutcome, "OUTCOME_ID");
49
+ if (outcome === "VOID") throw new Error("INVALID_OUTCOME_ID: VOID is reserved for market invalidation");
50
+ if (seenOutcomes.has(outcome)) throw new Error(`DUPLICATE_OUTCOME_ID: ${outcome}`);
51
+ seenOutcomes.add(outcome);
52
+ normalizedOutcomes.push(outcome);
53
+ this.ammOutcomeReserves.set(outcome, 0n);
54
+ this.outcomeHolderBalances.set(outcome, /* @__PURE__ */ new Map());
55
+ }
56
+ const { lpFeeBps, creatorFeeBps, hostFeeBps, protocolFeeBps } = config.feeConfig;
57
+ assertNonNegativeSafeInteger(lpFeeBps, "LP_FEE_BPS");
58
+ assertNonNegativeSafeInteger(creatorFeeBps, "CREATOR_FEE_BPS");
59
+ assertNonNegativeSafeInteger(hostFeeBps, "HOST_FEE_BPS");
60
+ assertNonNegativeSafeInteger(protocolFeeBps, "PROTOCOL_FEE_BPS");
61
+ const totalFeeBps = lpFeeBps + creatorFeeBps + hostFeeBps + protocolFeeBps;
62
+ if (totalFeeBps > MAX_TOTAL_FEE_BPS) throw new Error(`INVALID_FEE_CONFIG: total fee bps (${totalFeeBps}) exceeds max ${MAX_TOTAL_FEE_BPS}`);
63
+ this.config = {
64
+ ...config,
65
+ marketId,
66
+ question,
67
+ arbiterDid,
68
+ outcomes: normalizedOutcomes,
69
+ feeConfig: { ...config.feeConfig }
70
+ };
71
+ }
72
+ getStatus() {
73
+ return this.status;
74
+ }
75
+ getWinningOutcomeId() {
76
+ return this.winningOutcomeId;
77
+ }
78
+ getCollateralVaultBalance() {
79
+ return this.collateralVaultBalance;
80
+ }
81
+ getTotalCompleteSetsMinted() {
82
+ return this.totalCompleteSetsMinted;
83
+ }
84
+ getFeeBuckets() {
85
+ return {
86
+ lpFeeBucket: this.lpFeeBucket,
87
+ creatorFeeBucket: this.creatorFeeBucket,
88
+ hostFeeBucket: this.hostFeeBucket,
89
+ protocolFeeBucket: this.protocolFeeBucket
90
+ };
91
+ }
92
+ getAmmOutcomeReserves() {
93
+ const out = Object.create(null);
94
+ for (const [k, v] of this.ammOutcomeReserves.entries()) out[k] = v;
95
+ return out;
96
+ }
97
+ getHolderOutcomeBalance(holderDid, outcomeId) {
98
+ const normalizedHolder = assertNonEmptyTrimmed(holderDid, "HOLDER_DID");
99
+ const normalizedOutcome = assertNonEmptyTrimmed(outcomeId, "OUTCOME_ID");
100
+ const holders = this.outcomeHolderBalances.get(normalizedOutcome);
101
+ if (!holders) throw new Error(`UNKNOWN_OUTCOME_ID: ${normalizedOutcome}`);
102
+ return holders.get(normalizedHolder) ?? 0n;
103
+ }
104
+ /**
105
+ * Computes implied probabilities in basis points (summing to 10000 bps) from AMM reserves.
106
+ * For Complete-Set Constant Product AMM, price_i is proportional to prod_{j != i} R_j.
107
+ */
108
+ getImpliedProbabilitiesBps() {
109
+ const outcomes = this.config.outcomes;
110
+ const reserves = outcomes.map((o) => this.ammOutcomeReserves.get(o) ?? 0n);
111
+ if (reserves.some((r) => r <= 0n)) throw new Error("AMM_NOT_SEEDED: all outcome reserves must be positive");
112
+ const weights = outcomes.map((_, idx) => {
113
+ let prod = 1n;
114
+ for (let j = 0; j < outcomes.length; j += 1) if (j !== idx) prod *= reserves[j];
115
+ return prod;
116
+ });
117
+ const totalWeight = weights.reduce((acc, w) => acc + w, 0n);
118
+ const result = Object.create(null);
119
+ let allocatedBps = 0;
120
+ for (let i = 0; i < outcomes.length; i += 1) {
121
+ const bps = Number(weights[i] * BPS_DENOMINATOR / totalWeight);
122
+ result[outcomes[i]] = bps;
123
+ allocatedBps += bps;
124
+ }
125
+ const remainder = 1e4 - allocatedBps;
126
+ if (remainder > 0) result[outcomes[0]] += remainder;
127
+ return result;
128
+ }
129
+ /**
130
+ * Splits `collateralAmount` 1:1 into `collateralAmount` shares of every mutually exclusive outcome.
131
+ */
132
+ splitPosition(holderDid, collateralAmount) {
133
+ if (this.status !== "OPEN") throw new Error(`MARKET_NOT_OPEN: current status is ${this.status}`);
134
+ const normalizedHolder = assertNonEmptyTrimmed(holderDid, "HOLDER_DID");
135
+ assertPositiveBigInt(collateralAmount, "COLLATERAL_AMOUNT");
136
+ this.collateralVaultBalance += collateralAmount;
137
+ this.totalCompleteSetsMinted += collateralAmount;
138
+ const updatedBalances = Object.create(null);
139
+ for (const outcome of this.config.outcomes) {
140
+ const holders = this.outcomeHolderBalances.get(outcome);
141
+ const next = (holders.get(normalizedHolder) ?? 0n) + collateralAmount;
142
+ holders.set(normalizedHolder, next);
143
+ updatedBalances[outcome] = next;
144
+ }
145
+ return updatedBalances;
146
+ }
147
+ /**
148
+ * Merges `shareAmount` complete sets across all outcomes back into `shareAmount` collateral 1:1.
149
+ */
150
+ mergePositions(holderDid, shareAmount) {
151
+ if (this.status !== "OPEN") throw new Error(`MARKET_NOT_OPEN: current status is ${this.status}`);
152
+ const normalizedHolder = assertNonEmptyTrimmed(holderDid, "HOLDER_DID");
153
+ assertPositiveBigInt(shareAmount, "SHARE_AMOUNT");
154
+ for (const outcome of this.config.outcomes) if (this.getHolderOutcomeBalance(normalizedHolder, outcome) < shareAmount) throw new Error(`INSUFFICIENT_OUTCOME_SHARES: holder ${normalizedHolder} lacks ${outcome} shares`);
155
+ for (const outcome of this.config.outcomes) {
156
+ const holders = this.outcomeHolderBalances.get(outcome);
157
+ const current = holders.get(normalizedHolder);
158
+ holders.set(normalizedHolder, current - shareAmount);
159
+ }
160
+ this.totalCompleteSetsMinted -= shareAmount;
161
+ this.collateralVaultBalance -= shareAmount;
162
+ return { collateralReturned: shareAmount };
163
+ }
164
+ /**
165
+ * Transfers conditional outcome shares between holders.
166
+ */
167
+ transferOutcomeShares(outcomeId, fromDid, toDid, shareAmount) {
168
+ const normalizedOutcome = assertNonEmptyTrimmed(outcomeId, "OUTCOME_ID");
169
+ const normalizedFrom = assertNonEmptyTrimmed(fromDid, "FROM_DID");
170
+ const normalizedTo = assertNonEmptyTrimmed(toDid, "TO_DID");
171
+ if (normalizedFrom === normalizedTo) throw new Error("SELF_TRANSFER_NOT_ALLOWED: fromDid and toDid must differ");
172
+ assertPositiveBigInt(shareAmount, "SHARE_AMOUNT");
173
+ const holders = this.outcomeHolderBalances.get(normalizedOutcome);
174
+ if (!holders) throw new Error(`UNKNOWN_OUTCOME_ID: ${normalizedOutcome}`);
175
+ const fromBal = holders.get(normalizedFrom) ?? 0n;
176
+ if (fromBal < shareAmount) throw new Error(`INSUFFICIENT_OUTCOME_SHARES: ${normalizedFrom} has ${fromBal} < ${shareAmount}`);
177
+ holders.set(normalizedFrom, fromBal - shareAmount);
178
+ holders.set(normalizedTo, (holders.get(normalizedTo) ?? 0n) + shareAmount);
179
+ }
180
+ /**
181
+ * Seeds initial AMM complete-set reserves by splitting `collateralAmount` across all outcomes.
182
+ */
183
+ seedInitialLiquidity(lpDid, collateralAmount) {
184
+ if (this.status !== "OPEN") throw new Error(`MARKET_NOT_OPEN: current status is ${this.status}`);
185
+ assertNonEmptyTrimmed(lpDid, "LP_DID");
186
+ assertPositiveBigInt(collateralAmount, "COLLATERAL_AMOUNT");
187
+ this.collateralVaultBalance += collateralAmount;
188
+ this.totalCompleteSetsMinted += collateralAmount;
189
+ for (const outcome of this.config.outcomes) {
190
+ const prev = this.ammOutcomeReserves.get(outcome) ?? 0n;
191
+ this.ammOutcomeReserves.set(outcome, prev + collateralAmount);
192
+ }
193
+ return this.getAmmOutcomeReserves();
194
+ }
195
+ /**
196
+ * Quotes buying `targetOutcomeId` shares with `grossCollateralIn` via Complete-Set CPMM.
197
+ */
198
+ quoteBuyOutcomeShares(targetOutcomeId, grossCollateralIn) {
199
+ if (this.status !== "OPEN") throw new Error(`MARKET_NOT_OPEN: current status is ${this.status}`);
200
+ const normalizedTarget = assertNonEmptyTrimmed(targetOutcomeId, "TARGET_OUTCOME_ID");
201
+ if (!this.ammOutcomeReserves.has(normalizedTarget)) throw new Error(`UNKNOWN_OUTCOME_ID: ${normalizedTarget}`);
202
+ assertPositiveBigInt(grossCollateralIn, "GROSS_COLLATERAL_IN");
203
+ for (const outcome of this.config.outcomes) if ((this.ammOutcomeReserves.get(outcome) ?? 0n) <= 0n) throw new Error("AMM_NOT_SEEDED: all outcome reserves must be positive");
204
+ const { lpFeeBps, creatorFeeBps, hostFeeBps, protocolFeeBps } = this.config.feeConfig;
205
+ const lpFee = grossCollateralIn * BigInt(lpFeeBps) / BPS_DENOMINATOR;
206
+ const creatorFee = grossCollateralIn * BigInt(creatorFeeBps) / BPS_DENOMINATOR;
207
+ const hostFee = grossCollateralIn * BigInt(hostFeeBps) / BPS_DENOMINATOR;
208
+ const protocolFee = grossCollateralIn * BigInt(protocolFeeBps) / BPS_DENOMINATOR;
209
+ const totalFee = lpFee + creatorFee + hostFee + protocolFee;
210
+ const netCollateralIn = grossCollateralIn - totalFee;
211
+ if (netCollateralIn <= 0n) throw new Error("NET_COLLATERAL_ZERO: grossCollateralIn too small after fees");
212
+ let oldInvariantProduct = 1n;
213
+ let newOtherProduct = 1n;
214
+ const nextOutcomeReserves = Object.create(null);
215
+ for (const outcome of this.config.outcomes) {
216
+ const r = this.ammOutcomeReserves.get(outcome);
217
+ oldInvariantProduct *= r;
218
+ if (outcome !== normalizedTarget) {
219
+ const nextR = r + netCollateralIn;
220
+ nextOutcomeReserves[outcome] = nextR;
221
+ newOtherProduct *= nextR;
222
+ }
223
+ }
224
+ const oldTargetReserve = this.ammOutcomeReserves.get(normalizedTarget);
225
+ const nextTargetReserve = (oldInvariantProduct + newOtherProduct - 1n) / newOtherProduct;
226
+ nextOutcomeReserves[normalizedTarget] = nextTargetReserve;
227
+ return {
228
+ targetOutcomeId: normalizedTarget,
229
+ grossCollateralIn,
230
+ netCollateralIn,
231
+ totalFee,
232
+ lpFee,
233
+ creatorFee,
234
+ hostFee,
235
+ protocolFee,
236
+ sharesOut: netCollateralIn + (oldTargetReserve - nextTargetReserve),
237
+ nextOutcomeReserves
238
+ };
239
+ }
240
+ /**
241
+ * Executes a buy of `targetOutcomeId` shares with slippage protection (`minSharesOut`).
242
+ */
243
+ buyOutcomeShares(buyerDid, targetOutcomeId, grossCollateralIn, minSharesOut = 1n) {
244
+ const normalizedBuyer = assertNonEmptyTrimmed(buyerDid, "BUYER_DID");
245
+ assertPositiveBigInt(minSharesOut, "MIN_SHARES_OUT");
246
+ const quote = this.quoteBuyOutcomeShares(targetOutcomeId, grossCollateralIn);
247
+ if (quote.sharesOut < minSharesOut) throw new Error(`SLIPPAGE_EXCEEDED: sharesOut (${quote.sharesOut}) < minSharesOut (${minSharesOut})`);
248
+ this.lpFeeBucket += quote.lpFee;
249
+ this.creatorFeeBucket += quote.creatorFee;
250
+ this.hostFeeBucket += quote.hostFee;
251
+ this.protocolFeeBucket += quote.protocolFee;
252
+ this.collateralVaultBalance += quote.netCollateralIn;
253
+ this.totalCompleteSetsMinted += quote.netCollateralIn;
254
+ for (const outcome of this.config.outcomes) this.ammOutcomeReserves.set(outcome, quote.nextOutcomeReserves[outcome]);
255
+ const targetHolders = this.outcomeHolderBalances.get(quote.targetOutcomeId);
256
+ targetHolders.set(normalizedBuyer, (targetHolders.get(normalizedBuyer) ?? 0n) + quote.sharesOut);
257
+ return quote;
258
+ }
259
+ /**
260
+ * Submits an optimistic resolution proposal backed by a dispute bond.
261
+ */
262
+ proposeResolution(params) {
263
+ if (this.status !== "OPEN") throw new Error(`INVALID_STATE_FOR_PROPOSAL: ${this.status}`);
264
+ const proposerDid = assertNonEmptyTrimmed(params.proposerDid, "PROPOSER_DID");
265
+ const proposedOutcomeId = assertNonEmptyTrimmed(params.proposedOutcomeId, "PROPOSED_OUTCOME_ID");
266
+ const evidenceCid = assertNonEmptyTrimmed(params.evidenceCid, "EVIDENCE_CID");
267
+ assertPositiveBigInt(params.bondAmount, "BOND_AMOUNT");
268
+ assertNonNegativeSafeInteger(params.proposedAt, "PROPOSED_AT");
269
+ const challengeDeadline = params.proposedAt + this.config.challengeWindowSeconds;
270
+ if (!Number.isSafeInteger(challengeDeadline)) throw new Error("INVALID_PROPOSED_AT: challengeDeadline exceeds safe integer range");
271
+ if (params.bondAmount < this.config.requiredDisputeBond) throw new Error(`INSUFFICIENT_DISPUTE_BOND: ${params.bondAmount} < ${this.config.requiredDisputeBond}`);
272
+ if (proposedOutcomeId !== "VOID" && !this.ammOutcomeReserves.has(proposedOutcomeId)) throw new Error(`INVALID_PROPOSED_OUTCOME: ${proposedOutcomeId}`);
273
+ this.proposal = {
274
+ proposerDid,
275
+ proposedOutcomeId,
276
+ bondAmount: params.bondAmount,
277
+ proposedAt: params.proposedAt,
278
+ challengeDeadline,
279
+ evidenceCid
280
+ };
281
+ this.status = "PROPOSED";
282
+ return { ...this.proposal };
283
+ }
284
+ /**
285
+ * Challenges an active optimistic proposal within the challenge window.
286
+ */
287
+ challengeResolution(params) {
288
+ if (this.status !== "PROPOSED" || !this.proposal) throw new Error(`INVALID_STATE_FOR_CHALLENGE: ${this.status}`);
289
+ const challengerDid = assertNonEmptyTrimmed(params.challengerDid, "CHALLENGER_DID");
290
+ const reason = assertNonEmptyTrimmed(params.reason, "CHALLENGE_REASON");
291
+ assertPositiveBigInt(params.bondAmount, "CHALLENGE_BOND_AMOUNT");
292
+ assertNonNegativeSafeInteger(params.challengedAt, "CHALLENGED_AT");
293
+ if (challengerDid === this.proposal.proposerDid) throw new Error("SELF_CHALLENGE_NOT_ALLOWED: challenger cannot be the proposer");
294
+ if (params.challengedAt < this.proposal.proposedAt || params.challengedAt > this.proposal.challengeDeadline) throw new Error("CHALLENGE_WINDOW_CLOSED: timestamp outside valid challenge window");
295
+ if (params.bondAmount < this.proposal.bondAmount) throw new Error(`INSUFFICIENT_CHALLENGE_BOND: ${params.bondAmount} < ${this.proposal.bondAmount}`);
296
+ this.challenge = {
297
+ challengerDid,
298
+ bondAmount: params.bondAmount,
299
+ challengedAt: params.challengedAt,
300
+ reason
301
+ };
302
+ this.status = "CHALLENGED";
303
+ return { ...this.challenge };
304
+ }
305
+ /**
306
+ * Finalizes market resolution either after an unchallenged window or via arbiter adjudication.
307
+ */
308
+ finalizeResolution(params) {
309
+ assertNonNegativeSafeInteger(params.currentTimestamp, "CURRENT_TIMESTAMP");
310
+ if (this.status === "PROPOSED" && this.proposal) {
311
+ if (params.currentTimestamp <= this.proposal.challengeDeadline) throw new Error("CHALLENGE_WINDOW_STILL_ACTIVE: cannot finalize before deadline");
312
+ const outcome = this.proposal.proposedOutcomeId;
313
+ this.winningOutcomeId = outcome;
314
+ this.status = outcome === "VOID" ? "VOID" : "RESOLVED";
315
+ return {
316
+ status: this.status,
317
+ winningOutcomeId: outcome,
318
+ bondWinnerDid: this.proposal.proposerDid,
319
+ bondPayout: this.proposal.bondAmount
320
+ };
321
+ }
322
+ if (this.status === "CHALLENGED" && this.proposal && this.challenge) {
323
+ if (params.arbiterDid?.trim() !== this.config.arbiterDid) throw new Error("UNAUTHORIZED_ARBITER: caller is not configured market arbiter");
324
+ const outcome = params.adjudicatedOutcomeId?.trim();
325
+ if (!outcome || outcome !== "VOID" && !this.ammOutcomeReserves.has(outcome)) throw new Error(`INVALID_ADJUDICATED_OUTCOME: ${String(params.adjudicatedOutcomeId)}`);
326
+ this.winningOutcomeId = outcome;
327
+ this.status = outcome === "VOID" ? "VOID" : "RESOLVED";
328
+ const bondWinnerDid = outcome === this.proposal.proposedOutcomeId ? this.proposal.proposerDid : this.challenge.challengerDid;
329
+ const bondPayout = this.proposal.bondAmount + this.challenge.bondAmount;
330
+ return {
331
+ status: this.status,
332
+ winningOutcomeId: outcome,
333
+ bondWinnerDid,
334
+ bondPayout
335
+ };
336
+ }
337
+ throw new Error(`INVALID_STATE_FOR_FINALIZE: ${this.status}`);
338
+ }
339
+ /**
340
+ * Redeems a holder's winning shares 1:1 for collateral (or 1/N across outcomes if VOID).
341
+ */
342
+ redeemWinningShares(holderDid) {
343
+ const normalizedHolder = assertNonEmptyTrimmed(holderDid, "HOLDER_DID");
344
+ if (this.status === "RESOLVED" && this.winningOutcomeId) {
345
+ const holders = this.outcomeHolderBalances.get(this.winningOutcomeId);
346
+ const winningShares = holders.get(normalizedHolder) ?? 0n;
347
+ if (winningShares <= 0n) throw new Error(`NO_WINNING_SHARES: ${normalizedHolder} holds 0 shares of ${this.winningOutcomeId}`);
348
+ holders.set(normalizedHolder, 0n);
349
+ this.collateralVaultBalance -= winningShares;
350
+ return {
351
+ sharesBurned: winningShares,
352
+ collateralPayout: winningShares
353
+ };
354
+ }
355
+ if (this.status === "VOID") {
356
+ let totalSharesAcrossOutcomes = 0n;
357
+ for (const outcome of this.config.outcomes) {
358
+ const holders = this.outcomeHolderBalances.get(outcome);
359
+ totalSharesAcrossOutcomes += holders.get(normalizedHolder) ?? 0n;
360
+ }
361
+ if (totalSharesAcrossOutcomes <= 0n) throw new Error(`NO_SHARES_TO_REDEEM: ${normalizedHolder} holds 0 shares`);
362
+ const nOutcomes = BigInt(this.config.outcomes.length);
363
+ const collateralPayout = totalSharesAcrossOutcomes / nOutcomes;
364
+ if (collateralPayout <= 0n) throw new Error(`INSUFFICIENT_VOID_SHARES: ${totalSharesAcrossOutcomes} shares < ${nOutcomes} outcomes`);
365
+ for (const outcome of this.config.outcomes) this.outcomeHolderBalances.get(outcome).set(normalizedHolder, 0n);
366
+ this.collateralVaultBalance -= collateralPayout;
367
+ return {
368
+ sharesBurned: totalSharesAcrossOutcomes,
369
+ collateralPayout
370
+ };
371
+ }
372
+ throw new Error(`MARKET_NOT_FINALIZED: current status is ${this.status}`);
373
+ }
374
+ };
375
+
376
+ //#endregion
377
+ exports.ConditionalMarketPool = ConditionalMarketPool;
@@ -0,0 +1,151 @@
1
+ //#region src/conditional-market.d.ts
2
+ type ConditionalMarketStatus = 'OPEN' | 'PROPOSED' | 'CHALLENGED' | 'RESOLVED' | 'VOID';
3
+ interface ConditionalMarketFeeConfig {
4
+ readonly lpFeeBps: number;
5
+ readonly creatorFeeBps: number;
6
+ readonly hostFeeBps: number;
7
+ readonly protocolFeeBps: number;
8
+ }
9
+ interface ConditionalMarketConfig {
10
+ readonly marketId: string;
11
+ readonly question: string;
12
+ readonly outcomes: readonly string[];
13
+ readonly feeConfig: ConditionalMarketFeeConfig;
14
+ readonly requiredDisputeBond: bigint;
15
+ readonly challengeWindowSeconds: number;
16
+ readonly arbiterDid: string;
17
+ }
18
+ interface ConditionalResolutionProposal {
19
+ readonly proposerDid: string;
20
+ readonly proposedOutcomeId: string;
21
+ readonly bondAmount: bigint;
22
+ readonly proposedAt: number;
23
+ readonly challengeDeadline: number;
24
+ readonly evidenceCid: string;
25
+ }
26
+ interface ConditionalResolutionChallenge {
27
+ readonly challengerDid: string;
28
+ readonly bondAmount: bigint;
29
+ readonly challengedAt: number;
30
+ readonly reason: string;
31
+ }
32
+ interface OutcomeBuyQuote {
33
+ readonly targetOutcomeId: string;
34
+ readonly grossCollateralIn: bigint;
35
+ readonly netCollateralIn: bigint;
36
+ readonly totalFee: bigint;
37
+ readonly lpFee: bigint;
38
+ readonly creatorFee: bigint;
39
+ readonly hostFee: bigint;
40
+ readonly protocolFee: bigint;
41
+ readonly sharesOut: bigint;
42
+ readonly nextOutcomeReserves: Readonly<Record<string, bigint>>;
43
+ }
44
+ interface FinalizeResolutionResult {
45
+ readonly status: 'RESOLVED' | 'VOID';
46
+ readonly winningOutcomeId: string;
47
+ readonly bondWinnerDid: string;
48
+ readonly bondPayout: bigint;
49
+ }
50
+ /**
51
+ * Polymarket / Gnosis CTF-style Conditional Prediction Market Pool:
52
+ * - 100% collateralized Complete-Set Split & Merge (`splitPosition`, `mergePositions`)
53
+ * - Complete-Set Constant Product Automated Market Maker (`seedInitialLiquidity`, `quoteBuyOutcomeShares`, `buyOutcomeShares`)
54
+ * - 4-way trading fee split (`lpFeeBucket`, `creatorFeeBucket`, `hostFeeBucket`, `protocolFeeBucket`)
55
+ * - Optimistic resolution with challenge window, dispute bond slashing, and 1:1 winning share redemption
56
+ */
57
+ declare class ConditionalMarketPool {
58
+ readonly config: ConditionalMarketConfig;
59
+ private status;
60
+ private winningOutcomeId;
61
+ private collateralVaultBalance;
62
+ private totalCompleteSetsMinted;
63
+ private lpFeeBucket;
64
+ private creatorFeeBucket;
65
+ private hostFeeBucket;
66
+ private protocolFeeBucket;
67
+ private readonly ammOutcomeReserves;
68
+ private readonly outcomeHolderBalances;
69
+ private proposal;
70
+ private challenge;
71
+ constructor(config: ConditionalMarketConfig);
72
+ getStatus(): ConditionalMarketStatus;
73
+ getWinningOutcomeId(): string | null;
74
+ getCollateralVaultBalance(): bigint;
75
+ getTotalCompleteSetsMinted(): bigint;
76
+ getFeeBuckets(): {
77
+ lpFeeBucket: bigint;
78
+ creatorFeeBucket: bigint;
79
+ hostFeeBucket: bigint;
80
+ protocolFeeBucket: bigint;
81
+ };
82
+ getAmmOutcomeReserves(): Record<string, bigint>;
83
+ getHolderOutcomeBalance(holderDid: string, outcomeId: string): bigint;
84
+ /**
85
+ * Computes implied probabilities in basis points (summing to 10000 bps) from AMM reserves.
86
+ * For Complete-Set Constant Product AMM, price_i is proportional to prod_{j != i} R_j.
87
+ */
88
+ getImpliedProbabilitiesBps(): Record<string, number>;
89
+ /**
90
+ * Splits `collateralAmount` 1:1 into `collateralAmount` shares of every mutually exclusive outcome.
91
+ */
92
+ splitPosition(holderDid: string, collateralAmount: bigint): Record<string, bigint>;
93
+ /**
94
+ * Merges `shareAmount` complete sets across all outcomes back into `shareAmount` collateral 1:1.
95
+ */
96
+ mergePositions(holderDid: string, shareAmount: bigint): {
97
+ collateralReturned: bigint;
98
+ };
99
+ /**
100
+ * Transfers conditional outcome shares between holders.
101
+ */
102
+ transferOutcomeShares(outcomeId: string, fromDid: string, toDid: string, shareAmount: bigint): void;
103
+ /**
104
+ * Seeds initial AMM complete-set reserves by splitting `collateralAmount` across all outcomes.
105
+ */
106
+ seedInitialLiquidity(lpDid: string, collateralAmount: bigint): Record<string, bigint>;
107
+ /**
108
+ * Quotes buying `targetOutcomeId` shares with `grossCollateralIn` via Complete-Set CPMM.
109
+ */
110
+ quoteBuyOutcomeShares(targetOutcomeId: string, grossCollateralIn: bigint): OutcomeBuyQuote;
111
+ /**
112
+ * Executes a buy of `targetOutcomeId` shares with slippage protection (`minSharesOut`).
113
+ */
114
+ buyOutcomeShares(buyerDid: string, targetOutcomeId: string, grossCollateralIn: bigint, minSharesOut?: bigint): OutcomeBuyQuote;
115
+ /**
116
+ * Submits an optimistic resolution proposal backed by a dispute bond.
117
+ */
118
+ proposeResolution(params: {
119
+ proposerDid: string;
120
+ proposedOutcomeId: string;
121
+ bondAmount: bigint;
122
+ proposedAt: number;
123
+ evidenceCid: string;
124
+ }): ConditionalResolutionProposal;
125
+ /**
126
+ * Challenges an active optimistic proposal within the challenge window.
127
+ */
128
+ challengeResolution(params: {
129
+ challengerDid: string;
130
+ bondAmount: bigint;
131
+ challengedAt: number;
132
+ reason: string;
133
+ }): ConditionalResolutionChallenge;
134
+ /**
135
+ * Finalizes market resolution either after an unchallenged window or via arbiter adjudication.
136
+ */
137
+ finalizeResolution(params: {
138
+ currentTimestamp: number;
139
+ arbiterDid?: string;
140
+ adjudicatedOutcomeId?: string;
141
+ }): FinalizeResolutionResult;
142
+ /**
143
+ * Redeems a holder's winning shares 1:1 for collateral (or 1/N across outcomes if VOID).
144
+ */
145
+ redeemWinningShares(holderDid: string): {
146
+ sharesBurned: bigint;
147
+ collateralPayout: bigint;
148
+ };
149
+ }
150
+ //#endregion
151
+ export { ConditionalMarketConfig, ConditionalMarketFeeConfig, ConditionalMarketPool, ConditionalMarketStatus, ConditionalResolutionChallenge, ConditionalResolutionProposal, FinalizeResolutionResult, OutcomeBuyQuote };
package/lib/curve.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  const require_bn = require('./bn.cjs');
2
+ const require_index = require('./index.cjs');
2
3
 
3
4
  //#region src/curve.ts
4
5
  const ZERO = new require_bn.BN(0);
6
+ const ONE = new require_bn.BN(1);
5
7
  const TWO = new require_bn.BN(2);
6
8
  const THREE = new require_bn.BN(3);
7
9
  const TEN = new require_bn.BN(10);
@@ -11,9 +13,14 @@ let Direction = /* @__PURE__ */ function(Direction$1) {
11
13
  return Direction$1;
12
14
  }({});
13
15
  function getDecimalFactor(decimal) {
14
- if (!Number.isInteger(decimal) || decimal <= 0 || decimal > 78) throw new Error("INVALID_DECIMAL_FACTOR");
16
+ if (!Number.isInteger(decimal) || decimal < 0 || decimal > 78) throw new Error("INVALID_DECIMAL_FACTOR");
15
17
  return TEN.pow(new require_bn.BN(decimal));
16
18
  }
19
+ function divByDirection(numerator, denominator, direction) {
20
+ if (numerator.isZero()) return ZERO;
21
+ if (direction === Direction.Mint) return numerator.add(denominator).sub(ONE).div(denominator);
22
+ return numerator.div(denominator);
23
+ }
17
24
  function assertValidDirection(direction) {
18
25
  if (direction !== Direction.Mint && direction !== Direction.Burn) throw new Error("INVALID_DIRECTION");
19
26
  }
@@ -51,7 +58,7 @@ function calcConstantCost({ amount, fixedPrice, decimal, direction = Direction.M
51
58
  direction
52
59
  });
53
60
  if (amountBN.isZero()) return ZERO;
54
- return amountBN.mul(priceBN).div(decimalFactor);
61
+ return divByDirection(amountBN.mul(priceBN), decimalFactor, direction);
55
62
  }
56
63
  /**
57
64
  * linear Curve
@@ -92,9 +99,10 @@ function calcLinearCost(params) {
92
99
  if (params.direction === Direction.Burn && amount.gt(currentSupply)) throw new Error("SUPPLY_INSUFFICIENT");
93
100
  if (amount.isZero()) return ZERO;
94
101
  const integralDelta = params.direction === Direction.Mint ? amount.mul(currentSupply.mul(TWO).add(amount)) : amount.mul(currentSupply.mul(TWO).sub(amount));
95
- const linearTerm = basePrice.mul(amount).div(decimalFactor);
96
- const integralTerm = slope.mul(integralDelta).div(TWO.mul(decimalFactor.sqr()));
97
- return linearTerm.add(integralTerm);
102
+ const denominator = TWO.mul(decimalFactor.sqr());
103
+ const linearNumerator = TWO.mul(decimalFactor).mul(basePrice).mul(amount);
104
+ const integralNumerator = slope.mul(integralDelta);
105
+ return divByDirection(linearNumerator.add(integralNumerator), denominator, params.direction);
98
106
  }
99
107
  /**
100
108
  * Quadratic Curve
@@ -142,9 +150,8 @@ function calcQuadraticCost(params) {
142
150
  const sumSquaresAndProduct = newSupply.sqr().add(newSupply.mul(currentSupply)).add(currentSupply.sqr());
143
151
  const cubicDelta = diff.mul(sumSquaresAndProduct);
144
152
  const denom = THREE.mul(constant).mul(decimalFactor.sqr());
145
- const cubicCost = cubicDelta.div(denom);
146
- const linearCost = basePrice.mul(amount).div(decimalFactor);
147
- return cubicCost.add(linearCost);
153
+ const linearNumerator = THREE.mul(constant).mul(decimalFactor).mul(basePrice).mul(amount);
154
+ return divByDirection(cubicDelta.add(linearNumerator), denom, params.direction);
148
155
  }
149
156
  function calcFee({ reserveAmount, feeRate }) {
150
157
  const reserveBN = new require_bn.BN(reserveAmount);
@@ -200,6 +207,61 @@ function calcCost({ amount, decimal, currentSupply, direction, curve }) {
200
207
  if (!calculator) throw new Error("INVALID_CURVE_TYPE");
201
208
  return calculator();
202
209
  }
210
+ /**
211
+ * 3-Token Model Prepaid Quota Minting & Revenue Split (#1168).
212
+ *
213
+ * Separates ABT reserve payment for consumable `Quota` (CreditToken) from `ArcKey` (BondingCurveToken)
214
+ * reserve pool so service consumption never drains the bonding curve redemption reserve.
215
+ */
216
+ function calcQuotaMintFromPayment(params) {
217
+ const reservePaid = require_index.toBN(params.reservePaid);
218
+ const unitPrice = require_index.toBN(params.unitPrice);
219
+ const decimal = params.decimal ?? 2;
220
+ const creatorFeeBps = params.creatorFeeBps ?? 9500;
221
+ const protocolFeeBps = params.protocolFeeBps ?? 500;
222
+ if (reservePaid.lte(ZERO)) throw new Error("INVALID_RESERVE_AMOUNT");
223
+ if (unitPrice.lte(ZERO)) throw new Error("INVALID_PRICE");
224
+ if (!Number.isInteger(decimal) || decimal < 0 || decimal > 18) throw new Error("INVALID_DECIMAL");
225
+ if (!Number.isInteger(creatorFeeBps) || !Number.isInteger(protocolFeeBps) || creatorFeeBps < 0 || protocolFeeBps < 0 || creatorFeeBps + protocolFeeBps > 1e4) throw new Error("INVALID_FEE_RATE");
226
+ const decimalFactor = TEN.pow(new require_bn.BN(decimal));
227
+ const quotaMinted = reservePaid.mul(decimalFactor).div(unitPrice);
228
+ if (quotaMinted.lte(ZERO)) throw new Error("INSUFFICIENT_PAYMENT_FOR_QUOTA");
229
+ const effectiveReserveCost = divByDirection(quotaMinted.mul(unitPrice), decimalFactor, Direction.Mint);
230
+ const refundReserve = reservePaid.sub(effectiveReserveCost);
231
+ const bpsDenom = new require_bn.BN(1e4);
232
+ const protocolFee = effectiveReserveCost.mul(new require_bn.BN(protocolFeeBps)).div(bpsDenom);
233
+ const creatorRevenue = effectiveReserveCost.mul(new require_bn.BN(creatorFeeBps)).div(bpsDenom);
234
+ return {
235
+ quotaMinted,
236
+ effectiveReserveCost,
237
+ refundReserve,
238
+ creatorRevenue,
239
+ protocolFee,
240
+ serviceEscrow: effectiveReserveCost.sub(protocolFee).sub(creatorRevenue)
241
+ };
242
+ }
243
+ /**
244
+ * 3-Token Model Prepaid Quota Consumption & ArcKey Gating Check (#1168).
245
+ *
246
+ * Verifies the caller holds the required indivisible `ArcKey` balance (without burning `ArcKey`),
247
+ * enforces `Quota` expiration, and burns `consumeAmount` of prepaid `Quota`.
248
+ */
249
+ function consumePrepaidQuota(params) {
250
+ const availableQuota = require_index.toBN(params.availableQuota);
251
+ const consumeAmount = require_index.toBN(params.consumeAmount);
252
+ const userArcKeyBalance = require_index.toBN(params.userArcKeyBalance ?? 1);
253
+ const minArcKeyBalance = require_index.toBN(params.minArcKeyBalance ?? 1);
254
+ if (availableQuota.lt(ZERO)) throw new Error("INVALID_QUOTA_BALANCE");
255
+ if (consumeAmount.lte(ZERO)) throw new Error("INVALID_CONSUME_AMOUNT");
256
+ if (userArcKeyBalance.lt(minArcKeyBalance)) throw new Error("INSUFFICIENT_ARCKEY_PASS");
257
+ if (typeof params.expiresAt === "number" && params.expiresAt > 0 && typeof params.now === "number" && params.now > params.expiresAt) throw new Error("QUOTA_EXPIRED");
258
+ if (availableQuota.lt(consumeAmount)) throw new Error("INSUFFICIENT_QUOTA");
259
+ return {
260
+ burnedQuota: consumeAmount,
261
+ remainingQuota: availableQuota.sub(consumeAmount),
262
+ arcKeyBalanceAfter: userArcKeyBalance
263
+ };
264
+ }
203
265
 
204
266
  //#endregion
205
267
  exports.Direction = Direction;
@@ -211,4 +273,6 @@ exports.calcLinearCost = calcLinearCost;
211
273
  exports.calcLinearPrice = calcLinearPrice;
212
274
  exports.calcPrice = calcPrice;
213
275
  exports.calcQuadraticCost = calcQuadraticCost;
214
- exports.calcQuadraticPrice = calcQuadraticPrice;
276
+ exports.calcQuadraticPrice = calcQuadraticPrice;
277
+ exports.calcQuotaMintFromPayment = calcQuotaMintFromPayment;
278
+ exports.consumePrepaidQuota = consumePrepaidQuota;