@sundaeswap/math 0.0.2 → 0.1.1

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 (32) hide show
  1. package/dist/cjs/PoolMath/ConstantProductPool.js +4 -29
  2. package/dist/cjs/PoolMath/ConstantProductPool.js.map +1 -1
  3. package/dist/cjs/PoolMath/SharedPoolMath.js +33 -0
  4. package/dist/cjs/PoolMath/SharedPoolMath.js.map +1 -0
  5. package/dist/cjs/PoolMath/StableSwapsPool.js +414 -0
  6. package/dist/cjs/PoolMath/StableSwapsPool.js.map +1 -0
  7. package/dist/cjs/PoolMath/index.js +5 -1
  8. package/dist/cjs/PoolMath/index.js.map +1 -1
  9. package/dist/esm/PoolMath/ConstantProductPool.js +3 -26
  10. package/dist/esm/PoolMath/ConstantProductPool.js.map +1 -1
  11. package/dist/esm/PoolMath/SharedPoolMath.js +26 -0
  12. package/dist/esm/PoolMath/SharedPoolMath.js.map +1 -0
  13. package/dist/esm/PoolMath/StableSwapsPool.js +400 -0
  14. package/dist/esm/PoolMath/StableSwapsPool.js.map +1 -0
  15. package/dist/esm/PoolMath/index.js +2 -0
  16. package/dist/esm/PoolMath/index.js.map +1 -1
  17. package/dist/types/PoolMath/ConstantProductPool.d.ts +6 -36
  18. package/dist/types/PoolMath/ConstantProductPool.d.ts.map +1 -1
  19. package/dist/types/PoolMath/SharedPoolMath.d.ts +36 -0
  20. package/dist/types/PoolMath/SharedPoolMath.d.ts.map +1 -0
  21. package/dist/types/PoolMath/StableSwapsPool.d.ts +221 -0
  22. package/dist/types/PoolMath/StableSwapsPool.d.ts.map +1 -0
  23. package/dist/types/PoolMath/index.d.ts +2 -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 +1 -1
  27. package/src/PoolMath/ConstantProductPool.ts +10 -45
  28. package/src/PoolMath/SharedPoolMath.ts +41 -0
  29. package/src/PoolMath/StableSwapsPool.ts +527 -0
  30. package/src/PoolMath/__tests__/ConstantProductPool.test.ts +6 -4
  31. package/src/PoolMath/__tests__/StableSwapsPool.test.ts +518 -0
  32. package/src/PoolMath/index.ts +2 -0
@@ -1,36 +1,7 @@
1
1
  import { AssetAmount } from "@sundaeswap/asset";
2
2
  import { Fraction, type TFractionLike } from "@sundaeswap/fraction";
3
3
  import { sqrt } from "@sundaeswap/bigint-math";
4
-
5
- /**
6
- * The direction of a ratio (A per B or B per A)
7
- */
8
- export type TRatioDirection = "A_PER_B" | "B_PER_A";
9
-
10
- /**
11
- * Asset used in a ratio calculation
12
- */
13
- export interface IRatioCalculationAsset {
14
- assetId: string;
15
- quantity: bigint;
16
- decimals: number;
17
- }
18
-
19
- /**
20
- * The result of a ratio calculation on a pool
21
- */
22
- export interface IRatioCalculationResult {
23
- calculatedAmount: AssetAmount;
24
- ratioAsFraction: Fraction;
25
- display: string;
26
- isDivisible: boolean;
27
- belowMinimumRatio: boolean;
28
- }
29
-
30
- /**
31
- * The amounts for a token pair
32
- */
33
- export type TPair = [bigint, bigint];
4
+ import { SharedPoolMath } from "./index.js";
34
5
 
35
6
  /**
36
7
  * Get the lp token amount for a, b
@@ -45,15 +16,6 @@ export const getFirstLp = (a: bigint, b: bigint) => sqrt(a * b);
45
16
  */
46
17
  export const getLp = getFirstLp;
47
18
 
48
- /**
49
- * Get the share ratio as Fraction
50
- * @param lp
51
- * @param totalLp
52
- * @returns
53
- */
54
- export const getShare = (lp: bigint, totalLp: bigint) =>
55
- new Fraction(lp, totalLp);
56
-
57
19
  /**
58
20
  * Calculate the Add (Mixed-Deposit) Liquidity parameters
59
21
  *
@@ -108,7 +70,7 @@ export const calculateLiquidity = (
108
70
  return {
109
71
  nextTotalLp: newTotalLpTokens,
110
72
  generatedLp: newLpTokens,
111
- shareAfterDeposit: getShare(newLpTokens, newTotalLpTokens),
73
+ shareAfterDeposit: SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),
112
74
  bChange,
113
75
  aChange,
114
76
  actualDepositedA,
@@ -130,7 +92,7 @@ export const addLiquidity = (
130
92
  const nextTotalLp = new Fraction(totalLp * (a + aReserve), aReserve).quotient;
131
93
  const lp = nextTotalLp - totalLp;
132
94
  const b = new Fraction(bReserve * a, aReserve);
133
- const share = getShare(lp, nextTotalLp);
95
+ const share = SharedPoolMath.getShare(lp, nextTotalLp);
134
96
 
135
97
  if (b.quotient === 0n) {
136
98
  throw new Error(
@@ -165,7 +127,7 @@ export const getTokensForLp = (
165
127
  aReserve: bigint,
166
128
  bReserve: bigint,
167
129
  totalLp: bigint,
168
- ): TPair => [
130
+ ): SharedPoolMath.TPair => [
169
131
  new Fraction(lp * aReserve, totalLp).quotient,
170
132
  new Fraction(lp * bReserve, totalLp).quotient,
171
133
  ];
@@ -351,9 +313,12 @@ export const getAssetsRatio = (
351
313
  * ```
352
314
  */
353
315
  export function getSwapRatio(
354
- direction: TRatioDirection,
355
- assets: [IRatioCalculationAsset, IRatioCalculationAsset],
356
- ): IRatioCalculationResult {
316
+ direction: SharedPoolMath.TRatioDirection,
317
+ assets: [
318
+ SharedPoolMath.IRatioCalculationAsset,
319
+ SharedPoolMath.IRatioCalculationAsset,
320
+ ],
321
+ ): SharedPoolMath.IRatioCalculationResult {
357
322
  let calculatedAmount: AssetAmount;
358
323
  let rawRatio: string;
359
324
  const adaIds = ["", ".", "ada.lovelace"];
@@ -0,0 +1,41 @@
1
+ import { AssetAmount } from "@sundaeswap/asset";
2
+ import { Fraction } from "@sundaeswap/fraction";
3
+
4
+ /**
5
+ * The direction of a ratio (A per B or B per A)
6
+ */
7
+ export type TRatioDirection = "A_PER_B" | "B_PER_A";
8
+
9
+ /**
10
+ * Asset used in a ratio calculation
11
+ */
12
+ export interface IRatioCalculationAsset {
13
+ assetId: string;
14
+ quantity: bigint;
15
+ decimals: number;
16
+ }
17
+
18
+ /**
19
+ * The result of a ratio calculation on a pool
20
+ */
21
+ export interface IRatioCalculationResult {
22
+ calculatedAmount: AssetAmount;
23
+ ratioAsFraction: Fraction;
24
+ display: string;
25
+ isDivisible: boolean;
26
+ belowMinimumRatio: boolean;
27
+ }
28
+
29
+ /**
30
+ * The amounts for a token pair
31
+ */
32
+ export type TPair = [bigint, bigint];
33
+
34
+ /**
35
+ * Get the share ratio as Fraction
36
+ * @param lp
37
+ * @param totalLp
38
+ * @returns
39
+ */
40
+ export const getShare = (lp: bigint, totalLp: bigint) =>
41
+ new Fraction(lp, totalLp);
@@ -0,0 +1,527 @@
1
+ import { SharedPoolMath } from "./index.js";
2
+ import { Fraction, type TFractionLike } from "@sundaeswap/fraction";
3
+
4
+ /**
5
+ * Validates that a given sum invariant (D) satisfies the liquidity invariant equation
6
+ * for the Stableswaps curve. This function checks if D is within the valid range by
7
+ * evaluating the invariant function at D and D+1.
8
+ *
9
+ * The liquidity invariant ensures that the curve equation is satisfied:
10
+ * 4A * 4xy * D + D^3 - (4xy * 4A * (x + y) + 4xy * D) should be <= 0 at D and > 0 at D+1
11
+ *
12
+ * @param {bigint} assetA - The reserve amount of asset A (already scaled by RESERVE_PRECISION).
13
+ * @param {bigint} assetB - The reserve amount of asset B (already scaled by RESERVE_PRECISION).
14
+ * @param {bigint} linearAmplification - The amplification coefficient for the pool.
15
+ * @param {bigint} newSumInvariant - The proposed sum invariant (D) to validate.
16
+ * @returns {boolean} True if the sum invariant satisfies the liquidity invariant equation, false otherwise.
17
+ */
18
+ export function liquidityInvariant(
19
+ assetA: bigint,
20
+ assetB: bigint,
21
+ linearAmplification: bigint,
22
+ newSumInvariant: bigint,
23
+ ) {
24
+ // 4 * A * 4 * (x*y) * D + D^3 - (4(x*y) * (4A(x + y) + D))
25
+ // 4A * 4xy * D + D^3 - (4xy * 4a * (x + y) + 4xy * D)
26
+ // 16Axy * D + D^3 - (16Axy * (x + y) + 4xy * D)
27
+ const four_a = 4n * linearAmplification;
28
+ const four_x_y = 4n * assetA * assetB;
29
+ const d_plus_one = newSumInvariant + 1n;
30
+ const d_cubed = newSumInvariant * newSumInvariant * newSumInvariant;
31
+ const d_plus_one_cubed = d_plus_one * d_plus_one * d_plus_one;
32
+ const x_plus_y = assetA + assetB;
33
+ const sixteen_a_x_y = four_a * four_x_y;
34
+ const sixteen_a_x_y_x_plus_y = sixteen_a_x_y * x_plus_y;
35
+ const f1 =
36
+ sixteen_a_x_y * newSumInvariant +
37
+ d_cubed -
38
+ (sixteen_a_x_y_x_plus_y + four_x_y * newSumInvariant);
39
+ const f2 =
40
+ sixteen_a_x_y * d_plus_one +
41
+ d_plus_one_cubed -
42
+ (sixteen_a_x_y_x_plus_y + four_x_y * d_plus_one);
43
+ return f1 <= 0n && f2 > 0n;
44
+ }
45
+
46
+ /**
47
+ * Precision factor for the amplification coefficient calculations.
48
+ * Used to scale the amplification factor for more precise arithmetic operations.
49
+ */
50
+ export const A_PRECISION: bigint = 200n;
51
+
52
+ /**
53
+ * Precision factor for reserve calculations in the Stableswaps curve.
54
+ * Reserves are multiplied by this value to maintain precision during calculations.
55
+ * This allows for accurate fractional calculations with integer arithmetic.
56
+ */
57
+ export const RESERVE_PRECISION: bigint = 1_000_000_000_000n;
58
+
59
+ /**
60
+ * Precision factor for fee calculations, representing basis points.
61
+ * A value of 10,000 means fees are calculated with 0.01% precision (1 basis point).
62
+ */
63
+ export const FEE_PRECISION: bigint = 10_000n;
64
+
65
+ /**
66
+ * Calculates the sum invariant (D) for a Stableswaps pool using Newton's method.
67
+ * The sum invariant represents the total value in the pool and is used to determine
68
+ * the fair exchange rate between assets.
69
+ *
70
+ * This function iteratively solves for D in the Stableswaps invariant equation:
71
+ * Ann * sum + D_p * 2 = Ann * D + D_p * 3
72
+ * where D_p = D^3 / (4 * x * y) and Ann = A * n^n (with n=2)
73
+ *
74
+ * The iteration continues until convergence (difference <= 1) or fails after 255 iterations.
75
+ *
76
+ * @param {bigint} a - The amplification coefficient for the pool (will be scaled by A_PRECISION).
77
+ * @param {bigint} x - The reserve amount of the first asset (will be scaled by RESERVE_PRECISION).
78
+ * @param {bigint} y - The reserve amount of the second asset (will be scaled by RESERVE_PRECISION).
79
+ * @returns {bigint} The calculated sum invariant (D) scaled by RESERVE_PRECISION.
80
+ * @throws {Error} If the amplification coefficient is not positive.
81
+ * @throws {Error} If convergence fails after 255 iterations.
82
+ */
83
+ export function getSumInvariant(a: bigint, x: bigint, y: bigint): bigint {
84
+ if (a <= 0n) {
85
+ throw new Error("Amplification coefficient must be positive.");
86
+ }
87
+ x = x * RESERVE_PRECISION;
88
+ y = y * RESERVE_PRECISION;
89
+ a = a * A_PRECISION;
90
+ const sum: bigint = x + y;
91
+ if (sum === 0n) {
92
+ return 0n;
93
+ }
94
+
95
+ let d = sum;
96
+ const ann = a * 2n;
97
+ for (let i = 0; i < 255; i++) {
98
+ const d_p = (d * d * d) / (4n * x * y);
99
+ const d_prev = d;
100
+
101
+ d =
102
+ (((ann * sum) / 100n + d_p * 2n) * d) /
103
+ (((ann - 100n) * d) / 100n + 3n * d_p);
104
+
105
+ if (d > d_prev) {
106
+ if (d - d_prev <= 1) {
107
+ if (liquidityInvariant(x, y, a / A_PRECISION, d)) {
108
+ return d;
109
+ } else {
110
+ return d - 1n;
111
+ }
112
+ }
113
+ } else {
114
+ if (d_prev - d <= 1) {
115
+ if (liquidityInvariant(x, y, a / A_PRECISION, d)) {
116
+ return d;
117
+ } else {
118
+ return d - 1n;
119
+ }
120
+ }
121
+ }
122
+ }
123
+ throw new Error("Failed to converge on D value after 255 iterations.");
124
+ }
125
+
126
+ /**
127
+ * Calculates the new Y reserve value given a new X reserve value and the sum invariant.
128
+ * This function uses Newton's method to iteratively solve for Y in the Stableswaps equation
129
+ * while maintaining the pool's invariant (D).
130
+ *
131
+ * The function solves: Y^2 + (sum + (D * A_PRECISION) / (2 * Ann) - D) * Y - c = 0
132
+ * where c is derived from D and the pool parameters.
133
+ *
134
+ * This is used during swaps to determine the output reserve after an input is added.
135
+ *
136
+ * @param {bigint} newX - The new reserve amount for asset X (will be scaled by RESERVE_PRECISION internally).
137
+ * @param {bigint} aRaw - The raw amplification coefficient for the pool (will be scaled by A_PRECISION).
138
+ * @param {bigint} sumInvariant - The pool's sum invariant (D), already scaled.
139
+ * @returns {bigint} The calculated Y reserve value scaled by RESERVE_PRECISION.
140
+ * @throws {Error} If convergence fails after 255 iterations.
141
+ */
142
+ export function getNewY(
143
+ newX: bigint,
144
+ aRaw: bigint,
145
+ sumInvariant: bigint,
146
+ ): bigint {
147
+ newX = newX * RESERVE_PRECISION;
148
+ const sum = newX;
149
+ let yPrev: bigint;
150
+ let c = sumInvariant;
151
+ const ann = aRaw * A_PRECISION * 2n;
152
+
153
+ c = (c * sumInvariant) / (newX * 2n);
154
+ c = (c * sumInvariant * A_PRECISION) / 2n;
155
+ c = c / (ann * 2n);
156
+ const b = sum + (sumInvariant * A_PRECISION) / 2n / ann;
157
+ let y = sumInvariant;
158
+ for (let i = 0; i < 255; i++) {
159
+ yPrev = y;
160
+ y = (y * y + c) / (y * 2n + b - sumInvariant);
161
+ if (y > yPrev) {
162
+ if (y - yPrev <= 1n) {
163
+ if (liquidityInvariant(newX, y, aRaw, sumInvariant)) {
164
+ return y;
165
+ } else {
166
+ return y + 1n;
167
+ }
168
+ }
169
+ } else {
170
+ if (yPrev - y <= 1n) {
171
+ if (liquidityInvariant(newX, y, aRaw, sumInvariant)) {
172
+ return y;
173
+ } else {
174
+ return y + 1n;
175
+ }
176
+ }
177
+ }
178
+ }
179
+ throw new Error("Failed to converge on y value after 255 iterations.");
180
+ }
181
+
182
+ /**
183
+ * Calculates the initial LP token amount for the first liquidity provision to a pool.
184
+ * This is used when bootstrapping a new pool with initial reserves of assets A and B.
185
+ *
186
+ * The LP tokens minted are derived from the sum invariant (D) divided by the reserve precision,
187
+ * effectively representing the pool's total value at inception.
188
+ *
189
+ * @param {bigint} a - The initial amount of token A being deposited.
190
+ * @param {bigint} b - The initial amount of token B being deposited.
191
+ * @param {bigint} laf - The linear amplification factor for the pool.
192
+ * @returns {bigint} The amount of LP tokens to mint for the first liquidity provision.
193
+ */
194
+ export const getFirstLp = (a: bigint, b: bigint, laf: bigint) =>
195
+ getSumInvariant(laf, a, b) / RESERVE_PRECISION;
196
+
197
+ /**
198
+ * Calculates the liquidity parameters for adding liquidity to a Stableswaps pool.
199
+ * This function supports mixed deposits where both assets can be deposited in any proportion.
200
+ *
201
+ * The calculation is based on the change in the sum invariant (D) before and after the deposit.
202
+ * LP tokens are minted proportionally to the increase in D relative to the old D value.
203
+ *
204
+ * TODO: Investigate way to optimize actual deposited amounts
205
+ *
206
+ * @param {bigint} a - The amount of token A to deposit.
207
+ * @param {bigint} b - The amount of token B to deposit.
208
+ * @param {bigint} aReserve - The current reserve of token A in the pool.
209
+ * @param {bigint} bReserve - The current reserve of token B in the pool.
210
+ * @param {bigint} totalLp - The total LP tokens for the pool before the deposit.
211
+ * @param {bigint} laf - The linear amplification factor of the pool.
212
+ * @throws {Error} If the pool doesn't have enough liquidity (both reserves are zero).
213
+ * @throws {Error} If both deposit amounts are zero.
214
+ * @returns {Object} An object containing:
215
+ * - nextTotalLp: The total LP tokens for the pool after the deposit.
216
+ * - generatedLp: The amount of LP tokens generated by the deposit.
217
+ * - shareAfterDeposit: The depositor's share of the pool after the deposit (as a Fraction).
218
+ * - aChange: Always 0n for Stableswaps (no refund needed).
219
+ * - bChange: Always 0n for Stableswaps (no refund needed).
220
+ * - actualDepositedA: The actual amount of A deposited (always equal to input a).
221
+ * - actualDepositedB: The actual amount of B deposited (always equal to input b).
222
+ */
223
+ export const calculateLiquidity = (
224
+ a: bigint,
225
+ b: bigint,
226
+ aReserve: bigint,
227
+ bReserve: bigint,
228
+ totalLp: bigint,
229
+ laf: bigint,
230
+ ) => {
231
+ if (aReserve === 0n && bReserve === 0n) {
232
+ throw new Error("Not enough pool liquidity");
233
+ }
234
+
235
+ if (a === 0n && b === 0n) {
236
+ throw new Error("Cannot use a deposit asset amount of 0");
237
+ }
238
+
239
+ const oldSumInvariant = getSumInvariant(laf, aReserve, bReserve);
240
+
241
+ const newSumInvariant = getSumInvariant(laf, aReserve + a, bReserve + b);
242
+
243
+ const newLpTokens =
244
+ ((newSumInvariant - oldSumInvariant) * totalLp) / oldSumInvariant;
245
+
246
+ const newTotalLpTokens = totalLp + newLpTokens;
247
+
248
+ return {
249
+ nextTotalLp: newTotalLpTokens,
250
+ generatedLp: newLpTokens,
251
+ shareAfterDeposit: SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),
252
+ aChange: 0n,
253
+ bChange: 0n,
254
+ actualDepositedA: a,
255
+ actualDepositedB: b,
256
+ };
257
+ };
258
+
259
+ /**
260
+ * Calculates the token amounts that a given LP token amount represents when withdrawing
261
+ * from a Stableswaps pool. The withdrawal is proportional to the LP tokens being redeemed
262
+ * relative to the total LP supply.
263
+ *
264
+ * This uses a simple linear proportion: amount = (lp * reserve) / totalLp for each asset.
265
+ *
266
+ * @param {bigint} lp - The amount of LP tokens being redeemed.
267
+ * @param {bigint} aReserve - The pool's current reserve amount of token A.
268
+ * @param {bigint} bReserve - The pool's current reserve amount of token B.
269
+ * @param {bigint} totalLp - The pool's total minted LP tokens currently in circulation.
270
+ * @returns {SharedPoolMath.TPair} A tuple [a, b] containing the amounts of tokens A and B to withdraw.
271
+ */
272
+ export const getTokensForLp = (
273
+ lp: bigint,
274
+ aReserve: bigint,
275
+ bReserve: bigint,
276
+ totalLp: bigint,
277
+ ): SharedPoolMath.TPair => [
278
+ new Fraction(lp * aReserve, totalLp).quotient,
279
+ new Fraction(lp * bReserve, totalLp).quotient,
280
+ ];
281
+
282
+ /**
283
+ * Represents the complete outcome of a swap operation in a Stableswaps pool.
284
+ * Contains all relevant information about the swap including amounts, fees, updated reserves,
285
+ * and price impact.
286
+ */
287
+ export type TSwapOutcome = {
288
+ /** The amount of input tokens being swapped */
289
+ input: bigint;
290
+ /** The amount of output tokens received (after all fees) */
291
+ output: bigint;
292
+ /** The portion of fees that goes to liquidity providers */
293
+ outputLpFee: bigint;
294
+ /** The portion of fees that goes to the protocol */
295
+ outputProtocolFee: bigint;
296
+ /** The input asset reserve amount after the swap */
297
+ nextInputReserve: bigint;
298
+ /** The output asset reserve amount after the swap (excluding protocol fees) */
299
+ nextOutputReserve: bigint;
300
+ /** The pool's sum invariant (D) after the swap */
301
+ nextSumInvariant: bigint;
302
+ /** The price impact of the swap as a fraction (difference between ideal and actual price) */
303
+ priceImpact: Fraction;
304
+ };
305
+
306
+ /**
307
+ * Calculates the output amount and all swap parameters for a given input amount in a Stableswaps pool.
308
+ * This function determines how many output tokens will be received for a given input, accounting for
309
+ * the Stableswaps curve, LP fees, and protocol fees.
310
+ *
311
+ * The calculation process:
312
+ * 1. Validates inputs and fees
313
+ * 2. Calculates the current sum invariant (D)
314
+ * 3. Determines the new Y value after adding input to X
315
+ * 4. Calculates raw output and applies fees (LP + protocol)
316
+ * 5. Computes price impact by comparing ideal vs actual execution price
317
+ *
318
+ * @param {bigint} input - The amount of input tokens to swap.
319
+ * @param {bigint} inputReserve - The current reserve amount of the input token in the pool.
320
+ * @param {bigint} outputReserve - The current reserve amount of the output token in the pool.
321
+ * @param {TFractionLike} fee - The liquidity provider fee as a fraction (e.g., 0.003 for 0.3%).
322
+ * @param {TFractionLike} protocolFee - The protocol fee as a fraction.
323
+ * @param {bigint} laf - The linear amplification factor of the pool.
324
+ * @param {boolean} [roundOutputUp] - Optional flag to round output up instead of down (default: false).
325
+ * @returns {TSwapOutcome} The complete swap outcome including output, fees, reserves, and price impact.
326
+ * @throws {Error} If input or reserves are not positive.
327
+ * @throws {Error} If fee is not in the range [0, 1).
328
+ * @throws {Error} If protocol fee is not in the range [0, 1).
329
+ * @throws {Error} If combined fee is greater than or equal to 1.
330
+ */
331
+ export const getSwapOutput = (
332
+ input: bigint,
333
+ inputReserve: bigint,
334
+ outputReserve: bigint,
335
+ fee: TFractionLike,
336
+ protocolFee: TFractionLike,
337
+ laf: bigint,
338
+ roundOutputUp?: boolean,
339
+ ): TSwapOutcome => {
340
+ if (input <= 0 || inputReserve <= 0 || outputReserve <= 0)
341
+ throw new Error("Input and reserves must be positive");
342
+
343
+ fee = Fraction.asFraction(fee);
344
+ if (fee.lt(Fraction.ZERO) || fee.gte(Fraction.ONE))
345
+ throw new Error("fee must be between 0 and 1");
346
+
347
+ protocolFee = Fraction.asFraction(protocolFee);
348
+ if (protocolFee.lt(Fraction.ZERO) || protocolFee.gte(Fraction.ONE))
349
+ throw new Error("protocolFee must be between 0 and 1");
350
+
351
+ const combinedFee = fee.add(protocolFee);
352
+ if (combinedFee.gte(Fraction.ONE))
353
+ throw new Error("Combined fee must be less than 1");
354
+ const sumInvariant = getSumInvariant(laf, inputReserve, outputReserve);
355
+ const nextInputReserve = inputReserve + input;
356
+ const newY = getNewY(nextInputReserve, laf, sumInvariant);
357
+
358
+ const deltaYPrec = outputReserve * RESERVE_PRECISION - newY;
359
+ const deltaY = new Fraction(deltaYPrec, RESERVE_PRECISION);
360
+ const totalFee = combinedFee
361
+ .multiply(FEE_PRECISION)
362
+ .multiply(deltaY.quotient)
363
+ .add(Fraction.asFraction(FEE_PRECISION - 1n))
364
+ .divide(FEE_PRECISION).quotient;
365
+ const totalProtocolFee = protocolFee
366
+ .multiply(totalFee)
367
+ .divide(combinedFee).quotient;
368
+ const totalLpFee = totalFee - totalProtocolFee;
369
+ const output = deltaY.subtract(totalFee);
370
+ const safeOutput = roundOutputUp
371
+ ? (output.numerator + output.denominator - 1n) / output.denominator
372
+ : output.quotient;
373
+ const nextOutputReserve = outputReserve - safeOutput - totalProtocolFee;
374
+
375
+ // PRICEIMPACT: "priceImpact" is slightly misleadingly named in the industry as a whole
376
+ // just by it's name, it would imply that it's the percentage difference between
377
+ // the current price and the price after the swap, but it's actually the percentage
378
+ // difference between the real price of your swap, and the price implied by the current
379
+ // reserves; We got this wrong in v1, but this aligns it with the industry standard
380
+ // Source: https://dailydefi.org/articles/price-impact-and-how-to-calculate/
381
+ const idealPrice = getPrice(inputReserve, outputReserve, laf);
382
+ const actualPrice = new Fraction(input, safeOutput);
383
+ const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
384
+ return {
385
+ input,
386
+ output: safeOutput,
387
+ outputLpFee: totalLpFee,
388
+ outputProtocolFee: totalProtocolFee,
389
+ nextInputReserve,
390
+ nextOutputReserve,
391
+ nextSumInvariant: getSumInvariant(laf, nextInputReserve, nextOutputReserve),
392
+ priceImpact,
393
+ };
394
+ };
395
+
396
+ /**
397
+ * Calculates the current price (exchange rate) of asset A in terms of asset B for a Stableswaps pool.
398
+ * The price is derived from the Stableswaps curve equation and takes into account the amplification factor.
399
+ *
400
+ * The calculation uses the formula:
401
+ * price = (xpA + (dR * aReserve) / bReserve) / (xpA + dR)
402
+ * where xpA = (Ann * aReserve) / A_PRECISION and dR is derived from the sum invariant
403
+ *
404
+ * @param {bigint} aReserve - The current reserve amount of asset A in the pool.
405
+ * @param {bigint} bReserve - The current reserve amount of asset B in the pool.
406
+ * @param {bigint} laf - The linear amplification factor of the pool.
407
+ * @returns {Fraction} The price of asset A in terms of asset B as a Fraction.
408
+ */
409
+ export function getPrice(
410
+ aReserve: bigint,
411
+ bReserve: bigint,
412
+ laf: bigint,
413
+ ): Fraction {
414
+ // dx_0 / dx_1 only, however can have any number of coins in pool
415
+ const ann = laf * 2n * A_PRECISION;
416
+ const sumInvariant =
417
+ getSumInvariant(laf, aReserve, bReserve) / RESERVE_PRECISION;
418
+ // D / n^n with n = 2
419
+ let dR = sumInvariant / 4n;
420
+ dR = (dR * sumInvariant) / aReserve;
421
+ dR = (dR * sumInvariant) / bReserve;
422
+ const xpA = (ann * aReserve) / A_PRECISION;
423
+ const p = new Fraction(xpA + (dR * aReserve) / bReserve, xpA + dR);
424
+ return p;
425
+ }
426
+
427
+ /**
428
+ * Calculates the required input amount and all swap parameters for a desired output amount in a Stableswaps pool.
429
+ * This is the reverse operation of getSwapOutput - given how much you want to receive, it determines
430
+ * how much you need to provide as input, accounting for fees and the Stableswaps curve.
431
+ *
432
+ * The calculation process:
433
+ * 1. Validates inputs, fees, and output constraints
434
+ * 2. Calculates raw output needed before fees
435
+ * 3. Determines the new X value to achieve the desired Y reduction
436
+ * 4. Calculates required input and separates LP and protocol fees
437
+ * 5. Computes price impact by comparing ideal vs actual execution price
438
+ *
439
+ * @param {bigint} output - The desired amount of output tokens to receive.
440
+ * @param {bigint} inputReserve - The current reserve amount of the input token in the pool.
441
+ * @param {bigint} outputReserve - The current reserve amount of the output token in the pool.
442
+ * @param {TFractionLike} fee - The liquidity provider fee as a fraction (e.g., 0.003 for 0.3%).
443
+ * @param {TFractionLike} protocolFee - The protocol fee as a fraction.
444
+ * @param {bigint} laf - The linear amplification factor of the pool.
445
+ * @returns {TSwapOutcome} The complete swap outcome including required input, fees, reserves, and price impact.
446
+ * @throws {Error} If output or reserves are not positive.
447
+ * @throws {Error} If output is greater than or equal to the output reserve.
448
+ * @throws {Error} If fee is not in the range [0, 1).
449
+ * @throws {Error} If protocol fee is not in the range [0, 1).
450
+ * @throws {Error} If combined fee is greater than or equal to 1.
451
+ */
452
+ export const getSwapInput = (
453
+ output: bigint,
454
+ inputReserve: bigint,
455
+ outputReserve: bigint,
456
+ fee: TFractionLike,
457
+ protocolFee: TFractionLike,
458
+ laf: bigint,
459
+ ): TSwapOutcome => {
460
+ if (output <= 0 || inputReserve <= 0 || outputReserve <= 0)
461
+ throw new Error("Output and reserves must be positive");
462
+
463
+ if (output >= outputReserve)
464
+ throw new Error("Output must be less than output reserve");
465
+
466
+ fee = Fraction.asFraction(fee);
467
+ if (fee.lt(Fraction.ZERO) || fee.gte(Fraction.ONE))
468
+ throw new Error("fee must be [0,1)");
469
+
470
+ protocolFee = Fraction.asFraction(protocolFee);
471
+ if (protocolFee.lt(Fraction.ZERO) || protocolFee.gte(Fraction.ONE))
472
+ throw new Error("protocolFee must be between 0 and 1");
473
+
474
+ const combinedFee = fee.add(protocolFee);
475
+ if (combinedFee.gte(Fraction.ONE))
476
+ throw new Error("Combined fee must be less than 1");
477
+
478
+ // output = rawOutput * (1-fee)
479
+ // rawOutput = output / (1-fee)
480
+ const rawOutputF = Fraction.asFraction(output).divide(
481
+ Fraction.ONE.sub(combinedFee),
482
+ );
483
+ const rawOutput =
484
+ (rawOutputF.numerator + rawOutputF.denominator - 1n) /
485
+ rawOutputF.denominator;
486
+ const sumInvariant = getSumInvariant(laf, inputReserve, outputReserve);
487
+ const newX = getNewY(outputReserve - rawOutput, laf, sumInvariant);
488
+ const input =
489
+ (newX - inputReserve * RESERVE_PRECISION + RESERVE_PRECISION - 1n) /
490
+ RESERVE_PRECISION;
491
+
492
+ const totalFee =
493
+ (combinedFee.multiply(FEE_PRECISION).quotient * rawOutput +
494
+ FEE_PRECISION -
495
+ 1n) /
496
+ FEE_PRECISION;
497
+ const totalProtocolFee = protocolFee
498
+ .multiply(totalFee)
499
+ .divide(combinedFee).quotient;
500
+
501
+ const totalLpFee = totalFee - totalProtocolFee;
502
+
503
+ const nextInputReserve = inputReserve + input;
504
+ const nextOutputReserve = outputReserve - output - totalProtocolFee;
505
+
506
+ // See PRICEIMPACT
507
+ const idealPrice = getPrice(inputReserve, outputReserve, laf);
508
+ const actualPrice = new Fraction(input, output);
509
+ const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));
510
+
511
+ const nextSumInvariant = getSumInvariant(
512
+ laf,
513
+ nextInputReserve,
514
+ nextOutputReserve,
515
+ );
516
+
517
+ return {
518
+ input,
519
+ output,
520
+ outputLpFee: totalLpFee,
521
+ outputProtocolFee: totalProtocolFee,
522
+ nextInputReserve,
523
+ nextOutputReserve,
524
+ priceImpact,
525
+ nextSumInvariant,
526
+ };
527
+ };
@@ -4,14 +4,16 @@ import { AssetAmount } from "@sundaeswap/asset";
4
4
  import {
5
5
  getSwapOutput,
6
6
  getSwapInput,
7
- TPair,
8
- TRatioDirection,
9
- IRatioCalculationAsset,
10
- IRatioCalculationResult,
11
7
  getSwapRatio,
12
8
  } from "../ConstantProductPool.js";
13
9
  import { getFirstLp } from "../ConstantProductPool.js";
14
10
  import { calculateLiquidity } from "../ConstantProductPool.js";
11
+ import {
12
+ IRatioCalculationAsset,
13
+ IRatioCalculationResult,
14
+ TPair,
15
+ TRatioDirection,
16
+ } from "../SharedPoolMath.js";
15
17
 
16
18
  describe("getSwapOutput", () => {
17
19
  const zeroThreePct = new Fraction(3, 1000);