@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
@@ -0,0 +1,529 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.pinnedDepositFromAnchor = exports.invariantG = exports.invariantF = exports.getSwapOutput = exports.getSwapInput = exports.getRawSwap = exports.getPrice = exports.getD = exports.calculatePinnedDeposit = exports.calculateLiquidity = exports.CALC_PRECISION = void 0;
7
+ var _asset = require("@sundaeswap/asset");
8
+ var _fraction = require("@sundaeswap/fraction");
9
+ var _index = require("./index.js");
10
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
11
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
12
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
13
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
14
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
15
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
16
+ /**
17
+ * THE V4 STABLESWAP INVARIANT MODULE — NOT THE V3 "STABLESWAPS" CONTRACT.
18
+ *
19
+ * Two different things in this SDK carry the word "stableswap". Keep them
20
+ * apart:
21
+ *
22
+ * - `StableSwapsPool` / `EContractVersion.Stableswaps` is the **v3** stableswap
23
+ * contract. It is a whole contract version with its own datum builder and
24
+ * transaction builder. It stores `D` in the pool datum and has no per-asset
25
+ * rates.
26
+ * - `V4StableswapPool` / `EPoolCurve.V4Stableswap` (this file) is a **v4
27
+ * invariant module**. It is one curve among several a v4 pool can bind, next
28
+ * to constant product, constant sum and concentrated liquidity. It stores no
29
+ * `D` and carries per-asset integer `rates`.
30
+ *
31
+ * The amplification `A` is the ONE thing they share: the same parameter on the
32
+ * same scale, carried by the same `linearAmplificationFactor` field, with each
33
+ * implementation applying its own internal scaling. Everything else is
34
+ * different — do not pass one's reserves, rates or `D` to the other.
35
+ *
36
+ * The curve, on rated and scaled reserves `x = r_a·rate_a·P` and
37
+ * `y = r_b·rate_b·P` with `P = calc_precision = 10^12` and `A` the linear
38
+ * amplification:
39
+ *
40
+ * 4A(x + y) + D = 4AD + D³ / (4xy)
41
+ *
42
+ * `D` is the largest integer that satisfies it. Neither `D` nor a swap output
43
+ * can be computed on-chain, because both need Newton's method. The scooper
44
+ * computes them and the module checks that each supplied integer is the unique
45
+ * one that solves the invariant. This file is the off-chain twin of
46
+ * `lib/modules/ss_math.ak` and `lib/modules/ss_check.ak` in the sundae-v4
47
+ * repository — those are the source of truth; keep this in lockstep with them.
48
+ */
49
+
50
+ /** `ss_math.calc_precision`: the scale applied to reserves before they enter the invariant. */
51
+ var CALC_PRECISION = exports.CALC_PRECISION = 1000000000000n;
52
+
53
+ /** Newton iteration cap, matching the reference implementation. */
54
+ var NEWTON_MAX_ITERATIONS = 255;
55
+
56
+ /** Bound on the fix-up walk of the reverse swap. The closed form lands within a few units. */
57
+ var CORRECTION_MAX_STEPS = 256;
58
+
59
+ /**
60
+ * Holds the calculated outcome of a v4 stableswap swap. Mirrors
61
+ * {@link ConstantProductPool.TSwapOutcome} so it flows through the same generic
62
+ * swap-outcome consumers.
63
+ *
64
+ * `lpFee` is denominated in the **output** asset, not the input asset. The
65
+ * stableswap fee is taken off the gross output (`fee = ceil(gross · feeRate)`),
66
+ * unlike constant product and constant sum which take the fee off the input.
67
+ * The v3 `StableSwapsPool` does the same.
68
+ */
69
+
70
+ // ─── Integer helpers ────────────────────────────────────────────────────────
71
+
72
+ /** Plutus `divideInteger`: floor toward −∞. */
73
+ var floorDiv = function floorDiv(a, b) {
74
+ var q = a / b;
75
+ var r = a % b;
76
+ return r !== 0n && r < 0n !== b < 0n ? q - 1n : q;
77
+ };
78
+
79
+ /** ceil(a / b) with the same sign convention as {@link floorDiv}. */
80
+ var ceilDiv = function ceilDiv(a, b) {
81
+ return -floorDiv(-a, b);
82
+ };
83
+ var asFeeParts = function asFeeParts(fee) {
84
+ var f = _fraction.Fraction.asFraction(fee);
85
+ if (f.lt(_fraction.Fraction.ZERO) || f.gte(_fraction.Fraction.ONE)) throw new Error("fee must be in [0, 1)");
86
+ return [BigInt(f.numerator), BigInt(f.denominator)];
87
+ };
88
+
89
+ // ─── Invariant polynomials (`ss_math.ak`) ───────────────────────────────────
90
+
91
+ /**
92
+ * `f(D)` from the on-chain `liquidity_invariant`. It is ≤ 0 when `D` is at or
93
+ * below the curve. All arguments are rated and scaled.
94
+ */
95
+ var invariantF = exports.invariantF = function invariantF(x, y, amp, d) {
96
+ var sixteenAxy = 16n * amp * x * y;
97
+ return sixteenAxy * d + d * d * d - (sixteenAxy * (x + y) + 4n * x * y * d);
98
+ };
99
+
100
+ /**
101
+ * `g(y)` from the on-chain `exchange_invariant`. It is ≥ 0 when the pool keeps
102
+ * enough of the taken asset. `g` is symmetric in `x` and `y`, which is what
103
+ * lets {@link getSwapInput} reuse the same solver in the other direction.
104
+ */
105
+ var invariantG = exports.invariantG = function invariantG(x, y, amp, d) {
106
+ var fourXy = 4n * x * y;
107
+ return fourXy * (4n * amp * (x + y) + d) - fourXy * 4n * amp * d - d * d * d;
108
+ };
109
+
110
+ // ─── D ──────────────────────────────────────────────────────────────────────
111
+
112
+ /** The ±1 fix-up that turns a Newton result into the exact largest `D`. */
113
+ var fixD = function fixD(x, y, amp, d0) {
114
+ var d = d0;
115
+ while (invariantF(x, y, amp, d) > 0n) d -= 1n;
116
+ while (invariantF(x, y, amp, d + 1n) <= 0n) d += 1n;
117
+ return d;
118
+ };
119
+
120
+ /**
121
+ * The sum invariant `D` of a two-asset v4 stableswap pool: the largest integer
122
+ * that satisfies the curve on the rated, scaled reserves. Newton from
123
+ * `D = x + y`, then a ±1 fix-up.
124
+ *
125
+ * `D` carries the `rate · CALC_PRECISION` scale — it is not a token amount.
126
+ *
127
+ * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.
128
+ * @param aReserve The pool's reserve of asset A, in token units.
129
+ * @param bReserve The pool's reserve of asset B, in token units.
130
+ * @param rateA The pool's rate for asset A (from the stableswap config).
131
+ * @param rateB The pool's rate for asset B.
132
+ */
133
+ var getD = exports.getD = function getD(amp, aReserve, bReserve) {
134
+ var rateA = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1n;
135
+ var rateB = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1n;
136
+ if (amp <= 0n) throw new Error("amplification must be positive");
137
+ if (aReserve < 0n || bReserve < 0n) throw new Error("reserves must be non-negative");
138
+ if (rateA <= 0n || rateB <= 0n) throw new Error("rates must be positive");
139
+ var xs = aReserve * rateA * CALC_PRECISION;
140
+ var ys = bReserve * rateB * CALC_PRECISION;
141
+ var sum = xs + ys;
142
+ // An empty pool has no invariant to solve; `D` is zero by definition.
143
+ if (sum === 0n) return 0n;
144
+ // Exactly one empty reserve is a different case, and it has no answer: the
145
+ // Newton step divides by `4·xs·ys`, which is zero here. The chain never
146
+ // reaches this state — Create requires both reserves positive, and the
147
+ // exchange invariant leaves at least one unit on the output side — but this
148
+ // is a client library, so it reports the bad input instead of faulting on a
149
+ // native division by zero.
150
+ if (xs === 0n || ys === 0n) {
151
+ throw new Error("getD: a stableswap pool cannot hold exactly one empty reserve; D is undefined there");
152
+ }
153
+ var ann = 4n * amp;
154
+ var d = sum;
155
+ for (var i = 0; i < NEWTON_MAX_ITERATIONS; i++) {
156
+ var dP = floorDiv(d * d * d, 4n * xs * ys);
157
+ var dNext = floorDiv((ann * sum + 2n * dP) * d, (ann - 1n) * d + 3n * dP);
158
+ var diff = dNext > d ? dNext - d : d - dNext;
159
+ d = dNext;
160
+ if (diff <= 1n) return fixD(xs, ys, amp, d);
161
+ }
162
+ throw new Error("getD: reached the Newton iteration cap");
163
+ };
164
+
165
+ // ─── The exchange solver ────────────────────────────────────────────────────
166
+
167
+ /**
168
+ * The smallest scaled `y` with `g(xs, y) ≥ 0` at the pre-swap `d`: the least
169
+ * the pool may keep of the counterparty asset and still sit on the curve.
170
+ * Newton on `y`, then a walk to the exact integer — the walk leaves `y` with
171
+ * `g(y) ≥ 0` and `g(y − 1) < 0`, so it is the boundary and not merely a valid
172
+ * point.
173
+ *
174
+ * Read the direction carefully, because the two framings invert. A caller
175
+ * turning this into an output computes `raw = Y − y`, so the SMALLEST `y` is
176
+ * the LARGEST output the invariant admits. It is still not generous: `y` is a
177
+ * ceiling on the exact real-valued requirement, so `raw` is at or below the
178
+ * exact output. Most the curve allows, never more than it allows.
179
+ *
180
+ * Both swap directions use this: `g` is symmetric, so solving for the
181
+ * counterparty reserve answers "what must the other side hold" whichever side
182
+ * is given.
183
+ */
184
+ var solveCounterparty = function solveCounterparty(amp, d, xs) {
185
+ if (xs <= 0n) throw new Error("solveCounterparty: the given side must be positive");
186
+ var ann = 4n * amp;
187
+ // n = 2: c = D³ / (4·x·Ann), b = x + D / Ann. Evaluated in the same order as
188
+ // the Aiken source so the intermediate floors match.
189
+ var c = floorDiv(floorDiv(d * d, 2n * xs) * d, 2n * ann);
190
+ var b = xs + floorDiv(d, ann);
191
+ var y = d;
192
+ var converged = false;
193
+ for (var i = 0; i < NEWTON_MAX_ITERATIONS; i++) {
194
+ var yNext = floorDiv(y * y + c, 2n * y + b - d);
195
+ var diff = yNext > y ? yNext - y : y - yNext;
196
+ y = yNext;
197
+ if (diff <= 1n) {
198
+ converged = true;
199
+ break;
200
+ }
201
+ }
202
+ if (!converged) throw new Error("solveCounterparty: reached the Newton iteration cap");
203
+ while (invariantG(xs, y, amp, d) < 0n) y += 1n;
204
+ while (invariantG(xs, y - 1n, amp, d) >= 0n) y -= 1n;
205
+ return y;
206
+ };
207
+
208
+ /**
209
+ * The raw swap output: the scaled, pre-fee amount the curve releases when the
210
+ * given reserve becomes `inAfter` and the taken reserve starts at `outBefore`,
211
+ * at the pre-swap `d`. It is the largest such amount the exchange invariant
212
+ * admits — one unit more leaves the pool below the curve — and it is at or
213
+ * below the exact real-valued output, so it never over-quotes.
214
+ *
215
+ * The result carries the `rate · CALC_PRECISION` scale. Divide by
216
+ * `rateOut · CALC_PRECISION` to get the gross output in token units.
217
+ *
218
+ * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.
219
+ * @param d The pre-swap sum invariant, from {@link getD}.
220
+ * @param inAfter The given asset's reserve after the input arrives, in token units.
221
+ * @param outBefore The taken asset's reserve before the swap, in token units.
222
+ * @param rateIn The pool's rate for the given asset.
223
+ * @param rateOut The pool's rate for the taken asset.
224
+ */
225
+ var getRawSwap = exports.getRawSwap = function getRawSwap(amp, d, inAfter, outBefore) {
226
+ var rateIn = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1n;
227
+ var rateOut = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 1n;
228
+ if (amp <= 0n) throw new Error("amplification must be positive");
229
+ if (d <= 0n) throw new Error("the sum invariant must be positive");
230
+ if (inAfter <= 0n || outBefore <= 0n) throw new Error("reserves must be positive");
231
+ if (rateIn <= 0n || rateOut <= 0n) throw new Error("rates must be positive");
232
+ var xs = inAfter * rateIn * CALC_PRECISION;
233
+ return outBefore * rateOut * CALC_PRECISION - solveCounterparty(amp, d, xs);
234
+ };
235
+
236
+ // ─── Marginal price ─────────────────────────────────────────────────────────
237
+
238
+ /**
239
+ * The marginal price of the curve at the current reserves, as input units per
240
+ * output unit. Differentiating the invariant at fixed `D` gives
241
+ *
242
+ * −dy/dx = (16A·x²y² + D³·y) / (16A·x²y² + D³·x)
243
+ *
244
+ * in scaled value units, which converts to token units through the rates. At a
245
+ * balanced pool (`x = y`) it reduces to `rateOut / rateIn`, the par price.
246
+ */
247
+ var marginalInputPerOutput = function marginalInputPerOutput(amp, xs, ys, d, rateIn, rateOut) {
248
+ var common = 16n * amp * xs * xs * ys * ys;
249
+ var cube = d * d * d;
250
+ return new _fraction.Fraction(rateOut * (common + cube * xs), rateIn * (common + cube * ys));
251
+ };
252
+
253
+ /**
254
+ * The pool's marginal price as raw units of asset A per raw unit of asset B.
255
+ * Use it where a constant-product pool would use the reserve ratio: for a
256
+ * stableswap pool the reserve ratio is not the price, because the curve holds
257
+ * the price near par across a wide band of ratios.
258
+ *
259
+ * The result is in raw (undecimalized) units. Adjust for the two assets'
260
+ * decimals before display.
261
+ */
262
+ var getPrice = exports.getPrice = function getPrice(amp, aReserve, bReserve) {
263
+ var rateA = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1n;
264
+ var rateB = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1n;
265
+ if (aReserve <= 0n || bReserve <= 0n) throw new Error("reserves must be positive");
266
+ var d = getD(amp, aReserve, bReserve, rateA, rateB);
267
+ var xs = aReserve * rateA * CALC_PRECISION;
268
+ var ys = bReserve * rateB * CALC_PRECISION;
269
+ // A per B: asset B is the output side of the derivative.
270
+ return marginalInputPerOutput(amp, xs, ys, d, rateA, rateB);
271
+ };
272
+
273
+ // ─── Swap output ────────────────────────────────────────────────────────────
274
+
275
+ /**
276
+ * Calculate the swap outcome for a v4 stableswap pool.
277
+ *
278
+ * The sequence the chain enforces (`ss_check.ak`, tag 3):
279
+ *
280
+ * 1. `D` is derived from the pre-swap reserves at the pool's rates.
281
+ * 2. `raw` is the LARGEST scaled output the exchange invariant admits at that
282
+ * `D`, with the input already added to the given reserve. The solver pins
283
+ * the pool's remaining taken reserve `y` to the SMALLEST integer that still
284
+ * satisfies the invariant, and `raw = outBefore·rateOut·P − y`, so the two
285
+ * statements are the same one: least reserve kept, most output released.
286
+ * 3. `gross = floor(raw / (rateOut · CALC_PRECISION))` is the output in token units.
287
+ * 4. `fee = ceil(gross · feeRate)` stays in the pool.
288
+ * 5. The trader receives `gross − fee`.
289
+ *
290
+ * Every rounding step favours the pool, never the trader: `y` is a ceiling on
291
+ * the exact reserve the curve requires, `gross` floors to whole tokens, and the
292
+ * fee ceilings. A trader is never quoted more than the chain will pay.
293
+ *
294
+ * @param outputMetadata Metadata for the **taken** asset. The fee is denominated in it.
295
+ * @param input The amount of the given asset being swapped.
296
+ * @param inputReserve The pool's reserve of the given asset.
297
+ * @param outputReserve The pool's reserve of the taken asset.
298
+ * @param rateIn The pool's rate for the given asset (from the stableswap config).
299
+ * @param rateOut The pool's rate for the taken asset.
300
+ * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.
301
+ * @param fee The swap fee rate, applied to the gross output.
302
+ * @returns The swap details in the shared {@link TSwapOutcome} shape.
303
+ */
304
+ var getSwapOutput = exports.getSwapOutput = function getSwapOutput(outputMetadata, input, inputReserve, outputReserve, rateIn, rateOut, amp, fee) {
305
+ if (input <= 0n || inputReserve <= 0n || outputReserve <= 0n) throw new Error("Input and reserves must be positive");
306
+ if (rateIn <= 0n || rateOut <= 0n) throw new Error("Rates must be positive");
307
+ if (amp <= 0n) throw new Error("Amplification must be positive");
308
+ var _asFeeParts = asFeeParts(fee),
309
+ _asFeeParts2 = _slicedToArray(_asFeeParts, 2),
310
+ feeNum = _asFeeParts2[0],
311
+ feeDen = _asFeeParts2[1];
312
+ var d = getD(amp, inputReserve, outputReserve, rateIn, rateOut);
313
+ var raw = getRawSwap(amp, d, inputReserve + input, outputReserve, rateIn, rateOut);
314
+ var gross = floorDiv(raw, rateOut * CALC_PRECISION);
315
+ var lpFee = ceilDiv(gross * feeNum, feeDen);
316
+ var output = gross - lpFee;
317
+ if (output <= 0n) throw new Error("Swap yields no output after the fee; raise the input");
318
+ var nextInputReserve = inputReserve + input;
319
+ var nextOutputReserve = outputReserve - output;
320
+
321
+ // Price impact against the pool's marginal price before the swap, the same
322
+ // definition concentrated liquidity uses. Constant sum measures against its
323
+ // par price instead, because a constant-sum pool has no other price. A
324
+ // stableswap pool does: its marginal price moves with the reserve ratio, so
325
+ // measuring against par would report the pool's standing imbalance as this
326
+ // trade's impact. The fee is excluded so the number is curve slippage only.
327
+ var xs = inputReserve * rateIn * CALC_PRECISION;
328
+ var ys = outputReserve * rateOut * CALC_PRECISION;
329
+ var idealPrice = marginalInputPerOutput(amp, xs, ys, d, rateIn, rateOut);
330
+ var actualPrice = new _fraction.Fraction(input, gross);
331
+ var priceImpact = _fraction.Fraction.ONE.subtract(idealPrice.divide(actualPrice));
332
+ return {
333
+ input: input,
334
+ output: output,
335
+ lpFee: new _asset.AssetAmount(lpFee, outputMetadata),
336
+ nextInputReserve: nextInputReserve,
337
+ nextOutputReserve: nextOutputReserve,
338
+ priceImpact: priceImpact
339
+ };
340
+ };
341
+
342
+ // ─── Swap input (the reverse) ───────────────────────────────────────────────
343
+
344
+ /**
345
+ * Calculate the minimal input that buys a given output — the inverse of
346
+ * {@link getSwapOutput}.
347
+ *
348
+ * The steps:
349
+ *
350
+ * 1. Invert the fee: the smallest gross output that nets `output` after
351
+ * `ceil(gross · feeRate)` is `ceil(output · feeDen / (feeDen − feeNum))`.
352
+ * 2. Turn that gross into the scaled reserve the pool may keep of the taken
353
+ * asset.
354
+ * 3. Solve the exchange invariant in the other direction for the given
355
+ * reserve that supports it. `g` is symmetric, so this is the same solver.
356
+ * 4. Convert to token units and walk down to the minimum, which absorbs the
357
+ * integer rounding of step 3.
358
+ *
359
+ * @param outputMetadata Metadata for the **taken** asset. The fee is denominated in it.
360
+ * @param output The wanted amount of the taken asset.
361
+ * @param inputReserve The pool's reserve of the given asset.
362
+ * @param outputReserve The pool's reserve of the taken asset.
363
+ * @param rateIn The pool's rate for the given asset (from the stableswap config).
364
+ * @param rateOut The pool's rate for the taken asset.
365
+ * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.
366
+ * @param fee The swap fee rate, applied to the gross output.
367
+ * @returns The swap details in the shared {@link TSwapOutcome} shape.
368
+ */
369
+ var getSwapInput = exports.getSwapInput = function getSwapInput(outputMetadata, output, inputReserve, outputReserve, rateIn, rateOut, amp, fee) {
370
+ if (output <= 0n || inputReserve <= 0n || outputReserve <= 0n) throw new Error("Output and reserves must be positive");
371
+ if (rateIn <= 0n || rateOut <= 0n) throw new Error("Rates must be positive");
372
+ if (amp <= 0n) throw new Error("Amplification must be positive");
373
+ if (output >= outputReserve) throw new Error("Output must be below the output reserve");
374
+ var _asFeeParts3 = asFeeParts(fee),
375
+ _asFeeParts4 = _slicedToArray(_asFeeParts3, 2),
376
+ feeNum = _asFeeParts4[0],
377
+ feeDen = _asFeeParts4[1];
378
+
379
+ // 1. Smallest gross whose post-fee remainder reaches `output`.
380
+ // gross − ceil(gross·n/d) = floor(gross·(d−n)/d), which is ≥ output
381
+ // exactly when gross ≥ ceil(output·d / (d−n)).
382
+ var grossMin = ceilDiv(output * feeDen, feeDen - feeNum);
383
+ if (grossMin >= outputReserve) throw new Error("Output is not reachable: the fee pushes it past the reserve");
384
+ var d = getD(amp, inputReserve, outputReserve, rateIn, rateOut);
385
+ var scaleIn = rateIn * CALC_PRECISION;
386
+ var scaleOut = rateOut * CALC_PRECISION;
387
+
388
+ // 2. The most the pool may keep of the taken asset and still pay `grossMin`.
389
+ var yTarget = (outputReserve - grossMin) * scaleOut;
390
+ if (yTarget <= 0n) throw new Error("Output is not reachable within the pool's reserves");
391
+
392
+ // 3. + 4. The scaled given reserve that supports it, then token units.
393
+ var xNeeded = solveCounterparty(amp, d, yTarget);
394
+ var xBefore = inputReserve * scaleIn;
395
+ var input = ceilDiv(xNeeded - xBefore, scaleIn);
396
+ if (input < 1n) input = 1n;
397
+ var grossOf = function grossOf(dx) {
398
+ return floorDiv(getRawSwap(amp, d, inputReserve + dx, outputReserve, rateIn, rateOut), scaleOut);
399
+ };
400
+ var steps = 0;
401
+ while (grossOf(input) < grossMin) {
402
+ input += 1n;
403
+ if (++steps > CORRECTION_MAX_STEPS) throw new Error("getSwapInput: the correction walk did not converge");
404
+ }
405
+ while (input > 1n && grossOf(input - 1n) >= grossMin) {
406
+ input -= 1n;
407
+ if (++steps > CORRECTION_MAX_STEPS) throw new Error("getSwapInput: the correction walk did not converge");
408
+ }
409
+ var gross = grossOf(input);
410
+ var lpFee = ceilDiv(gross * feeNum, feeDen);
411
+ var nextInputReserve = inputReserve + input;
412
+ var nextOutputReserve = outputReserve - output;
413
+ var xs = xBefore;
414
+ var ys = outputReserve * scaleOut;
415
+ var idealPrice = marginalInputPerOutput(amp, xs, ys, d, rateIn, rateOut);
416
+ var actualPrice = new _fraction.Fraction(input, gross);
417
+ var priceImpact = _fraction.Fraction.ONE.subtract(idealPrice.divide(actualPrice));
418
+ return {
419
+ input: input,
420
+ output: output,
421
+ lpFee: new _asset.AssetAmount(lpFee, outputMetadata),
422
+ nextInputReserve: nextInputReserve,
423
+ nextOutputReserve: nextOutputReserve,
424
+ priceImpact: priceImpact
425
+ };
426
+ };
427
+
428
+ // ─── Deposits ───────────────────────────────────────────────────────────────
429
+
430
+ /**
431
+ * The deposit target a holder of `offered` can cover, and everything pinned to
432
+ * it. This is the target-pinned rule the v4 module enforces (`ss_check.ak`,
433
+ * tag 6), and it is the same shape constant sum uses, stated on `D` instead of
434
+ * on the value sum `V`:
435
+ *
436
+ * - the fill declares a `D` delta `t`;
437
+ * - every reserve moves by `ceil(r_i · t / D_before)`;
438
+ * - `total_lp` becomes `floor(lp_before · (D_before + t) / D_before)`.
439
+ *
440
+ * The largest `t` a holder can cover is capped by the scarcest offered asset,
441
+ * `t = min_i floor(offered_i · D_before / r_i)`. Anything above the pinned
442
+ * deltas is refunded. Every pool asset must be offered, or `t` is zero and the
443
+ * deposit can never fill.
444
+ *
445
+ * The rates do not enter the deltas: a proportional move is proportional in
446
+ * any units. They enter only through `D`.
447
+ */
448
+ var calculatePinnedDeposit = exports.calculatePinnedDeposit = function calculatePinnedDeposit(offered, reserves, totalLp, d) {
449
+ if (offered.length !== reserves.length) throw new Error("offered and reserves must be aligned");
450
+ if (totalLp <= 0n) throw new Error("Not enough pool liquidity");
451
+ if (d <= 0n) throw new Error("Pool sum invariant is zero");
452
+ if (offered.some(function (o) {
453
+ return o < 0n;
454
+ })) throw new Error("Deposit amounts must be non-negative");
455
+ var t;
456
+ for (var i = 0; i < offered.length; i++) {
457
+ if (reserves[i] <= 0n) continue;
458
+ var cap = floorDiv(offered[i] * d, reserves[i]);
459
+ t = t === undefined || cap < t ? cap : t;
460
+ }
461
+ if (t === undefined || t <= 0n) throw new Error("A stableswap deposit must offer every pool asset in proportion (asymmetric deposits are disallowed on-chain)");
462
+ var deltas = reserves.map(function (r) {
463
+ return ceilDiv(r * t, d);
464
+ });
465
+ var nextTotalLp = floorDiv(totalLp * (d + t), d);
466
+ var generatedLp = nextTotalLp - totalLp;
467
+ if (generatedLp <= 0n) throw new Error("Deposit mints zero LP");
468
+ return {
469
+ targetDeltaD: t,
470
+ deltas: deltas,
471
+ generatedLp: generatedLp,
472
+ nextTotalLp: nextTotalLp,
473
+ shareAfterDeposit: _index.SharedPoolMath.getShare(generatedLp, nextTotalLp)
474
+ };
475
+ };
476
+
477
+ /**
478
+ * Calculate the deposit parameters for a two-asset v4 stableswap pool through
479
+ * the target-pinned rule (see {@link calculatePinnedDeposit}). Surplus above
480
+ * the pinned deltas comes back as `aChange` / `bChange`, the way the scoop
481
+ * refunds it on-chain.
482
+ *
483
+ * @param a The amount of token A to deposit.
484
+ * @param b The amount of token B to deposit.
485
+ * @param aReserve The pool's reserve of token A.
486
+ * @param bReserve The pool's reserve of token B.
487
+ * @param totalLp The pool's total LP supply before the deposit.
488
+ * @param rateA The pool's rate for token A (from the stableswap config).
489
+ * @param rateB The pool's rate for token B.
490
+ * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.
491
+ */
492
+ var calculateLiquidity = exports.calculateLiquidity = function calculateLiquidity(a, b, aReserve, bReserve, totalLp, rateA, rateB, amp) {
493
+ if (aReserve <= 0n || bReserve <= 0n) throw new Error("Not enough pool liquidity");
494
+ var d = getD(amp, aReserve, bReserve, rateA, rateB);
495
+ var _calculatePinnedDepos = calculatePinnedDeposit([a, b], [aReserve, bReserve], totalLp, d),
496
+ deltas = _calculatePinnedDepos.deltas,
497
+ generatedLp = _calculatePinnedDepos.generatedLp,
498
+ nextTotalLp = _calculatePinnedDepos.nextTotalLp,
499
+ shareAfterDeposit = _calculatePinnedDepos.shareAfterDeposit;
500
+ return {
501
+ nextTotalLp: nextTotalLp,
502
+ generatedLp: generatedLp,
503
+ shareAfterDeposit: shareAfterDeposit,
504
+ aChange: a - deltas[0],
505
+ bChange: b - deltas[1],
506
+ actualDepositedA: deltas[0],
507
+ actualDepositedB: deltas[1]
508
+ };
509
+ };
510
+
511
+ /**
512
+ * The per-asset amounts a pinned deposit needs when the user anchors on one
513
+ * asset's amount: `t` from the anchor (`floor(anchor · D / r_anchor)`), every
514
+ * other delta ceil-pinned to it. Drives proportional auto-fill in deposit
515
+ * forms.
516
+ */
517
+ var pinnedDepositFromAnchor = exports.pinnedDepositFromAnchor = function pinnedDepositFromAnchor(anchorIndex, anchorAmount, reserves, d) {
518
+ if (anchorIndex < 0 || anchorIndex >= reserves.length) throw new Error("anchor index is out of range");
519
+ if (reserves[anchorIndex] <= 0n) throw new Error("anchor asset has no reserve");
520
+ if (d <= 0n) throw new Error("Pool sum invariant is zero");
521
+ if (anchorAmount <= 0n) return reserves.map(function () {
522
+ return 0n;
523
+ });
524
+ var t = floorDiv(anchorAmount * d, reserves[anchorIndex]);
525
+ return reserves.map(function (r, i) {
526
+ return i === anchorIndex ? anchorAmount : ceilDiv(r * t, d);
527
+ });
528
+ };
529
+ //# sourceMappingURL=V4StableswapPool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"V4StableswapPool.js","names":["_asset","require","_fraction","_index","_slicedToArray","r","e","_arrayWithHoles","_iterableToArrayLimit","_unsupportedIterableToArray","_nonIterableRest","TypeError","a","_arrayLikeToArray","t","toString","call","slice","constructor","name","Array","from","test","length","n","l","Symbol","iterator","i","u","f","o","next","Object","done","push","value","isArray","CALC_PRECISION","exports","NEWTON_MAX_ITERATIONS","CORRECTION_MAX_STEPS","floorDiv","b","q","ceilDiv","asFeeParts","fee","Fraction","asFraction","lt","ZERO","gte","ONE","Error","BigInt","numerator","denominator","invariantF","x","y","amp","d","sixteenAxy","invariantG","fourXy","fixD","d0","getD","aReserve","bReserve","rateA","arguments","undefined","rateB","xs","ys","sum","ann","dP","dNext","diff","solveCounterparty","c","converged","yNext","getRawSwap","inAfter","outBefore","rateIn","rateOut","marginalInputPerOutput","common","cube","getPrice","getSwapOutput","outputMetadata","input","inputReserve","outputReserve","_asFeeParts","_asFeeParts2","feeNum","feeDen","raw","gross","lpFee","output","nextInputReserve","nextOutputReserve","idealPrice","actualPrice","priceImpact","subtract","divide","AssetAmount","getSwapInput","_asFeeParts3","_asFeeParts4","grossMin","scaleIn","scaleOut","yTarget","xNeeded","xBefore","grossOf","dx","steps","calculatePinnedDeposit","offered","reserves","totalLp","some","cap","deltas","map","nextTotalLp","generatedLp","targetDeltaD","shareAfterDeposit","SharedPoolMath","getShare","calculateLiquidity","_calculatePinnedDepos","aChange","bChange","actualDepositedA","actualDepositedB","pinnedDepositFromAnchor","anchorIndex","anchorAmount"],"sources":["../../../src/PoolMath/V4StableswapPool.ts"],"sourcesContent":["import { AssetAmount, IAssetAmountMetadata } from \"@sundaeswap/asset\";\nimport { Fraction, type TFractionLike } from \"@sundaeswap/fraction\";\n\nimport { SharedPoolMath } from \"./index.js\";\n\n/**\n * THE V4 STABLESWAP INVARIANT MODULE — NOT THE V3 \"STABLESWAPS\" CONTRACT.\n *\n * Two different things in this SDK carry the word \"stableswap\". Keep them\n * apart:\n *\n * - `StableSwapsPool` / `EContractVersion.Stableswaps` is the **v3** stableswap\n * contract. It is a whole contract version with its own datum builder and\n * transaction builder. It stores `D` in the pool datum and has no per-asset\n * rates.\n * - `V4StableswapPool` / `EPoolCurve.V4Stableswap` (this file) is a **v4\n * invariant module**. It is one curve among several a v4 pool can bind, next\n * to constant product, constant sum and concentrated liquidity. It stores no\n * `D` and carries per-asset integer `rates`.\n *\n * The amplification `A` is the ONE thing they share: the same parameter on the\n * same scale, carried by the same `linearAmplificationFactor` field, with each\n * implementation applying its own internal scaling. Everything else is\n * different — do not pass one's reserves, rates or `D` to the other.\n *\n * The curve, on rated and scaled reserves `x = r_a·rate_a·P` and\n * `y = r_b·rate_b·P` with `P = calc_precision = 10^12` and `A` the linear\n * amplification:\n *\n * 4A(x + y) + D = 4AD + D³ / (4xy)\n *\n * `D` is the largest integer that satisfies it. Neither `D` nor a swap output\n * can be computed on-chain, because both need Newton's method. The scooper\n * computes them and the module checks that each supplied integer is the unique\n * one that solves the invariant. This file is the off-chain twin of\n * `lib/modules/ss_math.ak` and `lib/modules/ss_check.ak` in the sundae-v4\n * repository — those are the source of truth; keep this in lockstep with them.\n */\n\n/** `ss_math.calc_precision`: the scale applied to reserves before they enter the invariant. */\nexport const CALC_PRECISION = 1_000_000_000_000n;\n\n/** Newton iteration cap, matching the reference implementation. */\nconst NEWTON_MAX_ITERATIONS = 255;\n\n/** Bound on the fix-up walk of the reverse swap. The closed form lands within a few units. */\nconst CORRECTION_MAX_STEPS = 256;\n\n/**\n * Holds the calculated outcome of a v4 stableswap swap. Mirrors\n * {@link ConstantProductPool.TSwapOutcome} so it flows through the same generic\n * swap-outcome consumers.\n *\n * `lpFee` is denominated in the **output** asset, not the input asset. The\n * stableswap fee is taken off the gross output (`fee = ceil(gross · feeRate)`),\n * unlike constant product and constant sum which take the fee off the input.\n * The v3 `StableSwapsPool` does the same.\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// ─── Integer helpers ────────────────────────────────────────────────────────\n\n/** Plutus `divideInteger`: floor toward −∞. */\nconst floorDiv = (a: bigint, b: bigint): bigint => {\n const q = a / b;\n const r = a % b;\n return r !== 0n && r < 0n !== b < 0n ? q - 1n : q;\n};\n\n/** ceil(a / b) with the same sign convention as {@link floorDiv}. */\nconst ceilDiv = (a: bigint, b: bigint): bigint => -floorDiv(-a, b);\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// ─── Invariant polynomials (`ss_math.ak`) ───────────────────────────────────\n\n/**\n * `f(D)` from the on-chain `liquidity_invariant`. It is ≤ 0 when `D` is at or\n * below the curve. All arguments are rated and scaled.\n */\nexport const invariantF = (\n x: bigint,\n y: bigint,\n amp: bigint,\n d: bigint,\n): bigint => {\n const sixteenAxy = 16n * amp * x * y;\n return sixteenAxy * d + d * d * d - (sixteenAxy * (x + y) + 4n * x * y * d);\n};\n\n/**\n * `g(y)` from the on-chain `exchange_invariant`. It is ≥ 0 when the pool keeps\n * enough of the taken asset. `g` is symmetric in `x` and `y`, which is what\n * lets {@link getSwapInput} reuse the same solver in the other direction.\n */\nexport const invariantG = (\n x: bigint,\n y: bigint,\n amp: bigint,\n d: bigint,\n): bigint => {\n const fourXy = 4n * x * y;\n return fourXy * (4n * amp * (x + y) + d) - fourXy * 4n * amp * d - d * d * d;\n};\n\n// ─── D ──────────────────────────────────────────────────────────────────────\n\n/** The ±1 fix-up that turns a Newton result into the exact largest `D`. */\nconst fixD = (x: bigint, y: bigint, amp: bigint, d0: bigint): bigint => {\n let d = d0;\n while (invariantF(x, y, amp, d) > 0n) d -= 1n;\n while (invariantF(x, y, amp, d + 1n) <= 0n) d += 1n;\n return d;\n};\n\n/**\n * The sum invariant `D` of a two-asset v4 stableswap pool: the largest integer\n * that satisfies the curve on the rated, scaled reserves. Newton from\n * `D = x + y`, then a ±1 fix-up.\n *\n * `D` carries the `rate · CALC_PRECISION` scale — it is not a token amount.\n *\n * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.\n * @param aReserve The pool's reserve of asset A, in token units.\n * @param bReserve The pool's reserve of asset B, in token units.\n * @param rateA The pool's rate for asset A (from the stableswap config).\n * @param rateB The pool's rate for asset B.\n */\nexport const getD = (\n amp: bigint,\n aReserve: bigint,\n bReserve: bigint,\n rateA = 1n,\n rateB = 1n,\n): bigint => {\n if (amp <= 0n) throw new Error(\"amplification must be positive\");\n if (aReserve < 0n || bReserve < 0n)\n throw new Error(\"reserves must be non-negative\");\n if (rateA <= 0n || rateB <= 0n) throw new Error(\"rates must be positive\");\n\n const xs = aReserve * rateA * CALC_PRECISION;\n const ys = bReserve * rateB * CALC_PRECISION;\n const sum = xs + ys;\n // An empty pool has no invariant to solve; `D` is zero by definition.\n if (sum === 0n) return 0n;\n // Exactly one empty reserve is a different case, and it has no answer: the\n // Newton step divides by `4·xs·ys`, which is zero here. The chain never\n // reaches this state — Create requires both reserves positive, and the\n // exchange invariant leaves at least one unit on the output side — but this\n // is a client library, so it reports the bad input instead of faulting on a\n // native division by zero.\n if (xs === 0n || ys === 0n) {\n throw new Error(\n \"getD: a stableswap pool cannot hold exactly one empty reserve; D is undefined there\",\n );\n }\n\n const ann = 4n * amp;\n let d = sum;\n for (let i = 0; i < NEWTON_MAX_ITERATIONS; i++) {\n const dP = floorDiv(d * d * d, 4n * xs * ys);\n const dNext = floorDiv((ann * sum + 2n * dP) * d, (ann - 1n) * d + 3n * dP);\n const diff = dNext > d ? dNext - d : d - dNext;\n d = dNext;\n if (diff <= 1n) return fixD(xs, ys, amp, d);\n }\n throw new Error(\"getD: reached the Newton iteration cap\");\n};\n\n// ─── The exchange solver ────────────────────────────────────────────────────\n\n/**\n * The smallest scaled `y` with `g(xs, y) ≥ 0` at the pre-swap `d`: the least\n * the pool may keep of the counterparty asset and still sit on the curve.\n * Newton on `y`, then a walk to the exact integer — the walk leaves `y` with\n * `g(y) ≥ 0` and `g(y − 1) < 0`, so it is the boundary and not merely a valid\n * point.\n *\n * Read the direction carefully, because the two framings invert. A caller\n * turning this into an output computes `raw = Y − y`, so the SMALLEST `y` is\n * the LARGEST output the invariant admits. It is still not generous: `y` is a\n * ceiling on the exact real-valued requirement, so `raw` is at or below the\n * exact output. Most the curve allows, never more than it allows.\n *\n * Both swap directions use this: `g` is symmetric, so solving for the\n * counterparty reserve answers \"what must the other side hold\" whichever side\n * is given.\n */\nconst solveCounterparty = (amp: bigint, d: bigint, xs: bigint): bigint => {\n if (xs <= 0n)\n throw new Error(\"solveCounterparty: the given side must be positive\");\n const ann = 4n * amp;\n // n = 2: c = D³ / (4·x·Ann), b = x + D / Ann. Evaluated in the same order as\n // the Aiken source so the intermediate floors match.\n const c = floorDiv(floorDiv(d * d, 2n * xs) * d, 2n * ann);\n const b = xs + floorDiv(d, ann);\n let y = d;\n let converged = false;\n for (let i = 0; i < NEWTON_MAX_ITERATIONS; i++) {\n const yNext = floorDiv(y * y + c, 2n * y + b - d);\n const diff = yNext > y ? yNext - y : y - yNext;\n y = yNext;\n if (diff <= 1n) {\n converged = true;\n break;\n }\n }\n if (!converged)\n throw new Error(\"solveCounterparty: reached the Newton iteration cap\");\n while (invariantG(xs, y, amp, d) < 0n) y += 1n;\n while (invariantG(xs, y - 1n, amp, d) >= 0n) y -= 1n;\n return y;\n};\n\n/**\n * The raw swap output: the scaled, pre-fee amount the curve releases when the\n * given reserve becomes `inAfter` and the taken reserve starts at `outBefore`,\n * at the pre-swap `d`. It is the largest such amount the exchange invariant\n * admits — one unit more leaves the pool below the curve — and it is at or\n * below the exact real-valued output, so it never over-quotes.\n *\n * The result carries the `rate · CALC_PRECISION` scale. Divide by\n * `rateOut · CALC_PRECISION` to get the gross output in token units.\n *\n * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.\n * @param d The pre-swap sum invariant, from {@link getD}.\n * @param inAfter The given asset's reserve after the input arrives, in token units.\n * @param outBefore The taken asset's reserve before the swap, in token units.\n * @param rateIn The pool's rate for the given asset.\n * @param rateOut The pool's rate for the taken asset.\n */\nexport const getRawSwap = (\n amp: bigint,\n d: bigint,\n inAfter: bigint,\n outBefore: bigint,\n rateIn = 1n,\n rateOut = 1n,\n): bigint => {\n if (amp <= 0n) throw new Error(\"amplification must be positive\");\n if (d <= 0n) throw new Error(\"the sum invariant must be positive\");\n if (inAfter <= 0n || outBefore <= 0n)\n throw new Error(\"reserves must be positive\");\n if (rateIn <= 0n || rateOut <= 0n) throw new Error(\"rates must be positive\");\n const xs = inAfter * rateIn * CALC_PRECISION;\n return outBefore * rateOut * CALC_PRECISION - solveCounterparty(amp, d, xs);\n};\n\n// ─── Marginal price ─────────────────────────────────────────────────────────\n\n/**\n * The marginal price of the curve at the current reserves, as input units per\n * output unit. Differentiating the invariant at fixed `D` gives\n *\n * −dy/dx = (16A·x²y² + D³·y) / (16A·x²y² + D³·x)\n *\n * in scaled value units, which converts to token units through the rates. At a\n * balanced pool (`x = y`) it reduces to `rateOut / rateIn`, the par price.\n */\nconst marginalInputPerOutput = (\n amp: bigint,\n xs: bigint,\n ys: bigint,\n d: bigint,\n rateIn: bigint,\n rateOut: bigint,\n): Fraction => {\n const common = 16n * amp * xs * xs * ys * ys;\n const cube = d * d * d;\n return new Fraction(\n rateOut * (common + cube * xs),\n rateIn * (common + cube * ys),\n );\n};\n\n/**\n * The pool's marginal price as raw units of asset A per raw unit of asset B.\n * Use it where a constant-product pool would use the reserve ratio: for a\n * stableswap pool the reserve ratio is not the price, because the curve holds\n * the price near par across a wide band of ratios.\n *\n * The result is in raw (undecimalized) units. Adjust for the two assets'\n * decimals before display.\n */\nexport const getPrice = (\n amp: bigint,\n aReserve: bigint,\n bReserve: bigint,\n rateA = 1n,\n rateB = 1n,\n): Fraction => {\n if (aReserve <= 0n || bReserve <= 0n)\n throw new Error(\"reserves must be positive\");\n const d = getD(amp, aReserve, bReserve, rateA, rateB);\n const xs = aReserve * rateA * CALC_PRECISION;\n const ys = bReserve * rateB * CALC_PRECISION;\n // A per B: asset B is the output side of the derivative.\n return marginalInputPerOutput(amp, xs, ys, d, rateA, rateB);\n};\n\n// ─── Swap output ────────────────────────────────────────────────────────────\n\n/**\n * Calculate the swap outcome for a v4 stableswap pool.\n *\n * The sequence the chain enforces (`ss_check.ak`, tag 3):\n *\n * 1. `D` is derived from the pre-swap reserves at the pool's rates.\n * 2. `raw` is the LARGEST scaled output the exchange invariant admits at that\n * `D`, with the input already added to the given reserve. The solver pins\n * the pool's remaining taken reserve `y` to the SMALLEST integer that still\n * satisfies the invariant, and `raw = outBefore·rateOut·P − y`, so the two\n * statements are the same one: least reserve kept, most output released.\n * 3. `gross = floor(raw / (rateOut · CALC_PRECISION))` is the output in token units.\n * 4. `fee = ceil(gross · feeRate)` stays in the pool.\n * 5. The trader receives `gross − fee`.\n *\n * Every rounding step favours the pool, never the trader: `y` is a ceiling on\n * the exact reserve the curve requires, `gross` floors to whole tokens, and the\n * fee ceilings. A trader is never quoted more than the chain will pay.\n *\n * @param outputMetadata Metadata for the **taken** asset. The fee is denominated in it.\n * @param input The amount of the given asset being swapped.\n * @param inputReserve The pool's reserve of the given asset.\n * @param outputReserve The pool's reserve of the taken asset.\n * @param rateIn The pool's rate for the given asset (from the stableswap config).\n * @param rateOut The pool's rate for the taken asset.\n * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.\n * @param fee The swap fee rate, applied to the gross output.\n * @returns The swap details in the shared {@link TSwapOutcome} shape.\n */\nexport const getSwapOutput = (\n outputMetadata: IAssetAmountMetadata,\n input: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n rateIn: bigint,\n rateOut: bigint,\n amp: bigint,\n fee: TFractionLike,\n): TSwapOutcome => {\n if (input <= 0n || inputReserve <= 0n || outputReserve <= 0n)\n throw new Error(\"Input and reserves must be positive\");\n if (rateIn <= 0n || rateOut <= 0n) throw new Error(\"Rates must be positive\");\n if (amp <= 0n) throw new Error(\"Amplification must be positive\");\n const [feeNum, feeDen] = asFeeParts(fee);\n\n const d = getD(amp, inputReserve, outputReserve, rateIn, rateOut);\n const raw = getRawSwap(\n amp,\n d,\n inputReserve + input,\n outputReserve,\n rateIn,\n rateOut,\n );\n const gross = floorDiv(raw, rateOut * CALC_PRECISION);\n const lpFee = ceilDiv(gross * feeNum, feeDen);\n const output = gross - lpFee;\n if (output <= 0n)\n throw new Error(\"Swap yields no output after the fee; raise the input\");\n\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - output;\n\n // Price impact against the pool's marginal price before the swap, the same\n // definition concentrated liquidity uses. Constant sum measures against its\n // par price instead, because a constant-sum pool has no other price. A\n // stableswap pool does: its marginal price moves with the reserve ratio, so\n // measuring against par would report the pool's standing imbalance as this\n // trade's impact. The fee is excluded so the number is curve slippage only.\n const xs = inputReserve * rateIn * CALC_PRECISION;\n const ys = outputReserve * rateOut * CALC_PRECISION;\n const idealPrice = marginalInputPerOutput(amp, xs, ys, d, rateIn, rateOut);\n const actualPrice = new Fraction(input, gross);\n const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n\n return {\n input,\n output,\n lpFee: new AssetAmount(lpFee, outputMetadata),\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n// ─── Swap input (the reverse) ───────────────────────────────────────────────\n\n/**\n * Calculate the minimal input that buys a given output — the inverse of\n * {@link getSwapOutput}.\n *\n * The steps:\n *\n * 1. Invert the fee: the smallest gross output that nets `output` after\n * `ceil(gross · feeRate)` is `ceil(output · feeDen / (feeDen − feeNum))`.\n * 2. Turn that gross into the scaled reserve the pool may keep of the taken\n * asset.\n * 3. Solve the exchange invariant in the other direction for the given\n * reserve that supports it. `g` is symmetric, so this is the same solver.\n * 4. Convert to token units and walk down to the minimum, which absorbs the\n * integer rounding of step 3.\n *\n * @param outputMetadata Metadata for the **taken** asset. The fee is denominated in it.\n * @param output The wanted amount of the taken asset.\n * @param inputReserve The pool's reserve of the given asset.\n * @param outputReserve The pool's reserve of the taken asset.\n * @param rateIn The pool's rate for the given asset (from the stableswap config).\n * @param rateOut The pool's rate for the taken asset.\n * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.\n * @param fee The swap fee rate, applied to the gross output.\n * @returns The swap details in the shared {@link TSwapOutcome} shape.\n */\nexport const getSwapInput = (\n outputMetadata: IAssetAmountMetadata,\n output: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n rateIn: bigint,\n rateOut: bigint,\n amp: 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 (rateIn <= 0n || rateOut <= 0n) throw new Error(\"Rates must be positive\");\n if (amp <= 0n) throw new Error(\"Amplification must be positive\");\n if (output >= outputReserve)\n throw new Error(\"Output must be below the output reserve\");\n const [feeNum, feeDen] = asFeeParts(fee);\n\n // 1. Smallest gross whose post-fee remainder reaches `output`.\n // gross − ceil(gross·n/d) = floor(gross·(d−n)/d), which is ≥ output\n // exactly when gross ≥ ceil(output·d / (d−n)).\n const grossMin = ceilDiv(output * feeDen, feeDen - feeNum);\n if (grossMin >= outputReserve)\n throw new Error(\n \"Output is not reachable: the fee pushes it past the reserve\",\n );\n\n const d = getD(amp, inputReserve, outputReserve, rateIn, rateOut);\n const scaleIn = rateIn * CALC_PRECISION;\n const scaleOut = rateOut * CALC_PRECISION;\n\n // 2. The most the pool may keep of the taken asset and still pay `grossMin`.\n const yTarget = (outputReserve - grossMin) * scaleOut;\n if (yTarget <= 0n)\n throw new Error(\"Output is not reachable within the pool's reserves\");\n\n // 3. + 4. The scaled given reserve that supports it, then token units.\n const xNeeded = solveCounterparty(amp, d, yTarget);\n const xBefore = inputReserve * scaleIn;\n let input = ceilDiv(xNeeded - xBefore, scaleIn);\n if (input < 1n) input = 1n;\n\n const grossOf = (dx: bigint): bigint =>\n floorDiv(\n getRawSwap(amp, d, inputReserve + dx, outputReserve, rateIn, rateOut),\n scaleOut,\n );\n\n let steps = 0;\n while (grossOf(input) < grossMin) {\n input += 1n;\n if (++steps > CORRECTION_MAX_STEPS)\n throw new Error(\"getSwapInput: the correction walk did not converge\");\n }\n while (input > 1n && grossOf(input - 1n) >= grossMin) {\n input -= 1n;\n if (++steps > CORRECTION_MAX_STEPS)\n throw new Error(\"getSwapInput: the correction walk did not converge\");\n }\n\n const gross = grossOf(input);\n const lpFee = ceilDiv(gross * feeNum, feeDen);\n\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - output;\n\n const xs = xBefore;\n const ys = outputReserve * scaleOut;\n const idealPrice = marginalInputPerOutput(amp, xs, ys, d, rateIn, rateOut);\n const actualPrice = new Fraction(input, gross);\n const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n\n return {\n input,\n output,\n lpFee: new AssetAmount(lpFee, outputMetadata),\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n// ─── Deposits ───────────────────────────────────────────────────────────────\n\n/**\n * The deposit target a holder of `offered` can cover, and everything pinned to\n * it. This is the target-pinned rule the v4 module enforces (`ss_check.ak`,\n * tag 6), and it is the same shape constant sum uses, stated on `D` instead of\n * on the value sum `V`:\n *\n * - the fill declares a `D` delta `t`;\n * - every reserve moves by `ceil(r_i · t / D_before)`;\n * - `total_lp` becomes `floor(lp_before · (D_before + t) / D_before)`.\n *\n * The largest `t` a holder can cover is capped by the scarcest offered asset,\n * `t = min_i floor(offered_i · D_before / r_i)`. Anything above the pinned\n * deltas is refunded. Every pool asset must be offered, or `t` is zero and the\n * deposit can never fill.\n *\n * The rates do not enter the deltas: a proportional move is proportional in\n * any units. They enter only through `D`.\n */\nexport const calculatePinnedDeposit = (\n offered: bigint[],\n reserves: bigint[],\n totalLp: bigint,\n d: bigint,\n): {\n targetDeltaD: bigint;\n deltas: bigint[];\n generatedLp: bigint;\n nextTotalLp: bigint;\n shareAfterDeposit: Fraction;\n} => {\n if (offered.length !== reserves.length)\n throw new Error(\"offered and reserves must be aligned\");\n if (totalLp <= 0n) throw new Error(\"Not enough pool liquidity\");\n if (d <= 0n) throw new Error(\"Pool sum invariant is zero\");\n if (offered.some((o) => o < 0n))\n throw new Error(\"Deposit amounts must be non-negative\");\n\n let t: bigint | undefined;\n for (let i = 0; i < offered.length; i++) {\n if (reserves[i] <= 0n) continue;\n const cap = floorDiv(offered[i] * d, reserves[i]);\n t = t === undefined || cap < t ? cap : t;\n }\n if (t === undefined || t <= 0n)\n throw new Error(\n \"A stableswap deposit must offer every pool asset in proportion (asymmetric deposits are disallowed on-chain)\",\n );\n\n const deltas = reserves.map((r) => ceilDiv(r * t, d));\n const nextTotalLp = floorDiv(totalLp * (d + t), d);\n const generatedLp = nextTotalLp - totalLp;\n if (generatedLp <= 0n) throw new Error(\"Deposit mints zero LP\");\n\n return {\n targetDeltaD: t,\n deltas,\n generatedLp,\n nextTotalLp,\n shareAfterDeposit: SharedPoolMath.getShare(generatedLp, nextTotalLp),\n };\n};\n\n/**\n * Calculate the deposit parameters for a two-asset v4 stableswap pool through\n * the target-pinned rule (see {@link calculatePinnedDeposit}). Surplus above\n * the pinned deltas comes back as `aChange` / `bChange`, the way the scoop\n * refunds it on-chain.\n *\n * @param a The amount of token A to deposit.\n * @param b The amount of token B to deposit.\n * @param aReserve The pool's reserve of token A.\n * @param bReserve The pool's reserve of token B.\n * @param totalLp The pool's total LP supply before the deposit.\n * @param rateA The pool's rate for token A (from the stableswap config).\n * @param rateB The pool's rate for token B.\n * @param amp The pool's `linear_amplification` (`A`), the raw stored integer.\n */\nexport const calculateLiquidity = (\n a: bigint,\n b: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n rateA: bigint,\n rateB: bigint,\n amp: bigint,\n) => {\n if (aReserve <= 0n || bReserve <= 0n)\n throw new Error(\"Not enough pool liquidity\");\n const d = getD(amp, aReserve, bReserve, rateA, rateB);\n const { deltas, generatedLp, nextTotalLp, shareAfterDeposit } =\n calculatePinnedDeposit([a, b], [aReserve, bReserve], totalLp, d);\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 per-asset amounts a pinned deposit needs when the user anchors on one\n * asset's amount: `t` from the anchor (`floor(anchor · D / r_anchor)`), every\n * other delta ceil-pinned to it. Drives proportional auto-fill in deposit\n * forms.\n */\nexport const pinnedDepositFromAnchor = (\n anchorIndex: number,\n anchorAmount: bigint,\n reserves: bigint[],\n d: bigint,\n): bigint[] => {\n if (anchorIndex < 0 || anchorIndex >= reserves.length)\n throw new Error(\"anchor index is out of range\");\n if (reserves[anchorIndex] <= 0n)\n throw new Error(\"anchor asset has no reserve\");\n if (d <= 0n) throw new Error(\"Pool sum invariant is zero\");\n if (anchorAmount <= 0n) return reserves.map(() => 0n);\n\n const t = floorDiv(anchorAmount * d, reserves[anchorIndex]);\n return reserves.map((r, i) =>\n i === anchorIndex ? anchorAmount : ceilDiv(r * t, d),\n );\n};\n"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,SAAA,GAAAD,OAAA;AAEA,IAAAE,MAAA,GAAAF,OAAA;AAA4C,SAAAG,eAAAC,CAAA,EAAAC,CAAA,WAAAC,eAAA,CAAAF,CAAA,KAAAG,qBAAA,CAAAH,CAAA,EAAAC,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E;EAAA,EAAC;EAErD,IAAMzH,CAAC,GAAG4B,QAAQ,CAAC4G,YAAY,GAAGxF,CAAC,EAAEoE,QAAQ,CAACmB,WAAW,CAAC,CAAC;EAC3D,OAAOnB,QAAQ,CAACK,GAAG,CAAC,UAAClI,CAAC,EAAEuB,CAAC;IAAA,OACvBA,CAAC,KAAKyH,WAAW,GAAGC,YAAY,GAAGzG,OAAO,CAACxC,CAAC,GAAGS,CAAC,EAAEgD,CAAC,CAAC;EAAA,CACtD,CAAC;AACH,CAAC","ignoreList":[]}
@@ -4,11 +4,17 @@ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" ==
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.StableSwapsPool = exports.SharedPoolMath = exports.ConstantProductPool = void 0;
7
+ exports.V4StableswapPool = exports.StableSwapsPool = exports.SharedPoolMath = exports.ConstantSumPool = exports.ConstantProductPool = exports.ConcentratedLiquidityPool = void 0;
8
+ var _ConcentratedLiquidityPool = _interopRequireWildcard(require("./ConcentratedLiquidityPool.js"));
9
+ exports.ConcentratedLiquidityPool = _ConcentratedLiquidityPool;
8
10
  var _ConstantProductPool = _interopRequireWildcard(require("./ConstantProductPool.js"));
9
11
  exports.ConstantProductPool = _ConstantProductPool;
12
+ var _ConstantSumPool = _interopRequireWildcard(require("./ConstantSumPool.js"));
13
+ exports.ConstantSumPool = _ConstantSumPool;
10
14
  var _StableSwapsPool = _interopRequireWildcard(require("./StableSwapsPool.js"));
11
15
  exports.StableSwapsPool = _StableSwapsPool;
16
+ var _V4StableswapPool = _interopRequireWildcard(require("./V4StableswapPool.js"));
17
+ exports.V4StableswapPool = _V4StableswapPool;
12
18
  var _SharedPoolMath = _interopRequireWildcard(require("./SharedPoolMath.js"));
13
19
  exports.SharedPoolMath = _SharedPoolMath;
14
20
  function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }