@sundaeswap/math 0.2.2 → 0.3.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.
@@ -0,0 +1,275 @@
1
+ import { AssetAmount, IAssetAmountMetadata } from "@sundaeswap/asset";
2
+ import { Fraction, type TFractionLike } from "@sundaeswap/fraction";
3
+
4
+ import * as ConstantProductPool from "./ConstantProductPool.js";
5
+
6
+ /**
7
+ * Holds the calculated outcome of a concentrated-liquidity swap. Mirrors
8
+ * {@link ConstantProductPool.TSwapOutcome} so it flows through the same generic
9
+ * swap-outcome consumers.
10
+ */
11
+ export type TSwapOutcome = {
12
+ input: bigint;
13
+ output: bigint;
14
+ lpFee: AssetAmount<IAssetAmountMetadata>;
15
+ nextInputReserve: bigint;
16
+ nextOutputReserve: bigint;
17
+ priceImpact: Fraction;
18
+ };
19
+
20
+ /** A sqrt-price bound from the CL config, as an exact rational `[num, den]`. */
21
+ export type TSqrtPrice = [bigint, bigint];
22
+
23
+ /**
24
+ * Concentrated liquidity is Sundae v4's single-range invariant. Unlike Uniswap
25
+ * v3 there are no per-position ranges or ticks: the whole pool shares ONE
26
+ * immutable price range `[sqrtPriceA, sqrtPriceB]` (a < b) set at creation, and
27
+ * LP is a single fungible token. Swaps run on *virtual* reserves that fold the
28
+ * pool's liquidity `L` (its total LP supply) into each side:
29
+ *
30
+ * VA = a·spbNum + L·spbDen
31
+ * VB = b·spaDen + L·spaNum
32
+ *
33
+ * where `a`/`b` are the raw assetA/assetB reserves. This is a direct port of the
34
+ * scooper's `cl_swap_result` (scooper-v2/src/sundaev4/swap_math.rs) and the
35
+ * on-chain `cl_check_swap` (sundae-v4/lib/modules/cl_check.ak) — those are the
36
+ * source of truth; keep this in lockstep with them.
37
+ */
38
+
39
+ const asFeeParts = (fee: TFractionLike): [bigint, bigint] => {
40
+ const f = Fraction.asFraction(fee);
41
+ if (f.lt(Fraction.ZERO) || f.gte(Fraction.ONE))
42
+ throw new Error("fee must be in [0, 1)");
43
+ return [BigInt(f.numerator), BigInt(f.denominator)];
44
+ };
45
+
46
+ /**
47
+ * The raw forward swap: given a pre-fee input `dx`, return the output amount.
48
+ * A→B and B→A use different virtual-reserve scalings (see `cl_check_swap`).
49
+ * All quantities are non-negative so integer division floors, matching chain.
50
+ */
51
+ const rawSwapOutput = (
52
+ dx: bigint,
53
+ aReserve: bigint,
54
+ bReserve: bigint,
55
+ totalLp: bigint,
56
+ spaNum: bigint,
57
+ spaDen: bigint,
58
+ spbNum: bigint,
59
+ spbDen: bigint,
60
+ feeNum: bigint,
61
+ feeDen: bigint,
62
+ isAInput: boolean,
63
+ ): bigint => {
64
+ const fee = (dx * feeNum) / feeDen;
65
+ const dxEff = dx - fee;
66
+ const va0 = aReserve * spbNum + totalLp * spbDen;
67
+ const vb0 = bReserve * spaDen + totalLp * spaNum;
68
+ if (isAInput) {
69
+ const dvaEff = dxEff * spbNum;
70
+ const denom = (va0 + dvaEff) * spaDen;
71
+ if (denom <= 0n) return 0n;
72
+ return (vb0 * dvaEff) / denom;
73
+ }
74
+ const dvbEff = dxEff * spaNum;
75
+ const denom = (vb0 + dvbEff) * spbNum;
76
+ if (denom <= 0n) return 0n;
77
+ return (va0 * dvbEff) / denom;
78
+ };
79
+
80
+ /**
81
+ * Calculate the swap outcome for a concentrated-liquidity pool.
82
+ *
83
+ * @param inputMetadata Metadata for the supplied (input) asset — used for the fee AssetAmount.
84
+ * @param input The pre-fee amount of the input asset being swapped.
85
+ * @param aReserve The pool's raw reserve of asset A.
86
+ * @param bReserve The pool's raw reserve of asset B.
87
+ * @param totalLp The pool's total LP supply (the virtual liquidity `L`).
88
+ * @param sqrtPriceA The lower sqrt-price bound `[num, den]` from the CL config.
89
+ * @param sqrtPriceB The upper sqrt-price bound `[num, den]` from the CL config.
90
+ * @param fee The liquidity-provider fee (plus protocol fee) as a fraction.
91
+ * @param isAInput True when asset A is the supplied asset (A→B swap).
92
+ * @returns The swap details in the shared {@link TSwapOutcome} shape.
93
+ */
94
+ export const getSwapOutput = (
95
+ inputMetadata: IAssetAmountMetadata,
96
+ input: bigint,
97
+ aReserve: bigint,
98
+ bReserve: bigint,
99
+ totalLp: bigint,
100
+ sqrtPriceA: TSqrtPrice,
101
+ sqrtPriceB: TSqrtPrice,
102
+ fee: TFractionLike,
103
+ isAInput: boolean,
104
+ ): TSwapOutcome => {
105
+ if (input <= 0n || aReserve <= 0n || bReserve <= 0n || totalLp <= 0n)
106
+ throw new Error("Input, reserves and liquidity must be positive");
107
+ const [spaNum, spaDen] = sqrtPriceA;
108
+ const [spbNum, spbDen] = sqrtPriceB;
109
+ if (spaNum <= 0n || spaDen <= 0n || spbNum <= 0n || spbDen <= 0n)
110
+ throw new Error("sqrt prices must be positive");
111
+ const [feeNum, feeDen] = asFeeParts(fee);
112
+
113
+ const inputReserve = isAInput ? aReserve : bReserve;
114
+ const outputReserve = isAInput ? bReserve : aReserve;
115
+
116
+ let output = rawSwapOutput(
117
+ input,
118
+ aReserve,
119
+ bReserve,
120
+ totalLp,
121
+ spaNum,
122
+ spaDen,
123
+ spbNum,
124
+ spbDen,
125
+ feeNum,
126
+ feeDen,
127
+ isAInput,
128
+ );
129
+ // Can't take more than the pool actually holds (virtual reserves can
130
+ // otherwise let the formula exceed the real reserve near the boundary).
131
+ if (output > outputReserve) output = outputReserve;
132
+
133
+ const inputLpFee = (input * feeNum) / feeDen;
134
+ const nextInputReserve = inputReserve + input;
135
+ const nextOutputReserve = outputReserve - output;
136
+
137
+ // Price impact vs the marginal (dx→0) rate. Marginal output-per-effective-
138
+ // input is vb0·spbNum/(va0·spaDen) for A→B (symmetric for B→A), so the ideal
139
+ // input-per-output is its reciprocal. Display-only.
140
+ const va0 = aReserve * spbNum + totalLp * spbDen;
141
+ const vb0 = bReserve * spaDen + totalLp * spaNum;
142
+ let priceImpact = Fraction.ZERO;
143
+ if (output > 0n) {
144
+ const idealPrice = isAInput
145
+ ? new Fraction(va0 * spaDen, vb0 * spbNum)
146
+ : new Fraction(vb0 * spbNum, va0 * spaDen);
147
+ const actualPrice = new Fraction(input - inputLpFee, output);
148
+ priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
149
+ }
150
+
151
+ return {
152
+ input,
153
+ output,
154
+ lpFee: new AssetAmount(inputLpFee, inputMetadata),
155
+ nextInputReserve,
156
+ nextOutputReserve,
157
+ priceImpact,
158
+ };
159
+ };
160
+
161
+ /**
162
+ * Calculate the minimal input required to receive a given output — the inverse
163
+ * of {@link getSwapOutput}. The forward swap is linear-fractional in the
164
+ * effective input, so it inverts in closed form; a short correction loop
165
+ * absorbs the fee floor and integer rounding so the result is the exact minimal
166
+ * input whose forward swap yields at least `output`.
167
+ */
168
+ export const getSwapInput = (
169
+ inputMetadata: IAssetAmountMetadata,
170
+ output: bigint,
171
+ aReserve: bigint,
172
+ bReserve: bigint,
173
+ totalLp: bigint,
174
+ sqrtPriceA: TSqrtPrice,
175
+ sqrtPriceB: TSqrtPrice,
176
+ fee: TFractionLike,
177
+ isAInput: boolean,
178
+ ): TSwapOutcome => {
179
+ if (output <= 0n || aReserve <= 0n || bReserve <= 0n || totalLp <= 0n)
180
+ throw new Error("Output, reserves and liquidity must be positive");
181
+ const [spaNum, spaDen] = sqrtPriceA;
182
+ const [spbNum, spbDen] = sqrtPriceB;
183
+ if (spaNum <= 0n || spaDen <= 0n || spbNum <= 0n || spbDen <= 0n)
184
+ throw new Error("sqrt prices must be positive");
185
+ const outputReserve = isAInput ? bReserve : aReserve;
186
+ if (output > outputReserve)
187
+ throw new Error("Output must not exceed the output reserve");
188
+
189
+ const [feeNum, feeDen] = asFeeParts(fee);
190
+ const feeDiff = feeDen - feeNum;
191
+
192
+ const va0 = aReserve * spbNum + totalLp * spbDen;
193
+ const vb0 = bReserve * spaDen + totalLp * spaNum;
194
+
195
+ const ceilDiv = (n: bigint, d: bigint) => (n + d - 1n) / d;
196
+
197
+ // Closed-form minimal effective input, then gross up for the fee floor.
198
+ let effMin: bigint;
199
+ if (isAInput) {
200
+ // dvaEff ≥ output·spaDen·va0 / (vb0 − output·spaDen)
201
+ const denom = vb0 - output * spaDen;
202
+ if (denom <= 0n)
203
+ throw new Error("Output not reachable within the pool's range");
204
+ const dvaEffMin = ceilDiv(output * spaDen * va0, denom);
205
+ effMin = ceilDiv(dvaEffMin, spbNum);
206
+ } else {
207
+ const denom = va0 - output * spbNum;
208
+ if (denom <= 0n)
209
+ throw new Error("Output not reachable within the pool's range");
210
+ const dvbEffMin = ceilDiv(output * spbNum * vb0, denom);
211
+ effMin = ceilDiv(dvbEffMin, spaNum);
212
+ }
213
+ let input = feeDiff > 0n ? ceilDiv(effMin * feeDen, feeDiff) : effMin;
214
+
215
+ // Correct for floor interactions: nudge up until the forward swap clears the
216
+ // target, then trim any over-shoot. Bounded — a couple of iterations at most.
217
+ const fwd = (dx: bigint) =>
218
+ rawSwapOutput(
219
+ dx,
220
+ aReserve,
221
+ bReserve,
222
+ totalLp,
223
+ spaNum,
224
+ spaDen,
225
+ spbNum,
226
+ spbDen,
227
+ feeNum,
228
+ feeDen,
229
+ isAInput,
230
+ );
231
+ let guard = 0;
232
+ while (fwd(input) < output && guard++ < 64) input += 1n;
233
+ while (input > 1n && fwd(input - 1n) >= output) input -= 1n;
234
+
235
+ const inputLpFee = (input * feeNum) / feeDen;
236
+ const inputReserve = isAInput ? aReserve : bReserve;
237
+ const nextInputReserve = inputReserve + input;
238
+ const nextOutputReserve = outputReserve - output;
239
+
240
+ let priceImpact = Fraction.ZERO;
241
+ if (output > 0n) {
242
+ const idealPrice = isAInput
243
+ ? new Fraction(va0 * spaDen, vb0 * spbNum)
244
+ : new Fraction(vb0 * spbNum, va0 * spaDen);
245
+ const actualPrice = new Fraction(input - inputLpFee, output);
246
+ priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
247
+ }
248
+
249
+ return {
250
+ input,
251
+ output,
252
+ lpFee: new AssetAmount(inputLpFee, inputMetadata),
253
+ nextInputReserve,
254
+ nextOutputReserve,
255
+ priceImpact,
256
+ };
257
+ };
258
+
259
+ /**
260
+ * Deposit LP estimate for a concentrated-liquidity pool. CL deposits reuse the
261
+ * constant-product *proportional* pinning: minting by the scarcest offered
262
+ * asset and ceil-pinning the reserve deltas gives, per asset,
263
+ * `a1·L0 ≥ a0·L1` and `b1·L0 ≥ b0·L1` — and those two bounds multiply to
264
+ * exactly the on-chain CL non-swap invariant `va1·vb1·L0² ≥ va0·vb0·L1²`
265
+ * (`cl_check.ak`). So the proportional deposit is always chain-valid; excess of
266
+ * either asset is refunded via aChange/bChange. This mirrors the scooper's
267
+ * `resolve_cl_deposit` (which likewise reuses the CP pinning).
268
+ */
269
+ export const calculateLiquidity = (
270
+ a: bigint,
271
+ b: bigint,
272
+ aReserve: bigint,
273
+ bReserve: bigint,
274
+ totalLp: bigint,
275
+ ) => ConstantProductPool.calculateLiquidity(a, b, aReserve, bReserve, totalLp);
@@ -0,0 +1,371 @@
1
+ import { AssetAmount, IAssetAmountMetadata } from "@sundaeswap/asset";
2
+ import { Fraction, type TFractionLike } from "@sundaeswap/fraction";
3
+ import { SharedPoolMath } from "./index.js";
4
+
5
+ /**
6
+ * Holds the calculated outcome of a constant-sum swap. Mirrors
7
+ * {@link ConstantProductPool.TSwapOutcome} so both can flow through the same
8
+ * generic swap-outcome consumers.
9
+ */
10
+ export type TSwapOutcome = {
11
+ input: bigint;
12
+ output: bigint;
13
+ lpFee: AssetAmount<IAssetAmountMetadata>;
14
+ nextInputReserve: bigint;
15
+ nextOutputReserve: bigint;
16
+ priceImpact: Fraction;
17
+ };
18
+
19
+ /**
20
+ * Calculate the swap outcome for a constant-sum (fixed-price) pool — the
21
+ * invariant used by Sundae v4 stable/pegged pools. Unlike constant product,
22
+ * the exchange rate is fixed by the pool's per-asset `prices`: the input is
23
+ * converted to "value" at `priceIn`, the fee is taken off that value, and the
24
+ * remainder is converted to the output asset at `priceOut`. The result is
25
+ * capped at the output reserve (you can't take more than the pool holds).
26
+ *
27
+ * Matches the scooper's `cs_swap_result`:
28
+ * output = floor((input·priceIn − floor(input·priceIn·fee)) / priceOut)
29
+ *
30
+ * @param inputMetadata Metadata for the supplied (input) asset — used for the fee AssetAmount.
31
+ * @param input The amount of the input asset being swapped.
32
+ * @param inputReserve The pool's reserve of the input asset.
33
+ * @param outputReserve The pool's reserve of the output asset.
34
+ * @param priceIn The pool's price for the input asset (from the constant-sum config).
35
+ * @param priceOut The pool's price for the output asset.
36
+ * @param fee The liquidity-provider fee (plus protocol fee) as a fraction.
37
+ * @param roundOutputUp When true, round the output up instead of flooring.
38
+ * @returns The swap details in the shared {@link TSwapOutcome} shape.
39
+ */
40
+ export const getSwapOutput = (
41
+ inputMetadata: IAssetAmountMetadata,
42
+ input: bigint,
43
+ inputReserve: bigint,
44
+ outputReserve: bigint,
45
+ priceIn: bigint,
46
+ priceOut: bigint,
47
+ fee: TFractionLike,
48
+ roundOutputUp?: boolean,
49
+ ): TSwapOutcome => {
50
+ if (input <= 0n || inputReserve <= 0n || outputReserve <= 0n)
51
+ throw new Error("Input and reserves must be positive");
52
+ if (priceIn <= 0n || priceOut <= 0n)
53
+ throw new Error("Prices must be positive");
54
+
55
+ const feeFraction = Fraction.asFraction(fee);
56
+ if (feeFraction.lt(Fraction.ZERO) || feeFraction.gt(Fraction.ONE))
57
+ throw new Error("fee must be between 0 and 1");
58
+
59
+ const inputValue = input * priceIn;
60
+ const feeValue = new Fraction(
61
+ inputValue * BigInt(feeFraction.numerator),
62
+ BigInt(feeFraction.denominator),
63
+ ).quotient;
64
+ const outputValue = inputValue - feeValue;
65
+
66
+ let output = roundOutputUp
67
+ ? (outputValue + priceOut - 1n) / priceOut
68
+ : outputValue / priceOut;
69
+
70
+ // Can't take more than the pool holds.
71
+ if (output > outputReserve) {
72
+ output = outputReserve;
73
+ }
74
+
75
+ // LP fee expressed in input-asset units (value scales linearly with input,
76
+ // so the input-denominated fee is input·feeRate) — matching ConstantProductPool.
77
+ const inputLpFee = new Fraction(
78
+ input * BigInt(feeFraction.numerator),
79
+ BigInt(feeFraction.denominator),
80
+ ).quotient;
81
+
82
+ const nextInputReserve = inputReserve + input;
83
+ const nextOutputReserve = outputReserve - output;
84
+
85
+ // Price impact vs the pool's par price (priceOut/priceIn input-per-output);
86
+ // ~0 for a constant-sum pool aside from the fee. See ConstantProductPool.
87
+ let priceImpact = Fraction.ZERO;
88
+ if (output > 0n) {
89
+ const amountInLessFee = input - inputLpFee;
90
+ const idealPrice = new Fraction(priceOut, priceIn);
91
+ const actualPrice = new Fraction(amountInLessFee, output);
92
+ priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
93
+ }
94
+
95
+ return {
96
+ input,
97
+ output,
98
+ lpFee: new AssetAmount(inputLpFee, inputMetadata),
99
+ nextInputReserve,
100
+ nextOutputReserve,
101
+ priceImpact,
102
+ };
103
+ };
104
+
105
+ /**
106
+ * Calculate the minimal input required to receive a given output from a
107
+ * constant-sum pool — the exact inverse of {@link getSwapOutput}.
108
+ *
109
+ * The forward math floors the fee off the input value, which makes the
110
+ * post-fee value `ceil(input·priceIn·(1−fee))`; inverting that ceiling gives
111
+ * the smallest input whose forward swap yields at least `output`.
112
+ *
113
+ * Unlike constant product there is no asymptote, so an output equal to the
114
+ * full output reserve is attainable (the pool can be drained at par).
115
+ *
116
+ * @param inputMetadata Metadata for the supplied (input) asset — used for the fee AssetAmount.
117
+ * @param output The desired amount of the output asset.
118
+ * @param inputReserve The pool's reserve of the input asset.
119
+ * @param outputReserve The pool's reserve of the output asset.
120
+ * @param priceIn The pool's price for the input asset (from the constant-sum config).
121
+ * @param priceOut The pool's price for the output asset.
122
+ * @param fee The liquidity-provider fee (plus protocol fee) as a fraction.
123
+ * @returns The swap details in the shared {@link TSwapOutcome} shape.
124
+ */
125
+ export const getSwapInput = (
126
+ inputMetadata: IAssetAmountMetadata,
127
+ output: bigint,
128
+ inputReserve: bigint,
129
+ outputReserve: bigint,
130
+ priceIn: bigint,
131
+ priceOut: bigint,
132
+ fee: TFractionLike,
133
+ ): TSwapOutcome => {
134
+ if (output <= 0n || inputReserve <= 0n || outputReserve <= 0n)
135
+ throw new Error("Output and reserves must be positive");
136
+ if (priceIn <= 0n || priceOut <= 0n)
137
+ throw new Error("Prices must be positive");
138
+ if (output > outputReserve)
139
+ throw new Error("Output must not exceed the output reserve");
140
+
141
+ const feeFraction = Fraction.asFraction(fee);
142
+ if (feeFraction.lt(Fraction.ZERO) || feeFraction.gte(Fraction.ONE))
143
+ throw new Error("fee must be [0,1)");
144
+
145
+ const feeNum = BigInt(feeFraction.numerator);
146
+ const feeDen = BigInt(feeFraction.denominator);
147
+ const feeDiff = feeDen - feeNum;
148
+
149
+ // Forward: outputValue = ceil(input·priceIn·feeDiff/feeDen), and the swap
150
+ // yields ≥ output iff outputValue ≥ output·priceOut. ceil(x/d) ≥ T for
151
+ // integer x iff x ≥ d·(T−1)+1, so the minimal input is the ceiling of
152
+ // (feeDen·(output·priceOut − 1) + 1) / (feeDiff·priceIn).
153
+ const targetValue = output * priceOut;
154
+ const numerator = feeDen * (targetValue - 1n) + 1n;
155
+ const denominator = feeDiff * priceIn;
156
+ const input = (numerator + denominator - 1n) / denominator;
157
+
158
+ const inputLpFee = new Fraction(input * feeNum, feeDen).quotient;
159
+ const nextInputReserve = inputReserve + input;
160
+ const nextOutputReserve = outputReserve - output;
161
+
162
+ // Same par-price impact definition as getSwapOutput.
163
+ const amountInLessFee = input - inputLpFee;
164
+ const idealPrice = new Fraction(priceOut, priceIn);
165
+ const actualPrice = new Fraction(amountInLessFee, output);
166
+ const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
167
+
168
+ return {
169
+ input,
170
+ output,
171
+ lpFee: new AssetAmount(inputLpFee, inputMetadata),
172
+ nextInputReserve,
173
+ nextOutputReserve,
174
+ priceImpact,
175
+ };
176
+ };
177
+
178
+ /**
179
+ * Calculate the deposit parameters for a 2-asset constant-sum pool via the
180
+ * TARGET-PINNED rule the deployed validator enforces (see
181
+ * {@link calculatePinnedDeposit}): the mint is capped by the scarcest offered
182
+ * asset, both assets must be offered, and anything above the pinned deltas is
183
+ * refunded via aChange/bChange.
184
+ *
185
+ * @param {bigint} a - The amount of token A to deposit.
186
+ * @param {bigint} b - The amount of token B to deposit.
187
+ * @param {bigint} aReserve - The current reserve of token A in the pool.
188
+ * @param {bigint} bReserve - The current reserve of token B in the pool.
189
+ * @param {bigint} totalLp - The total lp tokens for the pool before the deposit.
190
+ * @param {bigint} priceA - The pool's price for token A (from the constant-sum config).
191
+ * @param {bigint} priceB - The pool's price for token B.
192
+ * @throws {Error} If the pool has no value or minted lp.
193
+ * @throws {Error} If both deposit amounts are zero, or either is negative.
194
+ * @throws {Error} If either price is non-positive.
195
+ */
196
+ export const calculateLiquidity = (
197
+ a: bigint,
198
+ b: bigint,
199
+ aReserve: bigint,
200
+ bReserve: bigint,
201
+ totalLp: bigint,
202
+ priceA: bigint,
203
+ priceB: bigint,
204
+ ) => {
205
+ // Target-pinned (what the deployed validator accepts): mint by the
206
+ // scarcest offered asset; anything above the pinned deltas is refunded
207
+ // (aChange/bChange).
208
+ const { deltas, generatedLp, nextTotalLp, shareAfterDeposit } =
209
+ calculatePinnedDeposit(
210
+ [a, b],
211
+ [aReserve, bReserve],
212
+ [priceA, priceB],
213
+ totalLp,
214
+ );
215
+
216
+ return {
217
+ nextTotalLp,
218
+ generatedLp,
219
+ shareAfterDeposit,
220
+ aChange: a - deltas[0],
221
+ bChange: b - deltas[1],
222
+ actualDepositedA: deltas[0],
223
+ actualDepositedB: deltas[1],
224
+ };
225
+ };
226
+
227
+ /**
228
+ * The N-asset form of {@link calculateLiquidity}, mirroring the v4 contract's
229
+ * `compute_deposit_n` exactly: a deposit of any mix of the pool's assets is
230
+ * valued at the fixed prices against the value of ALL reserves —
231
+ *
232
+ * generatedLp = Σ(amount_i·price_i) · totalLp / Σ(reserve_i·price_i)
233
+ *
234
+ * The three arrays must be aligned to the pool's canonical asset order (the
235
+ * API's `assets`/`quantities`/`prices`). Estimating an N-asset pool's deposit
236
+ * from just two of its reserves overstates the minted LP — the denominator is
237
+ * the whole pool's value — which is exactly the mistake this exists to
238
+ * prevent.
239
+ */
240
+ /**
241
+ * The target-pinned deposit — what the deployed CS validator (cs_check tag 6)
242
+ * actually accepts, and what the scooper builds. Asymmetric deposits are
243
+ * disallowed on-chain: the fill declares a value delta `t` and every asset's
244
+ * contribution is ceil-pinned to `ceil(r_i·t/V_b)`, with total LP
245
+ * floor-pinned to `floor(lp_b·(V_b+t)/V_b)`. Given what the user offers, the
246
+ * largest fillable t is capped by the SCARCEST asset —
247
+ * `t = min_i floor(offered_i·V_b/r_i)` — and anything above the pinned
248
+ * deltas is returned as surplus. Every pool asset must be offered (> 0) or
249
+ * t is zero and the deposit can never fill.
250
+ *
251
+ * Contrast with `calculateDepositN`, which is the plain value formula:
252
+ * it matches the pin only for exactly proportional offers and OVERSTATES the
253
+ * mint otherwise — using it for `minReceived` makes non-proportional orders
254
+ * unfillable.
255
+ */
256
+ export const calculatePinnedDeposit = (
257
+ offered: bigint[],
258
+ reserves: bigint[],
259
+ prices: bigint[],
260
+ totalLp: bigint,
261
+ ): {
262
+ targetDeltaV: bigint;
263
+ deltas: bigint[];
264
+ generatedLp: bigint;
265
+ nextTotalLp: bigint;
266
+ shareAfterDeposit: Fraction;
267
+ } => {
268
+ if (offered.length !== reserves.length || reserves.length !== prices.length)
269
+ throw new Error("offered, reserves and prices must be aligned");
270
+ if (prices.some((p) => p <= 0n)) throw new Error("Prices must be positive");
271
+ if (totalLp <= 0n) throw new Error("Not enough pool liquidity");
272
+
273
+ let vB = 0n;
274
+ for (let i = 0; i < reserves.length; i++) {
275
+ vB += reserves[i] * prices[i];
276
+ }
277
+ if (vB <= 0n) throw new Error("Pool value is zero");
278
+
279
+ let t: bigint | undefined;
280
+ for (let i = 0; i < offered.length; i++) {
281
+ if (reserves[i] === 0n) continue;
282
+ const cap = (offered[i] * vB) / reserves[i];
283
+ t = t === undefined || cap < t ? cap : t;
284
+ }
285
+ if (t === undefined || t <= 0n) {
286
+ throw new Error(
287
+ "A constant-sum deposit must offer every pool asset in proportion (asymmetric deposits are disallowed on-chain)",
288
+ );
289
+ }
290
+
291
+ const deltas = reserves.map((r) => (r * t! + vB - 1n) / vB); // ceil
292
+ const nextTotalLp = (totalLp * (vB + t)) / vB; // floor
293
+ const generatedLp = nextTotalLp - totalLp;
294
+ if (generatedLp <= 0n) throw new Error("Deposit mints zero LP");
295
+
296
+ return {
297
+ targetDeltaV: t,
298
+ deltas,
299
+ generatedLp,
300
+ nextTotalLp,
301
+ shareAfterDeposit: SharedPoolMath.getShare(generatedLp, nextTotalLp),
302
+ };
303
+ };
304
+
305
+ /**
306
+ * The per-asset amounts a pinned deposit needs when the user anchors on one
307
+ * asset's amount: t from the anchor (`floor(anchor·V_b/r_anchor)`), every
308
+ * delta ceil-pinned to it. Drives proportional auto-fill in deposit forms.
309
+ */
310
+ export const pinnedDepositFromAnchor = (
311
+ anchorIndex: number,
312
+ anchorAmount: bigint,
313
+ reserves: bigint[],
314
+ prices: bigint[],
315
+ ): bigint[] => {
316
+ if (reserves.length !== prices.length)
317
+ throw new Error("reserves and prices must be aligned");
318
+ if (
319
+ anchorIndex < 0 ||
320
+ anchorIndex >= reserves.length ||
321
+ reserves[anchorIndex] <= 0n
322
+ )
323
+ throw new Error("anchor asset has no reserve");
324
+ if (anchorAmount <= 0n) return reserves.map(() => 0n);
325
+
326
+ let vB = 0n;
327
+ for (let i = 0; i < reserves.length; i++) {
328
+ vB += reserves[i] * prices[i];
329
+ }
330
+ if (vB <= 0n) throw new Error("Pool value is zero");
331
+
332
+ const t = (anchorAmount * vB) / reserves[anchorIndex];
333
+ return reserves.map((r, i) =>
334
+ i === anchorIndex ? anchorAmount : (r * t + vB - 1n) / vB,
335
+ );
336
+ };
337
+
338
+ export const calculateDepositN = (
339
+ amounts: bigint[],
340
+ reserves: bigint[],
341
+ prices: bigint[],
342
+ totalLp: bigint,
343
+ ) => {
344
+ if (amounts.length !== reserves.length || reserves.length !== prices.length)
345
+ throw new Error("amounts, reserves and prices must be aligned");
346
+ if (prices.some((p) => p <= 0n)) throw new Error("Prices must be positive");
347
+ // Zeros in a MIX are fine — offering a subset is the point of the N-asset
348
+ // form. What's rejected is a negative amount, or offering nothing at all.
349
+ if (amounts.some((a) => a < 0n) || amounts.every((a) => a === 0n))
350
+ throw new Error(
351
+ "Deposit amounts must be non-negative, with at least one positive",
352
+ );
353
+
354
+ let totalValue = 0n;
355
+ let depositValue = 0n;
356
+ for (let i = 0; i < amounts.length; i++) {
357
+ totalValue += reserves[i] * prices[i];
358
+ depositValue += amounts[i] * prices[i];
359
+ }
360
+ if (totalValue <= 0n || totalLp <= 0n)
361
+ throw new Error("Not enough pool liquidity");
362
+
363
+ const generatedLp = (depositValue * totalLp) / totalValue;
364
+ const nextTotalLp = totalLp + generatedLp;
365
+
366
+ return {
367
+ nextTotalLp,
368
+ generatedLp,
369
+ shareAfterDeposit: SharedPoolMath.getShare(generatedLp, nextTotalLp),
370
+ };
371
+ };