@sundaeswap/math 0.2.2 → 0.4.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 (33) hide show
  1. package/dist/cjs/PoolMath/ConcentratedLiquidityPool.js +214 -0
  2. package/dist/cjs/PoolMath/ConcentratedLiquidityPool.js.map +1 -0
  3. package/dist/cjs/PoolMath/ConstantSumPool.js +284 -0
  4. package/dist/cjs/PoolMath/ConstantSumPool.js.map +1 -0
  5. package/dist/cjs/PoolMath/V4StableswapPool.js +529 -0
  6. package/dist/cjs/PoolMath/V4StableswapPool.js.map +1 -0
  7. package/dist/cjs/PoolMath/index.js +7 -1
  8. package/dist/cjs/PoolMath/index.js.map +1 -1
  9. package/dist/esm/PoolMath/ConcentratedLiquidityPool.js +181 -0
  10. package/dist/esm/PoolMath/ConcentratedLiquidityPool.js.map +1 -0
  11. package/dist/esm/PoolMath/ConstantSumPool.js +266 -0
  12. package/dist/esm/PoolMath/ConstantSumPool.js.map +1 -0
  13. package/dist/esm/PoolMath/V4StableswapPool.js +495 -0
  14. package/dist/esm/PoolMath/V4StableswapPool.js.map +1 -0
  15. package/dist/esm/PoolMath/index.js +3 -0
  16. package/dist/esm/PoolMath/index.js.map +1 -1
  17. package/dist/types/PoolMath/ConcentratedLiquidityPool.d.ts +60 -0
  18. package/dist/types/PoolMath/ConcentratedLiquidityPool.d.ts.map +1 -0
  19. package/dist/types/PoolMath/ConstantSumPool.d.ts +133 -0
  20. package/dist/types/PoolMath/ConstantSumPool.d.ts.map +1 -0
  21. package/dist/types/PoolMath/V4StableswapPool.d.ts +221 -0
  22. package/dist/types/PoolMath/V4StableswapPool.d.ts.map +1 -0
  23. package/dist/types/PoolMath/index.d.ts +3 -0
  24. package/dist/types/PoolMath/index.d.ts.map +1 -1
  25. package/dist/types/tsconfig.build.tsbuildinfo +1 -1
  26. package/package.json +2 -2
  27. package/src/PoolMath/ConcentratedLiquidityPool.ts +275 -0
  28. package/src/PoolMath/ConstantSumPool.ts +371 -0
  29. package/src/PoolMath/V4StableswapPool.ts +638 -0
  30. package/src/PoolMath/__tests__/ConcentratedLiquidityPool.test.ts +225 -0
  31. package/src/PoolMath/__tests__/ConstantSumPool.test.ts +322 -0
  32. package/src/PoolMath/__tests__/V4StableswapPool.test.ts +688 -0
  33. package/src/PoolMath/index.ts +3 -0
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/PoolMath/index.ts"],"sourcesContent":["export * as ConstantProductPool from \"./ConstantProductPool.js\";\nexport * as StableSwapsPool from \"./StableSwapsPool.js\";\nexport * as SharedPoolMath from \"./SharedPoolMath.js\";\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/PoolMath/index.ts"],"sourcesContent":["export * as ConcentratedLiquidityPool from \"./ConcentratedLiquidityPool.js\";\nexport * as ConstantProductPool from \"./ConstantProductPool.js\";\nexport * as ConstantSumPool from \"./ConstantSumPool.js\";\nexport * as StableSwapsPool from \"./StableSwapsPool.js\";\nexport * as V4StableswapPool from \"./V4StableswapPool.js\";\nexport * as SharedPoolMath from \"./SharedPoolMath.js\";\n"],"mappings":"","ignoreList":[]}
@@ -0,0 +1,181 @@
1
+ import { AssetAmount } from "@sundaeswap/asset";
2
+ import { Fraction } from "@sundaeswap/fraction";
3
+ import * as ConstantProductPool from "./ConstantProductPool.js";
4
+
5
+ /**
6
+ * Holds the calculated outcome of a concentrated-liquidity swap. Mirrors
7
+ * {@link ConstantProductPool.TSwapOutcome} so it flows through the same generic
8
+ * swap-outcome consumers.
9
+ */
10
+
11
+ /** A sqrt-price bound from the CL config, as an exact rational `[num, den]`. */
12
+
13
+ /**
14
+ * Concentrated liquidity is Sundae v4's single-range invariant. Unlike Uniswap
15
+ * v3 there are no per-position ranges or ticks: the whole pool shares ONE
16
+ * immutable price range `[sqrtPriceA, sqrtPriceB]` (a < b) set at creation, and
17
+ * LP is a single fungible token. Swaps run on *virtual* reserves that fold the
18
+ * pool's liquidity `L` (its total LP supply) into each side:
19
+ *
20
+ * VA = a·spbNum + L·spbDen
21
+ * VB = b·spaDen + L·spaNum
22
+ *
23
+ * where `a`/`b` are the raw assetA/assetB reserves. This is a direct port of the
24
+ * scooper's `cl_swap_result` (scooper-v2/src/sundaev4/swap_math.rs) and the
25
+ * on-chain `cl_check_swap` (sundae-v4/lib/modules/cl_check.ak) — those are the
26
+ * source of truth; keep this in lockstep with them.
27
+ */
28
+
29
+ const asFeeParts = fee => {
30
+ const f = Fraction.asFraction(fee);
31
+ if (f.lt(Fraction.ZERO) || f.gte(Fraction.ONE)) throw new Error("fee must be in [0, 1)");
32
+ return [BigInt(f.numerator), BigInt(f.denominator)];
33
+ };
34
+
35
+ /**
36
+ * The raw forward swap: given a pre-fee input `dx`, return the output amount.
37
+ * A→B and B→A use different virtual-reserve scalings (see `cl_check_swap`).
38
+ * All quantities are non-negative so integer division floors, matching chain.
39
+ */
40
+ const rawSwapOutput = (dx, aReserve, bReserve, totalLp, spaNum, spaDen, spbNum, spbDen, feeNum, feeDen, isAInput) => {
41
+ const fee = dx * feeNum / feeDen;
42
+ const dxEff = dx - fee;
43
+ const va0 = aReserve * spbNum + totalLp * spbDen;
44
+ const vb0 = bReserve * spaDen + totalLp * spaNum;
45
+ if (isAInput) {
46
+ const dvaEff = dxEff * spbNum;
47
+ const denom = (va0 + dvaEff) * spaDen;
48
+ if (denom <= 0n) return 0n;
49
+ return vb0 * dvaEff / denom;
50
+ }
51
+ const dvbEff = dxEff * spaNum;
52
+ const denom = (vb0 + dvbEff) * spbNum;
53
+ if (denom <= 0n) return 0n;
54
+ return va0 * dvbEff / denom;
55
+ };
56
+
57
+ /**
58
+ * Calculate the swap outcome for a concentrated-liquidity pool.
59
+ *
60
+ * @param inputMetadata Metadata for the supplied (input) asset — used for the fee AssetAmount.
61
+ * @param input The pre-fee amount of the input asset being swapped.
62
+ * @param aReserve The pool's raw reserve of asset A.
63
+ * @param bReserve The pool's raw reserve of asset B.
64
+ * @param totalLp The pool's total LP supply (the virtual liquidity `L`).
65
+ * @param sqrtPriceA The lower sqrt-price bound `[num, den]` from the CL config.
66
+ * @param sqrtPriceB The upper sqrt-price bound `[num, den]` from the CL config.
67
+ * @param fee The liquidity-provider fee (plus protocol fee) as a fraction.
68
+ * @param isAInput True when asset A is the supplied asset (A→B swap).
69
+ * @returns The swap details in the shared {@link TSwapOutcome} shape.
70
+ */
71
+ export const getSwapOutput = (inputMetadata, input, aReserve, bReserve, totalLp, sqrtPriceA, sqrtPriceB, fee, isAInput) => {
72
+ if (input <= 0n || aReserve <= 0n || bReserve <= 0n || totalLp <= 0n) throw new Error("Input, reserves and liquidity must be positive");
73
+ const [spaNum, spaDen] = sqrtPriceA;
74
+ const [spbNum, spbDen] = sqrtPriceB;
75
+ if (spaNum <= 0n || spaDen <= 0n || spbNum <= 0n || spbDen <= 0n) throw new Error("sqrt prices must be positive");
76
+ const [feeNum, feeDen] = asFeeParts(fee);
77
+ const inputReserve = isAInput ? aReserve : bReserve;
78
+ const outputReserve = isAInput ? bReserve : aReserve;
79
+ let output = rawSwapOutput(input, aReserve, bReserve, totalLp, spaNum, spaDen, spbNum, spbDen, feeNum, feeDen, isAInput);
80
+ // Can't take more than the pool actually holds (virtual reserves can
81
+ // otherwise let the formula exceed the real reserve near the boundary).
82
+ if (output > outputReserve) output = outputReserve;
83
+ const inputLpFee = input * feeNum / feeDen;
84
+ const nextInputReserve = inputReserve + input;
85
+ const nextOutputReserve = outputReserve - output;
86
+
87
+ // Price impact vs the marginal (dx→0) rate. Marginal output-per-effective-
88
+ // input is vb0·spbNum/(va0·spaDen) for A→B (symmetric for B→A), so the ideal
89
+ // input-per-output is its reciprocal. Display-only.
90
+ const va0 = aReserve * spbNum + totalLp * spbDen;
91
+ const vb0 = bReserve * spaDen + totalLp * spaNum;
92
+ let priceImpact = Fraction.ZERO;
93
+ if (output > 0n) {
94
+ const idealPrice = isAInput ? new Fraction(va0 * spaDen, vb0 * spbNum) : new Fraction(vb0 * spbNum, va0 * spaDen);
95
+ const actualPrice = new Fraction(input - inputLpFee, output);
96
+ priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
97
+ }
98
+ return {
99
+ input,
100
+ output,
101
+ lpFee: new AssetAmount(inputLpFee, inputMetadata),
102
+ nextInputReserve,
103
+ nextOutputReserve,
104
+ priceImpact
105
+ };
106
+ };
107
+
108
+ /**
109
+ * Calculate the minimal input required to receive a given output — the inverse
110
+ * of {@link getSwapOutput}. The forward swap is linear-fractional in the
111
+ * effective input, so it inverts in closed form; a short correction loop
112
+ * absorbs the fee floor and integer rounding so the result is the exact minimal
113
+ * input whose forward swap yields at least `output`.
114
+ */
115
+ export const getSwapInput = (inputMetadata, output, aReserve, bReserve, totalLp, sqrtPriceA, sqrtPriceB, fee, isAInput) => {
116
+ if (output <= 0n || aReserve <= 0n || bReserve <= 0n || totalLp <= 0n) throw new Error("Output, reserves and liquidity must be positive");
117
+ const [spaNum, spaDen] = sqrtPriceA;
118
+ const [spbNum, spbDen] = sqrtPriceB;
119
+ if (spaNum <= 0n || spaDen <= 0n || spbNum <= 0n || spbDen <= 0n) throw new Error("sqrt prices must be positive");
120
+ const outputReserve = isAInput ? bReserve : aReserve;
121
+ if (output > outputReserve) throw new Error("Output must not exceed the output reserve");
122
+ const [feeNum, feeDen] = asFeeParts(fee);
123
+ const feeDiff = feeDen - feeNum;
124
+ const va0 = aReserve * spbNum + totalLp * spbDen;
125
+ const vb0 = bReserve * spaDen + totalLp * spaNum;
126
+ const ceilDiv = (n, d) => (n + d - 1n) / d;
127
+
128
+ // Closed-form minimal effective input, then gross up for the fee floor.
129
+ let effMin;
130
+ if (isAInput) {
131
+ // dvaEff ≥ output·spaDen·va0 / (vb0 − output·spaDen)
132
+ const denom = vb0 - output * spaDen;
133
+ if (denom <= 0n) throw new Error("Output not reachable within the pool's range");
134
+ const dvaEffMin = ceilDiv(output * spaDen * va0, denom);
135
+ effMin = ceilDiv(dvaEffMin, spbNum);
136
+ } else {
137
+ const denom = va0 - output * spbNum;
138
+ if (denom <= 0n) throw new Error("Output not reachable within the pool's range");
139
+ const dvbEffMin = ceilDiv(output * spbNum * vb0, denom);
140
+ effMin = ceilDiv(dvbEffMin, spaNum);
141
+ }
142
+ let input = feeDiff > 0n ? ceilDiv(effMin * feeDen, feeDiff) : effMin;
143
+
144
+ // Correct for floor interactions: nudge up until the forward swap clears the
145
+ // target, then trim any over-shoot. Bounded — a couple of iterations at most.
146
+ const fwd = dx => rawSwapOutput(dx, aReserve, bReserve, totalLp, spaNum, spaDen, spbNum, spbDen, feeNum, feeDen, isAInput);
147
+ let guard = 0;
148
+ while (fwd(input) < output && guard++ < 64) input += 1n;
149
+ while (input > 1n && fwd(input - 1n) >= output) input -= 1n;
150
+ const inputLpFee = input * feeNum / feeDen;
151
+ const inputReserve = isAInput ? aReserve : bReserve;
152
+ const nextInputReserve = inputReserve + input;
153
+ const nextOutputReserve = outputReserve - output;
154
+ let priceImpact = Fraction.ZERO;
155
+ if (output > 0n) {
156
+ const idealPrice = isAInput ? new Fraction(va0 * spaDen, vb0 * spbNum) : new Fraction(vb0 * spbNum, va0 * spaDen);
157
+ const actualPrice = new Fraction(input - inputLpFee, output);
158
+ priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
159
+ }
160
+ return {
161
+ input,
162
+ output,
163
+ lpFee: new AssetAmount(inputLpFee, inputMetadata),
164
+ nextInputReserve,
165
+ nextOutputReserve,
166
+ priceImpact
167
+ };
168
+ };
169
+
170
+ /**
171
+ * Deposit LP estimate for a concentrated-liquidity pool. CL deposits reuse the
172
+ * constant-product *proportional* pinning: minting by the scarcest offered
173
+ * asset and ceil-pinning the reserve deltas gives, per asset,
174
+ * `a1·L0 ≥ a0·L1` and `b1·L0 ≥ b0·L1` — and those two bounds multiply to
175
+ * exactly the on-chain CL non-swap invariant `va1·vb1·L0² ≥ va0·vb0·L1²`
176
+ * (`cl_check.ak`). So the proportional deposit is always chain-valid; excess of
177
+ * either asset is refunded via aChange/bChange. This mirrors the scooper's
178
+ * `resolve_cl_deposit` (which likewise reuses the CP pinning).
179
+ */
180
+ export const calculateLiquidity = (a, b, aReserve, bReserve, totalLp) => ConstantProductPool.calculateLiquidity(a, b, aReserve, bReserve, totalLp);
181
+ //# sourceMappingURL=ConcentratedLiquidityPool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConcentratedLiquidityPool.js","names":["AssetAmount","Fraction","ConstantProductPool","asFeeParts","fee","f","asFraction","lt","ZERO","gte","ONE","Error","BigInt","numerator","denominator","rawSwapOutput","dx","aReserve","bReserve","totalLp","spaNum","spaDen","spbNum","spbDen","feeNum","feeDen","isAInput","dxEff","va0","vb0","dvaEff","denom","dvbEff","getSwapOutput","inputMetadata","input","sqrtPriceA","sqrtPriceB","inputReserve","outputReserve","output","inputLpFee","nextInputReserve","nextOutputReserve","priceImpact","idealPrice","actualPrice","subtract","divide","lpFee","getSwapInput","feeDiff","ceilDiv","n","d","effMin","dvaEffMin","dvbEffMin","fwd","guard","calculateLiquidity","a","b"],"sources":["../../../src/PoolMath/ConcentratedLiquidityPool.ts"],"sourcesContent":["import { AssetAmount, IAssetAmountMetadata } from \"@sundaeswap/asset\";\nimport { Fraction, type TFractionLike } from \"@sundaeswap/fraction\";\n\nimport * as ConstantProductPool from \"./ConstantProductPool.js\";\n\n/**\n * Holds the calculated outcome of a concentrated-liquidity swap. Mirrors\n * {@link ConstantProductPool.TSwapOutcome} so it flows through the same generic\n * swap-outcome consumers.\n */\nexport type TSwapOutcome = {\n input: bigint;\n output: bigint;\n lpFee: AssetAmount<IAssetAmountMetadata>;\n nextInputReserve: bigint;\n nextOutputReserve: bigint;\n priceImpact: Fraction;\n};\n\n/** A sqrt-price bound from the CL config, as an exact rational `[num, den]`. */\nexport type TSqrtPrice = [bigint, bigint];\n\n/**\n * Concentrated liquidity is Sundae v4's single-range invariant. Unlike Uniswap\n * v3 there are no per-position ranges or ticks: the whole pool shares ONE\n * immutable price range `[sqrtPriceA, sqrtPriceB]` (a < b) set at creation, and\n * LP is a single fungible token. Swaps run on *virtual* reserves that fold the\n * pool's liquidity `L` (its total LP supply) into each side:\n *\n * VA = a·spbNum + L·spbDen\n * VB = b·spaDen + L·spaNum\n *\n * where `a`/`b` are the raw assetA/assetB reserves. This is a direct port of the\n * scooper's `cl_swap_result` (scooper-v2/src/sundaev4/swap_math.rs) and the\n * on-chain `cl_check_swap` (sundae-v4/lib/modules/cl_check.ak) — those are the\n * source of truth; keep this in lockstep with them.\n */\n\nconst asFeeParts = (fee: TFractionLike): [bigint, bigint] => {\n const f = Fraction.asFraction(fee);\n if (f.lt(Fraction.ZERO) || f.gte(Fraction.ONE))\n throw new Error(\"fee must be in [0, 1)\");\n return [BigInt(f.numerator), BigInt(f.denominator)];\n};\n\n/**\n * The raw forward swap: given a pre-fee input `dx`, return the output amount.\n * A→B and B→A use different virtual-reserve scalings (see `cl_check_swap`).\n * All quantities are non-negative so integer division floors, matching chain.\n */\nconst rawSwapOutput = (\n dx: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n spaNum: bigint,\n spaDen: bigint,\n spbNum: bigint,\n spbDen: bigint,\n feeNum: bigint,\n feeDen: bigint,\n isAInput: boolean,\n): bigint => {\n const fee = (dx * feeNum) / feeDen;\n const dxEff = dx - fee;\n const va0 = aReserve * spbNum + totalLp * spbDen;\n const vb0 = bReserve * spaDen + totalLp * spaNum;\n if (isAInput) {\n const dvaEff = dxEff * spbNum;\n const denom = (va0 + dvaEff) * spaDen;\n if (denom <= 0n) return 0n;\n return (vb0 * dvaEff) / denom;\n }\n const dvbEff = dxEff * spaNum;\n const denom = (vb0 + dvbEff) * spbNum;\n if (denom <= 0n) return 0n;\n return (va0 * dvbEff) / denom;\n};\n\n/**\n * Calculate the swap outcome for a concentrated-liquidity pool.\n *\n * @param inputMetadata Metadata for the supplied (input) asset — used for the fee AssetAmount.\n * @param input The pre-fee amount of the input asset being swapped.\n * @param aReserve The pool's raw reserve of asset A.\n * @param bReserve The pool's raw reserve of asset B.\n * @param totalLp The pool's total LP supply (the virtual liquidity `L`).\n * @param sqrtPriceA The lower sqrt-price bound `[num, den]` from the CL config.\n * @param sqrtPriceB The upper sqrt-price bound `[num, den]` from the CL config.\n * @param fee The liquidity-provider fee (plus protocol fee) as a fraction.\n * @param isAInput True when asset A is the supplied asset (A→B swap).\n * @returns The swap details in the shared {@link TSwapOutcome} shape.\n */\nexport const getSwapOutput = (\n inputMetadata: IAssetAmountMetadata,\n input: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n sqrtPriceA: TSqrtPrice,\n sqrtPriceB: TSqrtPrice,\n fee: TFractionLike,\n isAInput: boolean,\n): TSwapOutcome => {\n if (input <= 0n || aReserve <= 0n || bReserve <= 0n || totalLp <= 0n)\n throw new Error(\"Input, reserves and liquidity must be positive\");\n const [spaNum, spaDen] = sqrtPriceA;\n const [spbNum, spbDen] = sqrtPriceB;\n if (spaNum <= 0n || spaDen <= 0n || spbNum <= 0n || spbDen <= 0n)\n throw new Error(\"sqrt prices must be positive\");\n const [feeNum, feeDen] = asFeeParts(fee);\n\n const inputReserve = isAInput ? aReserve : bReserve;\n const outputReserve = isAInput ? bReserve : aReserve;\n\n let output = rawSwapOutput(\n input,\n aReserve,\n bReserve,\n totalLp,\n spaNum,\n spaDen,\n spbNum,\n spbDen,\n feeNum,\n feeDen,\n isAInput,\n );\n // Can't take more than the pool actually holds (virtual reserves can\n // otherwise let the formula exceed the real reserve near the boundary).\n if (output > outputReserve) output = outputReserve;\n\n const inputLpFee = (input * feeNum) / feeDen;\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - output;\n\n // Price impact vs the marginal (dx→0) rate. Marginal output-per-effective-\n // input is vb0·spbNum/(va0·spaDen) for A→B (symmetric for B→A), so the ideal\n // input-per-output is its reciprocal. Display-only.\n const va0 = aReserve * spbNum + totalLp * spbDen;\n const vb0 = bReserve * spaDen + totalLp * spaNum;\n let priceImpact = Fraction.ZERO;\n if (output > 0n) {\n const idealPrice = isAInput\n ? new Fraction(va0 * spaDen, vb0 * spbNum)\n : new Fraction(vb0 * spbNum, va0 * spaDen);\n const actualPrice = new Fraction(input - inputLpFee, output);\n priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n }\n\n return {\n input,\n output,\n lpFee: new AssetAmount(inputLpFee, inputMetadata),\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n/**\n * Calculate the minimal input required to receive a given output — the inverse\n * of {@link getSwapOutput}. The forward swap is linear-fractional in the\n * effective input, so it inverts in closed form; a short correction loop\n * absorbs the fee floor and integer rounding so the result is the exact minimal\n * input whose forward swap yields at least `output`.\n */\nexport const getSwapInput = (\n inputMetadata: IAssetAmountMetadata,\n output: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n sqrtPriceA: TSqrtPrice,\n sqrtPriceB: TSqrtPrice,\n fee: TFractionLike,\n isAInput: boolean,\n): TSwapOutcome => {\n if (output <= 0n || aReserve <= 0n || bReserve <= 0n || totalLp <= 0n)\n throw new Error(\"Output, reserves and liquidity must be positive\");\n const [spaNum, spaDen] = sqrtPriceA;\n const [spbNum, spbDen] = sqrtPriceB;\n if (spaNum <= 0n || spaDen <= 0n || spbNum <= 0n || spbDen <= 0n)\n throw new Error(\"sqrt prices must be positive\");\n const outputReserve = isAInput ? bReserve : aReserve;\n if (output > outputReserve)\n throw new Error(\"Output must not exceed the output reserve\");\n\n const [feeNum, feeDen] = asFeeParts(fee);\n const feeDiff = feeDen - feeNum;\n\n const va0 = aReserve * spbNum + totalLp * spbDen;\n const vb0 = bReserve * spaDen + totalLp * spaNum;\n\n const ceilDiv = (n: bigint, d: bigint) => (n + d - 1n) / d;\n\n // Closed-form minimal effective input, then gross up for the fee floor.\n let effMin: bigint;\n if (isAInput) {\n // dvaEff ≥ output·spaDen·va0 / (vb0 − output·spaDen)\n const denom = vb0 - output * spaDen;\n if (denom <= 0n)\n throw new Error(\"Output not reachable within the pool's range\");\n const dvaEffMin = ceilDiv(output * spaDen * va0, denom);\n effMin = ceilDiv(dvaEffMin, spbNum);\n } else {\n const denom = va0 - output * spbNum;\n if (denom <= 0n)\n throw new Error(\"Output not reachable within the pool's range\");\n const dvbEffMin = ceilDiv(output * spbNum * vb0, denom);\n effMin = ceilDiv(dvbEffMin, spaNum);\n }\n let input = feeDiff > 0n ? ceilDiv(effMin * feeDen, feeDiff) : effMin;\n\n // Correct for floor interactions: nudge up until the forward swap clears the\n // target, then trim any over-shoot. Bounded — a couple of iterations at most.\n const fwd = (dx: bigint) =>\n rawSwapOutput(\n dx,\n aReserve,\n bReserve,\n totalLp,\n spaNum,\n spaDen,\n spbNum,\n spbDen,\n feeNum,\n feeDen,\n isAInput,\n );\n let guard = 0;\n while (fwd(input) < output && guard++ < 64) input += 1n;\n while (input > 1n && fwd(input - 1n) >= output) input -= 1n;\n\n const inputLpFee = (input * feeNum) / feeDen;\n const inputReserve = isAInput ? aReserve : bReserve;\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - output;\n\n let priceImpact = Fraction.ZERO;\n if (output > 0n) {\n const idealPrice = isAInput\n ? new Fraction(va0 * spaDen, vb0 * spbNum)\n : new Fraction(vb0 * spbNum, va0 * spaDen);\n const actualPrice = new Fraction(input - inputLpFee, output);\n priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n }\n\n return {\n input,\n output,\n lpFee: new AssetAmount(inputLpFee, inputMetadata),\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n/**\n * Deposit LP estimate for a concentrated-liquidity pool. CL deposits reuse the\n * constant-product *proportional* pinning: minting by the scarcest offered\n * asset and ceil-pinning the reserve deltas gives, per asset,\n * `a1·L0 ≥ a0·L1` and `b1·L0 ≥ b0·L1` — and those two bounds multiply to\n * exactly the on-chain CL non-swap invariant `va1·vb1·L0² ≥ va0·vb0·L1²`\n * (`cl_check.ak`). So the proportional deposit is always chain-valid; excess of\n * either asset is refunded via aChange/bChange. This mirrors the scooper's\n * `resolve_cl_deposit` (which likewise reuses the CP pinning).\n */\nexport const calculateLiquidity = (\n a: bigint,\n b: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n) => ConstantProductPool.calculateLiquidity(a, b, aReserve, bReserve, totalLp);\n"],"mappings":"AAAA,SAASA,WAAW,QAA8B,mBAAmB;AACrE,SAASC,QAAQ,QAA4B,sBAAsB;AAEnE,OAAO,KAAKC,mBAAmB,MAAM,0BAA0B;;AAE/D;AACA;AACA;AACA;AACA;;AAUA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,MAAMC,UAAU,GAAIC,GAAkB,IAAuB;EAC3D,MAAMC,CAAC,GAAGJ,QAAQ,CAACK,UAAU,CAACF,GAAG,CAAC;EAClC,IAAIC,CAAC,CAACE,EAAE,CAACN,QAAQ,CAACO,IAAI,CAAC,IAAIH,CAAC,CAACI,GAAG,CAACR,QAAQ,CAACS,GAAG,CAAC,EAC5C,MAAM,IAAIC,KAAK,CAAC,uBAAuB,CAAC;EAC1C,OAAO,CAACC,MAAM,CAACP,CAAC,CAACQ,SAAS,CAAC,EAAED,MAAM,CAACP,CAAC,CAACS,WAAW,CAAC,CAAC;AACrD,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA,MAAMC,aAAa,GAAGA,CACpBC,EAAU,EACVC,QAAgB,EAChBC,QAAgB,EAChBC,OAAe,EACfC,MAAc,EACdC,MAAc,EACdC,MAAc,EACdC,MAAc,EACdC,MAAc,EACdC,MAAc,EACdC,QAAiB,KACN;EACX,MAAMtB,GAAG,GAAIY,EAAE,GAAGQ,MAAM,GAAIC,MAAM;EAClC,MAAME,KAAK,GAAGX,EAAE,GAAGZ,GAAG;EACtB,MAAMwB,GAAG,GAAGX,QAAQ,GAAGK,MAAM,GAAGH,OAAO,GAAGI,MAAM;EAChD,MAAMM,GAAG,GAAGX,QAAQ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eswap/asset";
2
+ import { Fraction } 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
+
11
+ /**
12
+ * Calculate the swap outcome for a constant-sum (fixed-price) pool — the
13
+ * invariant used by Sundae v4 stable/pegged pools. Unlike constant product,
14
+ * the exchange rate is fixed by the pool's per-asset `prices`: the input is
15
+ * converted to "value" at `priceIn`, the fee is taken off that value, and the
16
+ * remainder is converted to the output asset at `priceOut`. The result is
17
+ * capped at the output reserve (you can't take more than the pool holds).
18
+ *
19
+ * Matches the scooper's `cs_swap_result`:
20
+ * output = floor((input·priceIn − floor(input·priceIn·fee)) / priceOut)
21
+ *
22
+ * @param inputMetadata Metadata for the supplied (input) asset — used for the fee AssetAmount.
23
+ * @param input The amount of the input asset being swapped.
24
+ * @param inputReserve The pool's reserve of the input asset.
25
+ * @param outputReserve The pool's reserve of the output asset.
26
+ * @param priceIn The pool's price for the input asset (from the constant-sum config).
27
+ * @param priceOut The pool's price for the output asset.
28
+ * @param fee The liquidity-provider fee (plus protocol fee) as a fraction.
29
+ * @param roundOutputUp When true, round the output up instead of flooring.
30
+ * @returns The swap details in the shared {@link TSwapOutcome} shape.
31
+ */
32
+ export const getSwapOutput = (inputMetadata, input, inputReserve, outputReserve, priceIn, priceOut, fee, roundOutputUp) => {
33
+ if (input <= 0n || inputReserve <= 0n || outputReserve <= 0n) throw new Error("Input and reserves must be positive");
34
+ if (priceIn <= 0n || priceOut <= 0n) throw new Error("Prices must be positive");
35
+ const feeFraction = Fraction.asFraction(fee);
36
+ if (feeFraction.lt(Fraction.ZERO) || feeFraction.gt(Fraction.ONE)) throw new Error("fee must be between 0 and 1");
37
+ const inputValue = input * priceIn;
38
+ const feeValue = new Fraction(inputValue * BigInt(feeFraction.numerator), BigInt(feeFraction.denominator)).quotient;
39
+ const outputValue = inputValue - feeValue;
40
+ let output = roundOutputUp ? (outputValue + priceOut - 1n) / priceOut : outputValue / priceOut;
41
+
42
+ // Can't take more than the pool holds.
43
+ if (output > outputReserve) {
44
+ output = outputReserve;
45
+ }
46
+
47
+ // LP fee expressed in input-asset units (value scales linearly with input,
48
+ // so the input-denominated fee is input·feeRate) — matching ConstantProductPool.
49
+ const inputLpFee = new Fraction(input * BigInt(feeFraction.numerator), BigInt(feeFraction.denominator)).quotient;
50
+ const nextInputReserve = inputReserve + input;
51
+ const nextOutputReserve = outputReserve - output;
52
+
53
+ // Price impact vs the pool's par price (priceOut/priceIn input-per-output);
54
+ // ~0 for a constant-sum pool aside from the fee. See ConstantProductPool.
55
+ let priceImpact = Fraction.ZERO;
56
+ if (output > 0n) {
57
+ const amountInLessFee = input - inputLpFee;
58
+ const idealPrice = new Fraction(priceOut, priceIn);
59
+ const actualPrice = new Fraction(amountInLessFee, output);
60
+ priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
61
+ }
62
+ return {
63
+ input,
64
+ output,
65
+ lpFee: new AssetAmount(inputLpFee, inputMetadata),
66
+ nextInputReserve,
67
+ nextOutputReserve,
68
+ priceImpact
69
+ };
70
+ };
71
+
72
+ /**
73
+ * Calculate the minimal input required to receive a given output from a
74
+ * constant-sum pool — the exact inverse of {@link getSwapOutput}.
75
+ *
76
+ * The forward math floors the fee off the input value, which makes the
77
+ * post-fee value `ceil(input·priceIn·(1−fee))`; inverting that ceiling gives
78
+ * the smallest input whose forward swap yields at least `output`.
79
+ *
80
+ * Unlike constant product there is no asymptote, so an output equal to the
81
+ * full output reserve is attainable (the pool can be drained at par).
82
+ *
83
+ * @param inputMetadata Metadata for the supplied (input) asset — used for the fee AssetAmount.
84
+ * @param output The desired amount of the output asset.
85
+ * @param inputReserve The pool's reserve of the input asset.
86
+ * @param outputReserve The pool's reserve of the output asset.
87
+ * @param priceIn The pool's price for the input asset (from the constant-sum config).
88
+ * @param priceOut The pool's price for the output asset.
89
+ * @param fee The liquidity-provider fee (plus protocol fee) as a fraction.
90
+ * @returns The swap details in the shared {@link TSwapOutcome} shape.
91
+ */
92
+ export const getSwapInput = (inputMetadata, output, inputReserve, outputReserve, priceIn, priceOut, fee) => {
93
+ if (output <= 0n || inputReserve <= 0n || outputReserve <= 0n) throw new Error("Output and reserves must be positive");
94
+ if (priceIn <= 0n || priceOut <= 0n) throw new Error("Prices must be positive");
95
+ if (output > outputReserve) throw new Error("Output must not exceed the output reserve");
96
+ const feeFraction = Fraction.asFraction(fee);
97
+ if (feeFraction.lt(Fraction.ZERO) || feeFraction.gte(Fraction.ONE)) throw new Error("fee must be [0,1)");
98
+ const feeNum = BigInt(feeFraction.numerator);
99
+ const feeDen = BigInt(feeFraction.denominator);
100
+ const feeDiff = feeDen - feeNum;
101
+
102
+ // Forward: outputValue = ceil(input·priceIn·feeDiff/feeDen), and the swap
103
+ // yields ≥ output iff outputValue ≥ output·priceOut. ceil(x/d) ≥ T for
104
+ // integer x iff x ≥ d·(T−1)+1, so the minimal input is the ceiling of
105
+ // (feeDen·(output·priceOut − 1) + 1) / (feeDiff·priceIn).
106
+ const targetValue = output * priceOut;
107
+ const numerator = feeDen * (targetValue - 1n) + 1n;
108
+ const denominator = feeDiff * priceIn;
109
+ const input = (numerator + denominator - 1n) / denominator;
110
+ const inputLpFee = new Fraction(input * feeNum, feeDen).quotient;
111
+ const nextInputReserve = inputReserve + input;
112
+ const nextOutputReserve = outputReserve - output;
113
+
114
+ // Same par-price impact definition as getSwapOutput.
115
+ const amountInLessFee = input - inputLpFee;
116
+ const idealPrice = new Fraction(priceOut, priceIn);
117
+ const actualPrice = new Fraction(amountInLessFee, output);
118
+ const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
119
+ return {
120
+ input,
121
+ output,
122
+ lpFee: new AssetAmount(inputLpFee, inputMetadata),
123
+ nextInputReserve,
124
+ nextOutputReserve,
125
+ priceImpact
126
+ };
127
+ };
128
+
129
+ /**
130
+ * Calculate the deposit parameters for a 2-asset constant-sum pool via the
131
+ * TARGET-PINNED rule the deployed validator enforces (see
132
+ * {@link calculatePinnedDeposit}): the mint is capped by the scarcest offered
133
+ * asset, both assets must be offered, and anything above the pinned deltas is
134
+ * refunded via aChange/bChange.
135
+ *
136
+ * @param {bigint} a - The amount of token A to deposit.
137
+ * @param {bigint} b - The amount of token B to deposit.
138
+ * @param {bigint} aReserve - The current reserve of token A in the pool.
139
+ * @param {bigint} bReserve - The current reserve of token B in the pool.
140
+ * @param {bigint} totalLp - The total lp tokens for the pool before the deposit.
141
+ * @param {bigint} priceA - The pool's price for token A (from the constant-sum config).
142
+ * @param {bigint} priceB - The pool's price for token B.
143
+ * @throws {Error} If the pool has no value or minted lp.
144
+ * @throws {Error} If both deposit amounts are zero, or either is negative.
145
+ * @throws {Error} If either price is non-positive.
146
+ */
147
+ export const calculateLiquidity = (a, b, aReserve, bReserve, totalLp, priceA, priceB) => {
148
+ // Target-pinned (what the deployed validator accepts): mint by the
149
+ // scarcest offered asset; anything above the pinned deltas is refunded
150
+ // (aChange/bChange).
151
+ const {
152
+ deltas,
153
+ generatedLp,
154
+ nextTotalLp,
155
+ shareAfterDeposit
156
+ } = calculatePinnedDeposit([a, b], [aReserve, bReserve], [priceA, priceB], totalLp);
157
+ return {
158
+ nextTotalLp,
159
+ generatedLp,
160
+ shareAfterDeposit,
161
+ aChange: a - deltas[0],
162
+ bChange: b - deltas[1],
163
+ actualDepositedA: deltas[0],
164
+ actualDepositedB: deltas[1]
165
+ };
166
+ };
167
+
168
+ /**
169
+ * The N-asset form of {@link calculateLiquidity}, mirroring the v4 contract's
170
+ * `compute_deposit_n` exactly: a deposit of any mix of the pool's assets is
171
+ * valued at the fixed prices against the value of ALL reserves —
172
+ *
173
+ * generatedLp = Σ(amount_i·price_i) · totalLp / Σ(reserve_i·price_i)
174
+ *
175
+ * The three arrays must be aligned to the pool's canonical asset order (the
176
+ * API's `assets`/`quantities`/`prices`). Estimating an N-asset pool's deposit
177
+ * from just two of its reserves overstates the minted LP — the denominator is
178
+ * the whole pool's value — which is exactly the mistake this exists to
179
+ * prevent.
180
+ */
181
+ /**
182
+ * The target-pinned deposit — what the deployed CS validator (cs_check tag 6)
183
+ * actually accepts, and what the scooper builds. Asymmetric deposits are
184
+ * disallowed on-chain: the fill declares a value delta `t` and every asset's
185
+ * contribution is ceil-pinned to `ceil(r_i·t/V_b)`, with total LP
186
+ * floor-pinned to `floor(lp_b·(V_b+t)/V_b)`. Given what the user offers, the
187
+ * largest fillable t is capped by the SCARCEST asset —
188
+ * `t = min_i floor(offered_i·V_b/r_i)` — and anything above the pinned
189
+ * deltas is returned as surplus. Every pool asset must be offered (> 0) or
190
+ * t is zero and the deposit can never fill.
191
+ *
192
+ * Contrast with `calculateDepositN`, which is the plain value formula:
193
+ * it matches the pin only for exactly proportional offers and OVERSTATES the
194
+ * mint otherwise — using it for `minReceived` makes non-proportional orders
195
+ * unfillable.
196
+ */
197
+ export const calculatePinnedDeposit = (offered, reserves, prices, totalLp) => {
198
+ if (offered.length !== reserves.length || reserves.length !== prices.length) throw new Error("offered, reserves and prices must be aligned");
199
+ if (prices.some(p => p <= 0n)) throw new Error("Prices must be positive");
200
+ if (totalLp <= 0n) throw new Error("Not enough pool liquidity");
201
+ let vB = 0n;
202
+ for (let i = 0; i < reserves.length; i++) {
203
+ vB += reserves[i] * prices[i];
204
+ }
205
+ if (vB <= 0n) throw new Error("Pool value is zero");
206
+ let t;
207
+ for (let i = 0; i < offered.length; i++) {
208
+ if (reserves[i] === 0n) continue;
209
+ const cap = offered[i] * vB / reserves[i];
210
+ t = t === undefined || cap < t ? cap : t;
211
+ }
212
+ if (t === undefined || t <= 0n) {
213
+ throw new Error("A constant-sum deposit must offer every pool asset in proportion (asymmetric deposits are disallowed on-chain)");
214
+ }
215
+ const deltas = reserves.map(r => (r * t + vB - 1n) / vB); // ceil
216
+ const nextTotalLp = totalLp * (vB + t) / vB; // floor
217
+ const generatedLp = nextTotalLp - totalLp;
218
+ if (generatedLp <= 0n) throw new Error("Deposit mints zero LP");
219
+ return {
220
+ targetDeltaV: t,
221
+ deltas,
222
+ generatedLp,
223
+ nextTotalLp,
224
+ shareAfterDeposit: SharedPoolMath.getShare(generatedLp, nextTotalLp)
225
+ };
226
+ };
227
+
228
+ /**
229
+ * The per-asset amounts a pinned deposit needs when the user anchors on one
230
+ * asset's amount: t from the anchor (`floor(anchor·V_b/r_anchor)`), every
231
+ * delta ceil-pinned to it. Drives proportional auto-fill in deposit forms.
232
+ */
233
+ export const pinnedDepositFromAnchor = (anchorIndex, anchorAmount, reserves, prices) => {
234
+ if (reserves.length !== prices.length) throw new Error("reserves and prices must be aligned");
235
+ if (anchorIndex < 0 || anchorIndex >= reserves.length || reserves[anchorIndex] <= 0n) throw new Error("anchor asset has no reserve");
236
+ if (anchorAmount <= 0n) return reserves.map(() => 0n);
237
+ let vB = 0n;
238
+ for (let i = 0; i < reserves.length; i++) {
239
+ vB += reserves[i] * prices[i];
240
+ }
241
+ if (vB <= 0n) throw new Error("Pool value is zero");
242
+ const t = anchorAmount * vB / reserves[anchorIndex];
243
+ return reserves.map((r, i) => i === anchorIndex ? anchorAmount : (r * t + vB - 1n) / vB);
244
+ };
245
+ export const calculateDepositN = (amounts, reserves, prices, totalLp) => {
246
+ if (amounts.length !== reserves.length || reserves.length !== prices.length) throw new Error("amounts, reserves and prices must be aligned");
247
+ if (prices.some(p => p <= 0n)) throw new Error("Prices must be positive");
248
+ // Zeros in a MIX are fine — offering a subset is the point of the N-asset
249
+ // form. What's rejected is a negative amount, or offering nothing at all.
250
+ if (amounts.some(a => a < 0n) || amounts.every(a => a === 0n)) throw new Error("Deposit amounts must be non-negative, with at least one positive");
251
+ let totalValue = 0n;
252
+ let depositValue = 0n;
253
+ for (let i = 0; i < amounts.length; i++) {
254
+ totalValue += reserves[i] * prices[i];
255
+ depositValue += amounts[i] * prices[i];
256
+ }
257
+ if (totalValue <= 0n || totalLp <= 0n) throw new Error("Not enough pool liquidity");
258
+ const generatedLp = depositValue * totalLp / totalValue;
259
+ const nextTotalLp = totalLp + generatedLp;
260
+ return {
261
+ nextTotalLp,
262
+ generatedLp,
263
+ shareAfterDeposit: SharedPoolMath.getShare(generatedLp, nextTotalLp)
264
+ };
265
+ };
266
+ //# sourceMappingURL=ConstantSumPool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConstantSumPool.js","names":["AssetAmount","Fraction","SharedPoolMath","getSwapOutput","inputMetadata","input","inputReserve","outputReserve","priceIn","priceOut","fee","roundOutputUp","Error","feeFraction","asFraction","lt","ZERO","gt","ONE","inputValue","feeValue","BigInt","numerator","denominator","quotient","outputValue","output","inputLpFee","nextInputReserve","nextOutputReserve","priceImpact","amountInLessFee","idealPrice","actualPrice","subtract","divide","lpFee","getSwapInput","gte","feeNum","feeDen","feeDiff","targetValue","calculateLiquidity","a","b","aReserve","bReserve","totalLp","priceA","priceB","deltas","generatedLp","nextTotalLp","shareAfterDeposit","calculatePinnedDeposit","aChange","bChange","actualDepositedA","actualDepositedB","offered","reserves","prices","length","some","p","vB","i","t","cap","undefined","map","r","targetDeltaV","getShare","pinnedDepositFromAnchor","anchorIndex","anchorAmount","calculateDepositN","amounts","every","totalValue","depositValue"],"sources":["../../../src/PoolMath/ConstantSumPool.ts"],"sourcesContent":["import { AssetAmount, IAssetAmountMetadata } from \"@sundaeswap/asset\";\nimport { Fraction, type TFractionLike } from \"@sundaeswap/fraction\";\nimport { SharedPoolMath } from \"./index.js\";\n\n/**\n * Holds the calculated outcome of a constant-sum swap. Mirrors\n * {@link ConstantProductPool.TSwapOutcome} so both can flow through the same\n * generic swap-outcome consumers.\n */\nexport type TSwapOutcome = {\n input: bigint;\n output: bigint;\n lpFee: AssetAmount<IAssetAmountMetadata>;\n nextInputReserve: bigint;\n nextOutputReserve: bigint;\n priceImpact: Fraction;\n};\n\n/**\n * Calculate the swap outcome for a constant-sum (fixed-price) pool — the\n * invariant used by Sundae v4 stable/pegged pools. Unlike constant product,\n * the exchange rate is fixed by the pool's per-asset `prices`: the input is\n * converted to \"value\" at `priceIn`, the fee is taken off that value, and the\n * remainder is converted to the output asset at `priceOut`. The result is\n * capped at the output reserve (you can't take more than the pool holds).\n *\n * Matches the scooper's `cs_swap_result`:\n * output = floor((input·priceIn − floor(input·priceIn·fee)) / priceOut)\n *\n * @param inputMetadata Metadata for the supplied (input) asset — used for the fee AssetAmount.\n * @param input The amount of the input asset being swapped.\n * @param inputReserve The pool's reserve of the input asset.\n * @param outputReserve The pool's reserve of the output asset.\n * @param priceIn The pool's price for the input asset (from the constant-sum config).\n * @param priceOut The pool's price for the output asset.\n * @param fee The liquidity-provider fee (plus protocol fee) as a fraction.\n * @param roundOutputUp When true, round the output up instead of flooring.\n * @returns The swap details in the shared {@link TSwapOutcome} shape.\n */\nexport const getSwapOutput = (\n inputMetadata: IAssetAmountMetadata,\n input: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n priceIn: bigint,\n priceOut: bigint,\n fee: TFractionLike,\n roundOutputUp?: boolean,\n): TSwapOutcome => {\n if (input <= 0n || inputReserve <= 0n || outputReserve <= 0n)\n throw new Error(\"Input and reserves must be positive\");\n if (priceIn <= 0n || priceOut <= 0n)\n throw new Error(\"Prices must be positive\");\n\n const feeFraction = Fraction.asFraction(fee);\n if (feeFraction.lt(Fraction.ZERO) || feeFraction.gt(Fraction.ONE))\n throw new Error(\"fee must be between 0 and 1\");\n\n const inputValue = input * priceIn;\n const feeValue = new Fraction(\n inputValue * BigInt(feeFraction.numerator),\n BigInt(feeFraction.denominator),\n ).quotient;\n const outputValue = inputValue - feeValue;\n\n let output = roundOutputUp\n ? (outputValue + priceOut - 1n) / priceOut\n : outputValue / priceOut;\n\n // Can't take more than the pool holds.\n if (output > outputReserve) {\n output = outputReserve;\n }\n\n // LP fee expressed in input-asset units (value scales linearly with input,\n // so the input-denominated fee is input·feeRate) — matching ConstantProductPool.\n const inputLpFee = new Fraction(\n input * BigInt(feeFraction.numerator),\n BigInt(feeFraction.denominator),\n ).quotient;\n\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - output;\n\n // Price impact vs the pool's par price (priceOut/priceIn input-per-output);\n // ~0 for a constant-sum pool aside from the fee. See ConstantProductPool.\n let priceImpact = Fraction.ZERO;\n if (output > 0n) {\n const amountInLessFee = input - inputLpFee;\n const idealPrice = new Fraction(priceOut, priceIn);\n const actualPrice = new Fraction(amountInLessFee, output);\n priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n }\n\n return {\n input,\n output,\n lpFee: new AssetAmount(inputLpFee, inputMetadata),\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n/**\n * Calculate the minimal input required to receive a given output from a\n * constant-sum pool — the exact inverse of {@link getSwapOutput}.\n *\n * The forward math floors the fee off the input value, which makes the\n * post-fee value `ceil(input·priceIn·(1−fee))`; inverting that ceiling gives\n * the smallest input whose forward swap yields at least `output`.\n *\n * Unlike constant product there is no asymptote, so an output equal to the\n * full output reserve is attainable (the pool can be drained at par).\n *\n * @param inputMetadata Metadata for the supplied (input) asset — used for the fee AssetAmount.\n * @param output The desired amount of the output asset.\n * @param inputReserve The pool's reserve of the input asset.\n * @param outputReserve The pool's reserve of the output asset.\n * @param priceIn The pool's price for the input asset (from the constant-sum config).\n * @param priceOut The pool's price for the output asset.\n * @param fee The liquidity-provider fee (plus protocol fee) as a fraction.\n * @returns The swap details in the shared {@link TSwapOutcome} shape.\n */\nexport const getSwapInput = (\n inputMetadata: IAssetAmountMetadata,\n output: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n priceIn: bigint,\n priceOut: bigint,\n fee: TFractionLike,\n): TSwapOutcome => {\n if (output <= 0n || inputReserve <= 0n || outputReserve <= 0n)\n throw new Error(\"Output and reserves must be positive\");\n if (priceIn <= 0n || priceOut <= 0n)\n throw new Error(\"Prices must be positive\");\n if (output > outputReserve)\n throw new Error(\"Output must not exceed the output reserve\");\n\n const feeFraction = Fraction.asFraction(fee);\n if (feeFraction.lt(Fraction.ZERO) || feeFraction.gte(Fraction.ONE))\n throw new Error(\"fee must be [0,1)\");\n\n const feeNum = BigInt(feeFraction.numerator);\n const feeDen = BigInt(feeFraction.denominator);\n const feeDiff = feeDen - feeNum;\n\n // Forward: outputValue = ceil(input·priceIn·feeDiff/feeDen), and the swap\n // yields ≥ output iff outputValue ≥ output·priceOut. ceil(x/d) ≥ T for\n // integer x iff x ≥ d·(T−1)+1, so the minimal input is the ceiling of\n // (feeDen·(output·priceOut − 1) + 1) / (feeDiff·priceIn).\n const targetValue = output * priceOut;\n const numerator = feeDen * (targetValue - 1n) + 1n;\n const denominator = feeDiff * priceIn;\n const input = (numerator + denominator - 1n) / denominator;\n\n const inputLpFee = new Fraction(input * feeNum, feeDen).quotient;\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - output;\n\n // Same par-price impact definition as getSwapOutput.\n const amountInLessFee = input - inputLpFee;\n const idealPrice = new Fraction(priceOut, priceIn);\n const actualPrice = new Fraction(amountInLessFee, output);\n const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n\n return {\n input,\n output,\n lpFee: new AssetAmount(inputLpFee, inputMetadata),\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n/**\n * Calculate the deposit parameters for a 2-asset constant-sum pool via the\n * TARGET-PINNED rule the deployed validator enforces (see\n * {@link calculatePinnedDeposit}): the mint is capped by the scarcest offered\n * asset, both assets must be offered, and anything above the pinned deltas is\n * refunded via aChange/bChange.\n *\n * @param {bigint} a - The amount of token A to deposit.\n * @param {bigint} b - The amount of token B to deposit.\n * @param {bigint} aReserve - The current reserve of token A in the pool.\n * @param {bigint} bReserve - The current reserve of token B in the pool.\n * @param {bigint} totalLp - The total lp tokens for the pool before the deposit.\n * @param {bigint} priceA - The pool's price for token A (from the constant-sum config).\n * @param {bigint} priceB - The pool's price for token B.\n * @throws {Error} If the pool has no value or minted lp.\n * @throws {Error} If both deposit amounts are zero, or either is negative.\n * @throws {Error} If either price is non-positive.\n */\nexport const calculateLiquidity = (\n a: bigint,\n b: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n priceA: bigint,\n priceB: bigint,\n) => {\n // Target-pinned (what the deployed validator accepts): mint by the\n // scarcest offered asset; anything above the pinned deltas is refunded\n // (aChange/bChange).\n const { deltas, generatedLp, nextTotalLp, shareAfterDeposit } =\n calculatePinnedDeposit(\n [a, b],\n [aReserve, bReserve],\n [priceA, priceB],\n totalLp,\n );\n\n return {\n nextTotalLp,\n generatedLp,\n shareAfterDeposit,\n aChange: a - deltas[0],\n bChange: b - deltas[1],\n actualDepositedA: deltas[0],\n actualDepositedB: deltas[1],\n };\n};\n\n/**\n * The N-asset form of {@link calculateLiquidity}, mirroring the v4 contract's\n * `compute_deposit_n` exactly: a deposit of any mix of the pool's assets is\n * valued at the fixed prices against the value of ALL reserves —\n *\n * generatedLp = Σ(amount_i·price_i) · totalLp / Σ(reserve_i·price_i)\n *\n * The three arrays must be aligned to the pool's canonical asset order (the\n * API's `assets`/`quantities`/`prices`). Estimating an N-asset pool's deposit\n * from just two of its reserves overstates the minted LP — the denominator is\n * the whole pool's value — which is exactly the mistake this exists to\n * prevent.\n */\n/**\n * The target-pinned deposit — what the deployed CS validator (cs_check tag 6)\n * actually accepts, and what the scooper builds. Asymmetric deposits are\n * disallowed on-chain: the fill declares a value delta `t` and every asset's\n * contribution is ceil-pinned to `ceil(r_i·t/V_b)`, with total LP\n * floor-pinned to `floor(lp_b·(V_b+t)/V_b)`. Given what the user offers, the\n * largest fillable t is capped by the SCARCEST asset —\n * `t = min_i floor(offered_i·V_b/r_i)` — and anything above the pinned\n * deltas is returned as surplus. Every pool asset must be offered (> 0) or\n * t is zero and the deposit can never fill.\n *\n * Contrast with `calculateDepositN`, which is the plain value formula:\n * it matches the pin only for exactly proportional offers and OVERSTATES the\n * mint otherwise — using it for `minReceived` makes non-proportional orders\n * unfillable.\n */\nexport const calculatePinnedDeposit = (\n offered: bigint[],\n reserves: bigint[],\n prices: bigint[],\n totalLp: bigint,\n): {\n targetDeltaV: bigint;\n deltas: bigint[];\n generatedLp: bigint;\n nextTotalLp: bigint;\n shareAfterDeposit: Fraction;\n} => {\n if (offered.length !== reserves.length || reserves.length !== prices.length)\n throw new Error(\"offered, reserves and prices must be aligned\");\n if (prices.some((p) => p <= 0n)) throw new Error(\"Prices must be positive\");\n if (totalLp <= 0n) throw new Error(\"Not enough pool liquidity\");\n\n let vB = 0n;\n for (let i = 0; i < reserves.length; i++) {\n vB += reserves[i] * prices[i];\n }\n if (vB <= 0n) throw new Error(\"Pool value is zero\");\n\n let t: bigint | undefined;\n for (let i = 0; i < offered.length; i++) {\n if (reserves[i] === 0n) continue;\n const cap = (offered[i] * vB) / reserves[i];\n t = t === undefined || cap < t ? cap : t;\n }\n if (t === undefined || t <= 0n) {\n throw new Error(\n \"A constant-sum deposit must offer every pool asset in proportion (asymmetric deposits are disallowed on-chain)\",\n );\n }\n\n const deltas = reserves.map((r) => (r * t! + vB - 1n) / vB); // ceil\n const nextTotalLp = (totalLp * (vB + t)) / vB; // floor\n const generatedLp = nextTotalLp - totalLp;\n if (generatedLp <= 0n) throw new Error(\"Deposit mints zero LP\");\n\n return {\n targetDeltaV: t,\n deltas,\n generatedLp,\n nextTotalLp,\n shareAfterDeposit: SharedPoolMath.getShare(generatedLp, nextTotalLp),\n };\n};\n\n/**\n * The per-asset amounts a pinned deposit needs when the user anchors on one\n * asset's amount: t from the anchor (`floor(anchor·V_b/r_anchor)`), every\n * delta ceil-pinned to it. Drives proportional auto-fill in deposit forms.\n */\nexport const pinnedDepositFromAnchor = (\n anchorIndex: number,\n anchorAmount: bigint,\n reserves: bigint[],\n prices: bigint[],\n): bigint[] => {\n if (reserves.length !== prices.length)\n throw new Error(\"reserves and prices must be aligned\");\n if (\n anchorIndex < 0 ||\n anchorIndex >= reserves.length ||\n reserves[anchorIndex] <= 0n\n )\n throw new Error(\"anchor asset has no reserve\");\n if (anchorAmount <= 0n) return reserves.map(() => 0n);\n\n let vB = 0n;\n for (let i = 0; i < reserves.length; i++) {\n vB += reserves[i] * prices[i];\n }\n if (vB <= 0n) throw new Error(\"Pool value is zero\");\n\n const t = (anchorAmount * vB) / reserves[anchorIndex];\n return reserves.map((r, i) =>\n i === anchorIndex ? anchorAmount : (r * t + vB - 1n) / vB,\n );\n};\n\nexport const calculateDepositN = (\n amounts: bigint[],\n reserves: bigint[],\n prices: bigint[],\n totalLp: bigint,\n) => {\n if (amounts.length !== reserves.length || reserves.length !== prices.length)\n throw new Error(\"amounts, reserves and prices must be aligned\");\n if (prices.some((p) => p <= 0n)) throw new Error(\"Prices must be positive\");\n // Zeros in a MIX are fine — offering a subset is the point of the N-asset\n // form. What's rejected is a negative amount, or offering nothing at all.\n if (amounts.some((a) => a < 0n) || amounts.every((a) => a === 0n))\n throw new Error(\n \"Deposit amounts must be non-negative, with at least one positive\",\n );\n\n let totalValue = 0n;\n let depositValue = 0n;\n for (let i = 0; i < amounts.length; i++) {\n totalValue += reserves[i] * prices[i];\n depositValue += amounts[i] * prices[i];\n }\n if (totalValue <= 0n || totalLp <= 0n)\n throw new Error(\"Not enough pool liquidity\");\n\n const generatedLp = (depositValue * totalLp) / totalValue;\n const nextTotalLp = totalLp + generatedLp;\n\n return {\n nextTotalLp,\n generatedLp,\n shareAfterDeposit: SharedPoolMath.getShare(generatedLp, nextTotalLp),\n };\n};\n"],"mappings":"AAAA,SAASA,WAAW,QAA8B,mBAAmB;AACrE,SAASC,QAAQ,QAA4B,sBAAsB;AACnE,SAASC,cAAc,QAAQ,YAAY;;AAE3C;AACA;AACA;AACA;AACA;;AAUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,aAAa,GAAGA,CAC3BC,aAAmC,EACnCC,KAAa,EACbC,YAAoB,EACpBC,aAAqB,EACrBC,OAAe,EACfC,QAAgB,EA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