@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
package/esm/amm.d.mts ADDED
@@ -0,0 +1,158 @@
1
+ import { BN } from "./bn.mjs";
2
+ import { calcPrice } from "./curve.mjs";
3
+
4
+ //#region src/amm.d.ts
5
+ type BNInput = string | number | BN;
6
+ /**
7
+ * Minimum LP shares permanently locked on initial pool creation (Uniswap V2 invariant)
8
+ * to prevent LP share inflation / donation attacks (#1171).
9
+ */
10
+ declare const MINIMUM_LIQUIDITY = 1000;
11
+ /**
12
+ * Maximum combined LP + protocol fee in basis points (2000 bps = 20%).
13
+ */
14
+ declare const MAX_TOTAL_FEE_BPS = 2000;
15
+ /**
16
+ * Exact floor integer square root for arbitrary-precision non-negative BN:
17
+ * returns largest integer r such that r * r <= n.
18
+ */
19
+ declare function isqrt(input: BNInput): BN;
20
+ /**
21
+ * Calculate initial LP share minting for a new Constant Product (`x * y = k`) pool (#1171).
22
+ * Permanently locks `MINIMUM_LIQUIDITY` (1000) shares to prevent first-depositor inflation attacks.
23
+ */
24
+ declare function calcInitialLiquidity(amount0Input: BNInput, amount1Input: BNInput): {
25
+ liquidity: BN;
26
+ lockedMinimumLiquidity: BN;
27
+ totalLpSupply: BN;
28
+ };
29
+ /**
30
+ * Calculate optimal deposit amounts and LP shares for adding liquidity to an existing pool (#1171).
31
+ * Uses floor division for minted LP shares so existing LPs are never diluted.
32
+ */
33
+ declare function calcAddLiquidity(params: {
34
+ amount0Desired: BNInput;
35
+ amount1Desired: BNInput;
36
+ amount0Min?: BNInput;
37
+ amount1Min?: BNInput;
38
+ reserve0: BNInput;
39
+ reserve1: BNInput;
40
+ totalLpSupply: BNInput;
41
+ }): {
42
+ amount0: BN;
43
+ amount1: BN;
44
+ liquidity: BN;
45
+ };
46
+ /**
47
+ * Calculate token withdrawals when burning LP shares (#1171).
48
+ * Uses floor division so remaining pool reserves are never under-collateralized.
49
+ */
50
+ declare function calcRemoveLiquidity(params: {
51
+ liquidity: BNInput;
52
+ reserve0: BNInput;
53
+ reserve1: BNInput;
54
+ totalLpSupply: BNInput;
55
+ }): {
56
+ amount0: BN;
57
+ amount1: BN;
58
+ };
59
+ /**
60
+ * Constant Product (`x * y = k`) Exact-In Swap with LP & Protocol Fee Split (#1171).
61
+ *
62
+ * - `protocolFee` is routed out of the pool (e.g. to `#1054` Stake revenue vault).
63
+ * - `lpFee` remains inside `newReserveIn`, growing `k = newReserveIn * newReserveOut` for LPs.
64
+ * - `amountOut` is floored so `newReserveIn * newReserveOut >= reserveIn * reserveOut` always holds.
65
+ */
66
+ declare function calcSwapExactIn(params: {
67
+ amountIn: BNInput;
68
+ reserveIn: BNInput;
69
+ reserveOut: BNInput;
70
+ lpFeeBps?: number;
71
+ protocolFeeBps?: number;
72
+ }): {
73
+ amountOut: BN;
74
+ lpFee: BN;
75
+ protocolFee: BN;
76
+ amountInAfterFee: BN;
77
+ newReserveIn: BN;
78
+ newReserveOut: BN;
79
+ };
80
+ /**
81
+ * Constant Product (`x * y = k`) Exact-Out Swap with LP & Protocol Fee Split (#1171).
82
+ * Uses `ceilDiv` so the pool never loses 1 unit to rounding.
83
+ */
84
+ declare function calcSwapExactOut(params: {
85
+ amountOut: BNInput;
86
+ reserveIn: BNInput;
87
+ reserveOut: BNInput;
88
+ lpFeeBps?: number;
89
+ protocolFeeBps?: number;
90
+ }): {
91
+ amountIn: BN;
92
+ lpFee: BN;
93
+ protocolFee: BN;
94
+ amountInAfterFee: BN;
95
+ newReserveIn: BN;
96
+ newReserveOut: BN;
97
+ };
98
+ /**
99
+ * Escrowed Limit Order Partial Fill Settlement Math (#1171).
100
+ *
101
+ * Guarantees the maker's limit price is never violated by partial-fill integer truncation:
102
+ * requiredMakerOut = ceil(fillAmountIn * makerMinAmountOut / makerOfferAmountIn)
103
+ */
104
+ declare function calcLimitOrderFill(params: {
105
+ makerOfferAmountIn: BNInput;
106
+ makerMinAmountOut: BNInput;
107
+ remainingAmountIn: BNInput;
108
+ fillAmountIn: BNInput;
109
+ takerOfferAmountOut: BNInput;
110
+ protocolFeeBps?: number;
111
+ }): {
112
+ requiredMakerOut: BN;
113
+ makerReceivedOut: BN;
114
+ protocolFeeOut: BN;
115
+ newRemainingAmountIn: BN;
116
+ isFullyFilled: boolean;
117
+ };
118
+ /**
119
+ * Day-0 Bonding Curve + AMM Graduation Supply Cap Split (#1172).
120
+ *
121
+ * Enforces `maxTotalSupply = maxCurveSupply + lpReserveSupply` with both components strictly positive,
122
+ * preventing post-graduation supply inflation beyond `maxTotalSupply`.
123
+ */
124
+ declare function calcGraduationSupplySplit(params: {
125
+ maxTotalSupply: BNInput;
126
+ lpReserveBps?: number;
127
+ lpReserveSupply?: BNInput;
128
+ }): {
129
+ maxTotalSupply: BN;
130
+ maxCurveSupply: BN;
131
+ lpReserveSupply: BN;
132
+ };
133
+ /**
134
+ * Atomic Bonding Curve -> Constant Product AMM Graduation Settlement (#1172).
135
+ *
136
+ * Ensures spot-price continuity at graduation (`P_amm = R_lp / S_amm == P_spot(S_curve)`)
137
+ * so no instant arbitrage gap exists at the moment of migration,burns any unallocated
138
+ * LP reserve tokens so `totalSupply <= maxTotalSupply`, and permanently locks the initial AMM LP.
139
+ */
140
+ declare function calcGraduationSettlement(params: {
141
+ curve: Parameters<typeof calcPrice>[0]['curve'];
142
+ decimal: number;
143
+ maxCurveSupply: BNInput;
144
+ lpReserveSupply: BNInput;
145
+ reserveBalance: BNInput;
146
+ graduationFeeBps?: number;
147
+ }): {
148
+ spotPrice: BN;
149
+ graduationFee: BN;
150
+ ammReserveAmount: BN;
151
+ ammTokenAmount: BN;
152
+ burnedLpTokenAmount: BN;
153
+ lockedLiquidity: BN;
154
+ permanentLiquidity: BN;
155
+ totalLiquidity: BN;
156
+ };
157
+ //#endregion
158
+ export { BNInput, MAX_TOTAL_FEE_BPS, MINIMUM_LIQUIDITY, calcAddLiquidity, calcGraduationSettlement, calcGraduationSupplySplit, calcInitialLiquidity, calcLimitOrderFill, calcRemoveLiquidity, calcSwapExactIn, calcSwapExactOut, isqrt };
package/esm/amm.mjs ADDED
@@ -0,0 +1,269 @@
1
+ import { BN } from "./bn.mjs";
2
+ import { toBN } from "./index.mjs";
3
+ import { calcPrice } from "./curve.mjs";
4
+
5
+ //#region src/amm.ts
6
+ const ZERO = new BN(0);
7
+ const ONE = new BN(1);
8
+ const BPS_DENOMINATOR = new BN(1e4);
9
+ /**
10
+ * Minimum LP shares permanently locked on initial pool creation (Uniswap V2 invariant)
11
+ * to prevent LP share inflation / donation attacks (#1171).
12
+ */
13
+ const MINIMUM_LIQUIDITY = 1e3;
14
+ /**
15
+ * Maximum combined LP + protocol fee in basis points (2000 bps = 20%).
16
+ */
17
+ const MAX_TOTAL_FEE_BPS = 2e3;
18
+ function ceilDiv(numerator, denominator) {
19
+ if (denominator.lte(ZERO)) throw new Error("Division by non-positive denominator");
20
+ if (numerator.lte(ZERO)) return ZERO;
21
+ return numerator.add(denominator).sub(ONE).div(denominator);
22
+ }
23
+ function assertPositiveBN(val, name) {
24
+ const bn = toBN(val);
25
+ if (bn.lte(ZERO)) throw new Error(`Invalid ${name}: must be greater than 0`);
26
+ return bn;
27
+ }
28
+ function assertNonNegativeBps(bps, name) {
29
+ if (!Number.isInteger(bps) || bps < 0 || bps > MAX_TOTAL_FEE_BPS) throw new Error(`Invalid ${name}: must be an integer between 0 and ${MAX_TOTAL_FEE_BPS}`);
30
+ return bps;
31
+ }
32
+ /**
33
+ * Exact floor integer square root for arbitrary-precision non-negative BN:
34
+ * returns largest integer r such that r * r <= n.
35
+ */
36
+ function isqrt(input) {
37
+ const n = toBN(input);
38
+ if (n.lt(ZERO)) throw new Error("Cannot compute square root of negative number");
39
+ if (n.isZero()) return ZERO;
40
+ if (n.lte(new BN(3))) return ONE;
41
+ let x0 = ONE.shln(n.bitLength() + 1 >> 1);
42
+ let x1 = x0.add(n.div(x0)).shrn(1);
43
+ while (x1.lt(x0)) {
44
+ x0 = x1;
45
+ x1 = x0.add(n.div(x0)).shrn(1);
46
+ }
47
+ return x0;
48
+ }
49
+ /**
50
+ * Calculate initial LP share minting for a new Constant Product (`x * y = k`) pool (#1171).
51
+ * Permanently locks `MINIMUM_LIQUIDITY` (1000) shares to prevent first-depositor inflation attacks.
52
+ */
53
+ function calcInitialLiquidity(amount0Input, amount1Input) {
54
+ const amount0 = assertPositiveBN(amount0Input, "amount0");
55
+ const amount1 = assertPositiveBN(amount1Input, "amount1");
56
+ const totalLpSupply = isqrt(amount0.mul(amount1));
57
+ const lockedMinimumLiquidity = new BN(MINIMUM_LIQUIDITY);
58
+ if (totalLpSupply.lte(lockedMinimumLiquidity)) throw new Error(`Insufficient initial liquidity: sqrt(amount0 * amount1) must exceed ${MINIMUM_LIQUIDITY}`);
59
+ return {
60
+ liquidity: totalLpSupply.sub(lockedMinimumLiquidity),
61
+ lockedMinimumLiquidity,
62
+ totalLpSupply
63
+ };
64
+ }
65
+ /**
66
+ * Calculate optimal deposit amounts and LP shares for adding liquidity to an existing pool (#1171).
67
+ * Uses floor division for minted LP shares so existing LPs are never diluted.
68
+ */
69
+ function calcAddLiquidity(params) {
70
+ const amount0Desired = assertPositiveBN(params.amount0Desired, "amount0Desired");
71
+ const amount1Desired = assertPositiveBN(params.amount1Desired, "amount1Desired");
72
+ const reserve0 = assertPositiveBN(params.reserve0, "reserve0");
73
+ const reserve1 = assertPositiveBN(params.reserve1, "reserve1");
74
+ const totalLpSupply = assertPositiveBN(params.totalLpSupply, "totalLpSupply");
75
+ const amount0Min = params.amount0Min !== void 0 ? toBN(params.amount0Min) : ZERO;
76
+ const amount1Min = params.amount1Min !== void 0 ? toBN(params.amount1Min) : ZERO;
77
+ let amount0;
78
+ let amount1;
79
+ const amount1Optimal = ceilDiv(amount0Desired.mul(reserve1), reserve0);
80
+ if (amount1Optimal.lte(amount1Desired)) {
81
+ if (amount1Optimal.lt(amount1Min)) throw new Error("Slippage exceeded: amount1Optimal is below amount1Min");
82
+ amount0 = amount0Desired;
83
+ amount1 = amount1Optimal;
84
+ } else {
85
+ const amount0Optimal = ceilDiv(amount1Desired.mul(reserve0), reserve1);
86
+ if (amount0Optimal.gt(amount0Desired) || amount0Optimal.lt(amount0Min)) throw new Error("Slippage exceeded: amount0Optimal is below amount0Min");
87
+ amount0 = amount0Optimal;
88
+ amount1 = amount1Desired;
89
+ }
90
+ const liquidity0 = amount0.mul(totalLpSupply).div(reserve0);
91
+ const liquidity1 = amount1.mul(totalLpSupply).div(reserve1);
92
+ const liquidity = liquidity0.lt(liquidity1) ? liquidity0 : liquidity1;
93
+ if (liquidity.lte(ZERO)) throw new Error("Insufficient liquidity minted");
94
+ return {
95
+ amount0,
96
+ amount1,
97
+ liquidity
98
+ };
99
+ }
100
+ /**
101
+ * Calculate token withdrawals when burning LP shares (#1171).
102
+ * Uses floor division so remaining pool reserves are never under-collateralized.
103
+ */
104
+ function calcRemoveLiquidity(params) {
105
+ const liquidity = assertPositiveBN(params.liquidity, "liquidity");
106
+ const reserve0 = assertPositiveBN(params.reserve0, "reserve0");
107
+ const reserve1 = assertPositiveBN(params.reserve1, "reserve1");
108
+ const totalLpSupply = assertPositiveBN(params.totalLpSupply, "totalLpSupply");
109
+ if (liquidity.gt(totalLpSupply)) throw new Error("Invalid liquidity: exceeds totalLpSupply");
110
+ const amount0 = liquidity.mul(reserve0).div(totalLpSupply);
111
+ const amount1 = liquidity.mul(reserve1).div(totalLpSupply);
112
+ if (amount0.lte(ZERO) || amount1.lte(ZERO)) throw new Error("Insufficient liquidity burned: output amount is zero");
113
+ return {
114
+ amount0,
115
+ amount1
116
+ };
117
+ }
118
+ /**
119
+ * Constant Product (`x * y = k`) Exact-In Swap with LP & Protocol Fee Split (#1171).
120
+ *
121
+ * - `protocolFee` is routed out of the pool (e.g. to `#1054` Stake revenue vault).
122
+ * - `lpFee` remains inside `newReserveIn`, growing `k = newReserveIn * newReserveOut` for LPs.
123
+ * - `amountOut` is floored so `newReserveIn * newReserveOut >= reserveIn * reserveOut` always holds.
124
+ */
125
+ function calcSwapExactIn(params) {
126
+ const amountIn = assertPositiveBN(params.amountIn, "amountIn");
127
+ const reserveIn = assertPositiveBN(params.reserveIn, "reserveIn");
128
+ const reserveOut = assertPositiveBN(params.reserveOut, "reserveOut");
129
+ const lpFeeBps = assertNonNegativeBps(params.lpFeeBps ?? 25, "lpFeeBps");
130
+ const protocolFeeBps = assertNonNegativeBps(params.protocolFeeBps ?? 5, "protocolFeeBps");
131
+ const totalFeeBps = lpFeeBps + protocolFeeBps;
132
+ assertNonNegativeBps(totalFeeBps, "totalFeeBps");
133
+ const totalFee = totalFeeBps > 0 ? ceilDiv(amountIn.mul(new BN(totalFeeBps)), BPS_DENOMINATOR) : ZERO;
134
+ const protocolFee = totalFeeBps > 0 && protocolFeeBps > 0 ? totalFee.mul(new BN(protocolFeeBps)).div(new BN(totalFeeBps)) : ZERO;
135
+ const lpFee = totalFee.sub(protocolFee);
136
+ const amountInAfterFee = amountIn.sub(totalFee);
137
+ if (amountInAfterFee.lte(ZERO)) throw new Error("Insufficient amountIn: zero after fee deduction");
138
+ const numerator = amountInAfterFee.mul(reserveOut);
139
+ const denominator = reserveIn.add(amountInAfterFee);
140
+ const amountOut = numerator.div(denominator);
141
+ if (amountOut.lte(ZERO) || amountOut.gte(reserveOut)) throw new Error("Insufficient liquidity for swap output");
142
+ return {
143
+ amountOut,
144
+ lpFee,
145
+ protocolFee,
146
+ amountInAfterFee,
147
+ newReserveIn: reserveIn.add(amountInAfterFee).add(lpFee),
148
+ newReserveOut: reserveOut.sub(amountOut)
149
+ };
150
+ }
151
+ /**
152
+ * Constant Product (`x * y = k`) Exact-Out Swap with LP & Protocol Fee Split (#1171).
153
+ * Uses `ceilDiv` so the pool never loses 1 unit to rounding.
154
+ */
155
+ function calcSwapExactOut(params) {
156
+ const amountOut = assertPositiveBN(params.amountOut, "amountOut");
157
+ const reserveIn = assertPositiveBN(params.reserveIn, "reserveIn");
158
+ const reserveOut = assertPositiveBN(params.reserveOut, "reserveOut");
159
+ const lpFeeBps = assertNonNegativeBps(params.lpFeeBps ?? 25, "lpFeeBps");
160
+ const protocolFeeBps = assertNonNegativeBps(params.protocolFeeBps ?? 5, "protocolFeeBps");
161
+ const totalFeeBps = lpFeeBps + protocolFeeBps;
162
+ assertNonNegativeBps(totalFeeBps, "totalFeeBps");
163
+ if (amountOut.gte(reserveOut)) throw new Error("Insufficient liquidity: amountOut must be strictly less than reserveOut");
164
+ const amountInAfterFee = ceilDiv(reserveIn.mul(amountOut), reserveOut.sub(amountOut));
165
+ const netBps = new BN(1e4 - totalFeeBps);
166
+ const amountIn = totalFeeBps > 0 ? ceilDiv(amountInAfterFee.mul(BPS_DENOMINATOR), netBps) : amountInAfterFee;
167
+ const totalFee = amountIn.sub(amountInAfterFee);
168
+ const protocolFee = totalFeeBps > 0 && protocolFeeBps > 0 ? totalFee.mul(new BN(protocolFeeBps)).div(new BN(totalFeeBps)) : ZERO;
169
+ const lpFee = totalFee.sub(protocolFee);
170
+ return {
171
+ amountIn,
172
+ lpFee,
173
+ protocolFee,
174
+ amountInAfterFee,
175
+ newReserveIn: reserveIn.add(amountInAfterFee).add(lpFee),
176
+ newReserveOut: reserveOut.sub(amountOut)
177
+ };
178
+ }
179
+ /**
180
+ * Escrowed Limit Order Partial Fill Settlement Math (#1171).
181
+ *
182
+ * Guarantees the maker's limit price is never violated by partial-fill integer truncation:
183
+ * requiredMakerOut = ceil(fillAmountIn * makerMinAmountOut / makerOfferAmountIn)
184
+ */
185
+ function calcLimitOrderFill(params) {
186
+ const makerOfferAmountIn = assertPositiveBN(params.makerOfferAmountIn, "makerOfferAmountIn");
187
+ const makerMinAmountOut = assertPositiveBN(params.makerMinAmountOut, "makerMinAmountOut");
188
+ const remainingAmountIn = assertPositiveBN(params.remainingAmountIn, "remainingAmountIn");
189
+ const fillAmountIn = assertPositiveBN(params.fillAmountIn, "fillAmountIn");
190
+ const takerOfferAmountOut = assertPositiveBN(params.takerOfferAmountOut, "takerOfferAmountOut");
191
+ const protocolFeeBps = assertNonNegativeBps(params.protocolFeeBps ?? 5, "protocolFeeBps");
192
+ if (remainingAmountIn.gt(makerOfferAmountIn)) throw new Error("Invalid remainingAmountIn: exceeds makerOfferAmountIn");
193
+ if (fillAmountIn.gt(remainingAmountIn)) throw new Error("Invalid fillAmountIn: exceeds remainingAmountIn");
194
+ const requiredMakerOut = ceilDiv(fillAmountIn.mul(makerMinAmountOut), makerOfferAmountIn);
195
+ const protocolFeeOut = protocolFeeBps > 0 ? ceilDiv(requiredMakerOut.mul(new BN(protocolFeeBps)), BPS_DENOMINATOR) : ZERO;
196
+ if (takerOfferAmountOut.lt(requiredMakerOut.add(protocolFeeOut))) throw new Error("Limit order price not met: takerOfferAmountOut is below requiredMakerOut + protocolFeeOut");
197
+ const makerReceivedOut = takerOfferAmountOut.sub(protocolFeeOut);
198
+ const newRemainingAmountIn = remainingAmountIn.sub(fillAmountIn);
199
+ return {
200
+ requiredMakerOut,
201
+ makerReceivedOut,
202
+ protocolFeeOut,
203
+ newRemainingAmountIn,
204
+ isFullyFilled: newRemainingAmountIn.isZero()
205
+ };
206
+ }
207
+ /**
208
+ * Day-0 Bonding Curve + AMM Graduation Supply Cap Split (#1172).
209
+ *
210
+ * Enforces `maxTotalSupply = maxCurveSupply + lpReserveSupply` with both components strictly positive,
211
+ * preventing post-graduation supply inflation beyond `maxTotalSupply`.
212
+ */
213
+ function calcGraduationSupplySplit(params) {
214
+ const maxTotalSupply = assertPositiveBN(params.maxTotalSupply, "maxTotalSupply");
215
+ let lpReserveSupply;
216
+ if (params.lpReserveSupply !== void 0 && params.lpReserveSupply !== null && params.lpReserveSupply !== "") lpReserveSupply = assertPositiveBN(params.lpReserveSupply, "lpReserveSupply");
217
+ else {
218
+ const lpReserveBps = params.lpReserveBps ?? 2e3;
219
+ if (typeof lpReserveBps !== "number" || !Number.isInteger(lpReserveBps) || lpReserveBps <= 0 || lpReserveBps >= 1e4) throw new Error(`Invalid lpReserveBps: ${lpReserveBps}. Must be an integer in (0, 10000)`);
220
+ lpReserveSupply = maxTotalSupply.mul(new BN(lpReserveBps)).div(BPS_DENOMINATOR);
221
+ }
222
+ if (lpReserveSupply.lte(ZERO) || lpReserveSupply.gte(maxTotalSupply)) throw new Error("Invalid graduation supply split: lpReserveSupply must be strictly between 0 and maxTotalSupply");
223
+ return {
224
+ maxTotalSupply,
225
+ maxCurveSupply: maxTotalSupply.sub(lpReserveSupply),
226
+ lpReserveSupply
227
+ };
228
+ }
229
+ /**
230
+ * Atomic Bonding Curve -> Constant Product AMM Graduation Settlement (#1172).
231
+ *
232
+ * Ensures spot-price continuity at graduation (`P_amm = R_lp / S_amm == P_spot(S_curve)`)
233
+ * so no instant arbitrage gap exists at the moment of migration,burns any unallocated
234
+ * LP reserve tokens so `totalSupply <= maxTotalSupply`, and permanently locks the initial AMM LP.
235
+ */
236
+ function calcGraduationSettlement(params) {
237
+ const maxCurveSupply = assertPositiveBN(params.maxCurveSupply, "maxCurveSupply");
238
+ const lpReserveSupply = assertPositiveBN(params.lpReserveSupply, "lpReserveSupply");
239
+ const reserveBalance = assertPositiveBN(params.reserveBalance, "reserveBalance");
240
+ const graduationFeeBps = assertNonNegativeBps(params.graduationFeeBps ?? 100, "graduationFeeBps");
241
+ if (typeof params.decimal !== "number" || !Number.isInteger(params.decimal) || params.decimal < 0 || params.decimal > 18) throw new Error(`Invalid decimal: ${params.decimal}`);
242
+ const spotPrice = calcPrice({
243
+ currentSupply: maxCurveSupply,
244
+ decimal: params.decimal,
245
+ curve: params.curve
246
+ });
247
+ if (!spotPrice || spotPrice.lte(ZERO)) throw new Error("Invalid spotPrice at graduation cap");
248
+ const graduationFee = graduationFeeBps > 0 ? reserveBalance.mul(new BN(graduationFeeBps)).div(BPS_DENOMINATOR) : ZERO;
249
+ const ammReserveAmount = reserveBalance.sub(graduationFee);
250
+ const scale = new BN(10).pow(new BN(params.decimal));
251
+ const idealAmmTokenAmount = ammReserveAmount.mul(scale).div(spotPrice);
252
+ if (idealAmmTokenAmount.lte(ZERO)) throw new Error("Insufficient reserveBalance to seed AMM liquidity at graduation spot price");
253
+ const ammTokenAmount = idealAmmTokenAmount.gt(lpReserveSupply) ? lpReserveSupply : idealAmmTokenAmount;
254
+ const burnedLpTokenAmount = lpReserveSupply.sub(ammTokenAmount);
255
+ const { liquidity, lockedMinimumLiquidity, totalLpSupply } = calcInitialLiquidity(ammReserveAmount, ammTokenAmount);
256
+ return {
257
+ spotPrice,
258
+ graduationFee,
259
+ ammReserveAmount,
260
+ ammTokenAmount,
261
+ burnedLpTokenAmount,
262
+ lockedLiquidity: lockedMinimumLiquidity,
263
+ permanentLiquidity: liquidity,
264
+ totalLiquidity: totalLpSupply
265
+ };
266
+ }
267
+
268
+ //#endregion
269
+ export { MAX_TOTAL_FEE_BPS, MINIMUM_LIQUIDITY, calcAddLiquidity, calcGraduationSettlement, calcGraduationSupplySplit, calcInitialLiquidity, calcLimitOrderFill, calcRemoveLiquidity, calcSwapExactIn, calcSwapExactOut, isqrt };
@@ -0,0 +1,217 @@
1
+ //#region src/arcade.d.ts
2
+ /**
3
+ * Verifies a single step of an inverted SHA-256 commit-reveal hash chain:
4
+ * `sha256Hex(serverSeedPreimage) === expectedCommitHash`.
5
+ */
6
+ declare function verifyHashChainStep(serverSeedPreimage: string, expectedCommitHash: string): boolean;
7
+ /**
8
+ * Generates an inverted SHA-256 hash chain of length `steps` from a terminal seed.
9
+ * Element `0` is the terminal secret (`seed_N`), and element `steps - 1` is the initial
10
+ * public commitment (`commit_0 = H^(steps-1)(seed_N)`).
11
+ */
12
+ declare function generateHashChain(terminalSeed: string, steps: number): string[];
13
+ interface ProvablyFairRollInput {
14
+ /** Preimage revealed by the arcade/table for the current hash-chain index */
15
+ serverSeedPreimage: string;
16
+ /** Committed hash stored on-chain before the player's receipt was locked */
17
+ expectedCommitHash: string;
18
+ /** Canonical ForeignReceipt ID or on-chain transaction hash locking the bet */
19
+ receiptId: string;
20
+ /** Player-supplied client seed (entropy bound in the play request) */
21
+ clientSeed: string;
22
+ /** Strictly monotonic per-machine or per-player play nonce */
23
+ playNonce: bigint | number | string;
24
+ /** Upper bound (exclusive) for the uniform roll, defaults to 10_000 (basis points) */
25
+ modulus?: bigint | number | string;
26
+ }
27
+ interface ProvablyFairRollResult {
28
+ entropyHex: string;
29
+ nextCommitHash: string;
30
+ roll: bigint;
31
+ modulus: bigint;
32
+ }
33
+ /**
34
+ * Receipt-then-Reveal Provably Fair Randomness derivation:
35
+ * 1. Verifies `sha256(serverSeedPreimage) === expectedCommitHash`
36
+ * 2. Combines `(serverSeedPreimage, receiptId, clientSeed, playNonce)` via domain-separated SHA-256
37
+ * 3. Extracts an unbiased 256-bit integer modulo `modulus`
38
+ */
39
+ declare function deriveProvablyFairRoll(input: ProvablyFairRollInput): ProvablyFairRollResult;
40
+ interface LootTableTier {
41
+ tierId: string;
42
+ weight: number;
43
+ payoutMultiplierBps: number;
44
+ }
45
+ interface PityConfig {
46
+ /** Number of consecutive non-high-tier rolls before pity triggers (e.g., 50) */
47
+ pityThreshold: number;
48
+ /** The tierId guaranteed when `currentPityCount + 1 >= pityThreshold` */
49
+ guaranteedTierId: string;
50
+ /** Tier IDs that reset the pity counter when hit naturally */
51
+ highTierIds: string[];
52
+ }
53
+ interface LootTableResolution {
54
+ selectedTier: LootTableTier;
55
+ pityTriggered: boolean;
56
+ nextPityCount: number;
57
+ }
58
+ /**
59
+ * Resolves a weighted loot table roll with an optional deterministic pity counter.
60
+ */
61
+ declare function resolveWeightedLootTable(tiers: readonly LootTableTier[], entropyValue: bigint | number | string, currentPityCount?: number, pityConfig?: PityConfig): LootTableResolution;
62
+ interface ArcadeMachineBankroll {
63
+ machineDid: string;
64
+ totalReserve: bigint;
65
+ lockedPendingPayouts: bigint;
66
+ maxSinglePayoutBps: number;
67
+ }
68
+ /**
69
+ * Verifies that an arcade/board-game machine's available reserve can cover `maxPossiblePayout`
70
+ * without violating `maxSinglePayoutBps` of its available bankroll.
71
+ */
72
+ declare function assertMachineBankrollSolvency(bankroll: ArcadeMachineBankroll, maxPossiblePayout: bigint | number | string): {
73
+ availableReserve: bigint;
74
+ maxAllowedSinglePayout: bigint;
75
+ };
76
+ interface ArcadeFourWaySplitConfig {
77
+ /** Basis points allocated to the machine's prize reserve bucket */
78
+ reserveBps: number;
79
+ /** Basis points allocated to the machine/game creator (royalty) */
80
+ creatorBps: number;
81
+ /** Basis points allocated to the machine NFT owner/investor pool */
82
+ ownerBps: number;
83
+ /** Basis points allocated to the island/venue host container where the machine is mounted */
84
+ hostBps: number;
85
+ }
86
+ interface ArcadeRtpMetrics {
87
+ playCount: bigint;
88
+ totalBet: bigint;
89
+ totalPayout: bigint;
90
+ realizedRtpBps: number;
91
+ }
92
+ interface ArcadePlaySettlementResult {
93
+ betAmount: bigint;
94
+ payoutAmount: bigint;
95
+ reserveCut: bigint;
96
+ creatorCut: bigint;
97
+ ownerCut: bigint;
98
+ hostCut: bigint;
99
+ nextReserveBalance: bigint;
100
+ metrics: ArcadeRtpMetrics;
101
+ }
102
+ /**
103
+ * Atomically settles a single play on a mounted Arcade / Board-Game Machine NFT:
104
+ * - Splits `betAmount` into `(reserveCut, creatorCut, ownerCut, hostCut)` with exact conservation
105
+ * (any integer rounding remainder is retained in `reserveCut` so prize solvency never leaks).
106
+ * - Verifies `currentReserve + reserveCut >= payoutAmount`.
107
+ * - Updates public verifiable RTP / PnL metrics (`playCount`, `totalBet`, `totalPayout`, `realizedRtpBps`).
108
+ */
109
+ declare function settleArcadeMachinePlay(params: {
110
+ betAmount: bigint | number | string;
111
+ payoutAmount: bigint | number | string;
112
+ currentReserve: bigint | number | string;
113
+ splitConfig: ArcadeFourWaySplitConfig;
114
+ maxPossiblePayout?: bigint | number | string;
115
+ previousMetrics?: ArcadeRtpMetrics;
116
+ }): ArcadePlaySettlementResult;
117
+ interface SplitRecipientEdge {
118
+ recipientDid: string;
119
+ shareBps: number;
120
+ }
121
+ type SplitGraphNodes = Record<string, readonly SplitRecipientEdge[]>;
122
+ /**
123
+ * Resolves a multi-level nested revenue-sharing DAG (e.g. an Island NFT co-owned by a Guild NFT
124
+ * and multiple partners, or a Game Machine NFT co-invested by a Syndicate NFT and angel investors).
125
+ *
126
+ * Enforces:
127
+ * - Acyclic graph invariant (`CYCLE_DETECTED` if `A -> B -> A` occurs)
128
+ * - Bounded recursion depth (`MAX_DEPTH_EXCEEDED` if nesting exceeds `maxDepth`)
129
+ * - Exact integer conservation at every internal node (rounding remainder is assigned to the first recipient edge)
130
+ * so that `sum(leafAllocations) === totalAmount` with zero dust loss.
131
+ */
132
+ declare function resolveHierarchicalSplitDag(params: {
133
+ rootNodeDid: string;
134
+ totalAmount: bigint | number | string;
135
+ nodes: SplitGraphNodes;
136
+ maxDepth?: number;
137
+ }): Record<string, bigint>;
138
+ interface ShareHolderPosition {
139
+ holderDid: string;
140
+ shares: bigint;
141
+ rewardDebt: bigint;
142
+ accruedUnclaimed: bigint;
143
+ totalClaimed: bigint;
144
+ }
145
+ /**
146
+ * O(1) Cumulative Dividend-Per-Share Pool (`accRewardPerShare`) for fractional/multi-investor
147
+ * Machine NFTs, Card Game Tables, and Co-Owned Islands.
148
+ *
149
+ * Supports:
150
+ * - O(1) revenue inflows (`distributeRevenue`) regardless of shareholder count
151
+ * - Ex-dividend checkpoint settlement on share transfers (`transferShares`) so sellers retain all
152
+ * dividends accrued prior to sale and buyers earn future cashflows from the transfer block onward
153
+ * - Exact unscaled fractional remainder preservation (`accruedScaled`) preventing Sybil share-splitting
154
+ * debt truncation attacks
155
+ * - On-chain DCF / NPV valuation (`estimateNpv`) combining trailing revenue cashflows and hard reserve floor
156
+ */
157
+ declare class RevenueSharePool {
158
+ readonly assetDid: string;
159
+ private totalShares;
160
+ private accRewardPerShare;
161
+ private carryRemainder;
162
+ private totalRevenueDistributed;
163
+ private readonly positions;
164
+ constructor(assetDid: string, initialHolders?: ReadonlyArray<{
165
+ holderDid: string;
166
+ shares: bigint | number | string;
167
+ }>);
168
+ getTotalShares(): bigint;
169
+ getAccRewardPerShare(): bigint;
170
+ getTotalRevenueDistributed(): bigint;
171
+ private toPublicPosition;
172
+ private settlePosition;
173
+ mintShares(holderDid: string, amount: bigint | number | string): ShareHolderPosition;
174
+ /**
175
+ * Distributes new cashflow into the equity pool in O(1) time.
176
+ */
177
+ distributeRevenue(inflowAmount: bigint | number | string): {
178
+ accRewardPerShare: bigint;
179
+ totalRevenueDistributed: bigint;
180
+ };
181
+ /**
182
+ * Returns total claimable dividends for `holderDid` without mutating state.
183
+ */
184
+ pendingDividend(holderDid: string): bigint;
185
+ /**
186
+ * Atomically settles both seller and buyer dividend checkpoints before transferring `shareAmount`
187
+ * so the seller can sell their equity token for NPV while retaining all prior unpaid dividends,
188
+ * and the buyer earns 100% of future cashflows on the transferred shares.
189
+ */
190
+ transferShares(fromDid: string, toDid: string, shareAmount: bigint | number | string): {
191
+ fromPosition: ShareHolderPosition;
192
+ toPosition: ShareHolderPosition;
193
+ };
194
+ /**
195
+ * Claims all accrued dividends for `holderDid`.
196
+ */
197
+ claimDividend(holderDid: string): bigint;
198
+ /**
199
+ * Computes deterministic on-chain NPV (Net Present Value) valuation for a given share count
200
+ * based on trailing/projected periodic net cashflow, discount rate in basis points, horizon periods,
201
+ * and optional hard reserve floor backing the asset.
202
+ */
203
+ estimateShareNpv(params: {
204
+ sharesToValue: bigint | number | string;
205
+ expectedPeriodRevenue: bigint | number | string;
206
+ discountRateBpsPerPeriod: number;
207
+ horizonPeriods: number;
208
+ reserveFloorTotal?: bigint | number | string;
209
+ }): {
210
+ totalPoolNpv: bigint;
211
+ shareNpv: bigint;
212
+ dcfPresentValueTotal: bigint;
213
+ reserveFloorTotal: bigint;
214
+ };
215
+ }
216
+ //#endregion
217
+ export { ArcadeFourWaySplitConfig, ArcadeMachineBankroll, ArcadePlaySettlementResult, ArcadeRtpMetrics, LootTableResolution, LootTableTier, PityConfig, ProvablyFairRollInput, ProvablyFairRollResult, RevenueSharePool, ShareHolderPosition, SplitGraphNodes, SplitRecipientEdge, assertMachineBankrollSolvency, deriveProvablyFairRoll, generateHashChain, resolveHierarchicalSplitDag, resolveWeightedLootTable, settleArcadeMachinePlay, verifyHashChainStep };