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