@sundaeswap/math 0.0.1 → 0.1.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 (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
@@ -3,34 +3,19 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.getSwapOutput = exports.getSwapInput = exports.getShare = exports.getLp = exports.getFirstLp = exports.getAssetsRatio = exports.calculateLiquidity = exports.addLiquidity = void 0;
6
+ exports.getSwapOutput = exports.getSwapInput = exports.getLp = exports.getFirstLp = exports.getAssetsRatio = exports.calculateLiquidity = exports.addLiquidity = void 0;
7
7
  exports.getSwapRatio = getSwapRatio;
8
8
  exports.getTokensForLp = void 0;
9
9
  var _asset = require("@sundaeswap/asset");
10
10
  var _fraction = require("@sundaeswap/fraction");
11
11
  var _bigintMath = require("@sundaeswap/bigint-math");
12
+ var _index = require("./index.js");
12
13
  function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
13
14
  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."); }
14
15
  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; } }
15
16
  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; }
16
17
  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; } }
17
18
  function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
18
- /**
19
- * The direction of a ratio (A per B or B per A)
20
- */
21
-
22
- /**
23
- * Asset used in a ratio calculation
24
- */
25
-
26
- /**
27
- * The result of a ratio calculation on a pool
28
- */
29
-
30
- /**
31
- * The amounts for a token pair
32
- */
33
-
34
19
  /**
35
20
  * Get the lp token amount for a, b
36
21
  * @param a tokenA amount
@@ -46,16 +31,6 @@ var getFirstLp = exports.getFirstLp = function getFirstLp(a, b) {
46
31
  */
47
32
  var getLp = exports.getLp = getFirstLp;
48
33
 
49
- /**
50
- * Get the share ratio as Fraction
51
- * @param lp
52
- * @param totalLp
53
- * @returns
54
- */
55
- var getShare = exports.getShare = function getShare(lp, totalLp) {
56
- return new _fraction.Fraction(lp, totalLp);
57
- };
58
-
59
34
  /**
60
35
  * Calculate the Add (Mixed-Deposit) Liquidity parameters
61
36
  *
@@ -99,7 +74,7 @@ var calculateLiquidity = exports.calculateLiquidity = function calculateLiquidit
99
74
  return {
100
75
  nextTotalLp: newTotalLpTokens,
101
76
  generatedLp: newLpTokens,
102
- shareAfterDeposit: getShare(newLpTokens, newTotalLpTokens),
77
+ shareAfterDeposit: _index.SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),
103
78
  bChange: bChange,
104
79
  aChange: aChange,
105
80
  actualDepositedA: actualDepositedA,
@@ -116,7 +91,7 @@ var addLiquidity = exports.addLiquidity = function addLiquidity(a, aReserve, bRe
116
91
  var nextTotalLp = new _fraction.Fraction(totalLp * (a + aReserve), aReserve).quotient;
117
92
  var lp = nextTotalLp - totalLp;
118
93
  var b = new _fraction.Fraction(bReserve * a, aReserve);
119
- var share = getShare(lp, nextTotalLp);
94
+ var share = _index.SharedPoolMath.getShare(lp, nextTotalLp);
120
95
  if (b.quotient === 0n) {
121
96
  throw new Error("The provided a asset is not enough to equal at least 1 of the b asset.");
122
97
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ConstantProductPool.js","names":["_asset","require","_fraction","_bigintMath","_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","getFirstLp","exports","b","sqrt","getLp","getShare","lp","totalLp","Fraction","calculateLiquidity","aReserve","bReserve","Error","bInUnitsOfA","aChange","bChange","actualDepositedA","actualDepositedB","newLpTokens","newTotalLpTokens","nextTotalLp","generatedLp","shareAfterDeposit","addLiquidity","quotient","share","requiredB","getTokensForLp","getSwapOutput","input","inputReserve","outputReserve","fee","roundOutputUp","asFraction","lt","ZERO","gt","ONE","feeDiff","denominator","numerator","outputNumerator","outputDenominator","output","safeOutput","inputLpFee","nextInputReserve","nextOutputReserve","amountInLessFee","idealPrice","actualPrice","priceImpact","subtract","divide","getSwapInput","gte","BigInt","getAssetsRatio","firstValue","secondValue","first","second","greaterThan","getSwapRatio","direction","assets","calculatedAmount","rawRatio","adaIds","_assets$sort","sort","isASpecial","includes","assetId","isBSpecial","localeCompare","_assets$sort2","firstAsset","secondAsset","quantity","AssetAmount","fromValue","Number","Math","pow","decimals","display","ratioAsFraction","isDivisible","belowMinimumRatio"],"sources":["../../../src/PoolMath/ConstantProductPool.ts"],"sourcesContent":["import { AssetAmount } from \"@sundaeswap/asset\";\nimport { Fraction, type TFractionLike } from \"@sundaeswap/fraction\";\nimport { sqrt } from \"@sundaeswap/bigint-math\";\n\n/**\n * The direction of a ratio (A per B or B per A)\n */\nexport type TRatioDirection = \"A_PER_B\" | \"B_PER_A\";\n\n/**\n * Asset used in a ratio calculation\n */\nexport interface IRatioCalculationAsset {\n assetId: string;\n quantity: bigint;\n decimals: number;\n}\n\n/**\n * The result of a ratio calculation on a pool\n */\nexport interface IRatioCalculationResult {\n calculatedAmount: AssetAmount;\n ratioAsFraction: Fraction;\n display: string;\n isDivisible: boolean;\n belowMinimumRatio: boolean;\n}\n\n/**\n * The amounts for a token pair\n */\nexport type TPair = [bigint, bigint];\n\n/**\n * Get the lp token amount for a, b\n * @param a tokenA amount\n * @param b tokenB amount\n * @returns the minted lp token amount\n */\nexport const getFirstLp = (a: bigint, b: bigint) => sqrt(a * b);\n\n/**\n * @deprecated\n */\nexport const getLp = getFirstLp;\n\n/**\n * Get the share ratio as Fraction\n * @param lp\n * @param totalLp\n * @returns\n */\nexport const getShare = (lp: bigint, totalLp: bigint) =>\n new Fraction(lp, totalLp);\n\n/**\n * Calculate the Add (Mixed-Deposit) Liquidity parameters\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 * @throws {Error} If the pool doesn't have enough liquidity.\n * @throws {Error} If either of the deposit amounts is zero.\n * @returns {Object} An object containing:\n * - nextTotalLp: The total lp tokens for the pool after the deposit.\n * - generatedLp: The amount of lp tokens generated by the deposit.\n * - shareAfterDeposit: The depositor's share of the pool after the deposit.\n */\nexport const calculateLiquidity = (\n a: bigint,\n b: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n) => {\n if (aReserve === 0n || bReserve === 0n) {\n throw new Error(\"Not enough pool liquidity\");\n }\n\n if (a === 0n || b === 0n) {\n throw new Error(\"Cannot use a deposit asset amount of 0\");\n }\n\n const bInUnitsOfA = (b * aReserve) / bReserve;\n\n let aChange: bigint;\n let bChange: bigint;\n\n if (bInUnitsOfA > a) {\n bChange = (bReserve * (bInUnitsOfA - a)) / aReserve;\n aChange = 0n;\n } else {\n aChange = a - bInUnitsOfA;\n bChange = 0n;\n }\n\n // Subtract off the surplus as returned to the user\n const actualDepositedA = a - aChange;\n const actualDepositedB = b - bChange;\n\n // Calculate LP Tokens\n const newLpTokens = (actualDepositedA * totalLp) / aReserve;\n const newTotalLpTokens = totalLp + newLpTokens;\n\n return {\n nextTotalLp: newTotalLpTokens,\n generatedLp: newLpTokens,\n shareAfterDeposit: getShare(newLpTokens, newTotalLpTokens),\n bChange,\n aChange,\n actualDepositedA,\n actualDepositedB,\n };\n};\n\n/**\n * @deprecated\n *\n * Use {@link calculateLiquidity} instead.\n */\nexport const addLiquidity = (\n a: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n) => {\n const nextTotalLp = new Fraction(totalLp * (a + aReserve), aReserve).quotient;\n const lp = nextTotalLp - totalLp;\n const b = new Fraction(bReserve * a, aReserve);\n const share = getShare(lp, nextTotalLp);\n\n if (b.quotient === 0n) {\n throw new Error(\n \"The provided a asset is not enough to equal at least 1 of the b asset.\",\n );\n }\n\n return {\n nextTotalLp,\n /** @deprecated */\n lp,\n generatedLp: lp,\n /** @deprecated */\n b: b.quotient,\n requiredB: b.quotient,\n /** @deprecated */\n share,\n shareAfterDeposit: share,\n };\n};\n\n/**\n * Get the token amounts the given lp represents\n * @param lp the lp amount\n * @param aReserve the pool's reserveA amount\n * @param bReserve the pool's reserveB amount\n * @param totalLp the pool's total minted lp currently\n * @returns [a, b] token amounts\n */\nexport const getTokensForLp = (\n lp: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n): TPair => [\n new Fraction(lp * aReserve, totalLp).quotient,\n new Fraction(lp * bReserve, totalLp).quotient,\n];\n\n/**\n * Holds the calculated outcome of a swap\n */\nexport type TSwapOutcome = {\n input: bigint;\n output: bigint;\n inputLpFee: bigint;\n nextInputReserve: bigint;\n nextOutputReserve: bigint;\n priceImpact: Fraction;\n};\n\n/**\n * Calculate swap outcome for a given input and pool parameters (input tokens, output tokens, fee).\n * Throws if\n * - any of the arguments are negative\n * - fee is greater than or equal 1\n *\n * @param input The given amount of tokens to be swapped\n * @param inputReserve The amount of tokens in the input reserve\n * @param outputReserve The amount of tokens in the output reserve\n * @param fee The liquidity provider fee\n * @returns The swap details\n */\nexport const getSwapOutput = (\n input: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n fee: TFractionLike,\n roundOutputUp?: boolean,\n): TSwapOutcome => {\n if (input <= 0 || inputReserve <= 0 || outputReserve <= 0)\n throw new Error(\"Input and reserves must be positive\");\n\n fee = Fraction.asFraction(fee);\n if (fee.lt(Fraction.ZERO) || fee.gt(Fraction.ONE))\n throw new Error(\"fee must be between 0 and 1\");\n\n const feeDiff = fee.denominator - fee.numerator;\n const outputNumerator = outputReserve * input * feeDiff;\n const outputDenominator = inputReserve * fee.denominator + input * feeDiff;\n const output = new Fraction(outputNumerator, outputDenominator);\n\n const safeOutput = roundOutputUp\n ? (outputNumerator + outputDenominator - 1n) / outputDenominator\n : output.quotient;\n\n const inputLpFee = new Fraction(input * fee.numerator, fee.denominator)\n .quotient;\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - safeOutput;\n\n // PRICEIMPACT: \"priceImpact\" is slightly misleadingly named in the industry as a whole\n // just by it's name, it would imply that it's the percentage difference between\n // the current price and the price after the swap, but it's actually the percentage\n // difference between the real price of your swap, and the price implied by the current\n // reserves; We got this wrong in v1, but this aligns it with the industry standard\n // Source: https://dailydefi.org/articles/price-impact-and-how-to-calculate/\n const amountInLessFee = input - inputLpFee;\n const idealPrice = new Fraction(inputReserve, outputReserve);\n const actualPrice = new Fraction(amountInLessFee, safeOutput);\n const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n return {\n input,\n output: safeOutput,\n inputLpFee,\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n/**\n * Calculate input required for a swap outcome for a given output and pool parameters (input tokens, output tokens, fee).\n * Throws if\n * - any of the arguments are negative\n * - fee is greater than or equal 1\n * - output is greater than or equal to output reserve\n *\n * @param output\n * @param inputReserve\n * @param outputReserve\n * @param fee\n * @returns The swap details\n */\nexport const getSwapInput = (\n output: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n fee: TFractionLike,\n): TSwapOutcome => {\n if (output <= 0 || inputReserve <= 0 || outputReserve <= 0)\n throw new Error(\"Output and reserves must be positive\");\n\n if (output >= outputReserve)\n throw new Error(\"Output must be less than output reserve\");\n\n fee = Fraction.asFraction(fee);\n if (fee.lt(Fraction.ZERO) || fee.gte(Fraction.ONE))\n throw new Error(\"fee must be [0,1)\");\n\n const feeDiff = BigInt(fee.denominator - fee.numerator);\n const input =\n new Fraction(\n inputReserve * output * fee.denominator,\n (outputReserve - output) * feeDiff,\n ).quotient + 1n;\n\n const inputLpFee = new Fraction(input * fee.numerator, fee.denominator)\n .quotient;\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - output;\n\n // See PRICEIMPACT\n const amountInLessFee = input - inputLpFee;\n const idealPrice = new Fraction(inputReserve, outputReserve);\n const actualPrice = new Fraction(amountInLessFee, output);\n const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n\n return {\n input,\n output,\n inputLpFee,\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n/**\n * Calculates the ratio between two values.\n *\n * @param {TFractionLike} firstValue - The first value for the ratio calculation.\n * @param {TFractionLike} secondValue - The second value for the ratio calculation.\n * @returns {string|null} The ratio of the first value to the second value, expressed as a string in base 10. If either of the inputs is zero or negative, or if either input is missing, the function returns null.\n * @throws {Error} Will throw an error if the inputs are not valid for the Fraction class's `asFraction` method.\n */\nexport const getAssetsRatio = (\n firstValue: TFractionLike,\n secondValue: TFractionLike,\n) => {\n const first = Fraction.asFraction(firstValue ?? 0);\n const second = Fraction.asFraction(secondValue ?? 0);\n\n if (!first.greaterThan(0) || !second.greaterThan(0)) {\n return \"0\";\n }\n\n return first.divide(second).toString(10);\n};\n\n/**\n * Calculates the swap ratio between two assets and returns an AssetAmount instance representing this ratio.\n *\n * The assets are first sorted lexicographically by their assetId to ensure any calculation will match\n * pool ratios (which are also sorted lexicographically when created). The direction of the swap determines the calculation.\n * For 'A_PER_B', it calculates how much of the lexicographically first asset (A) is obtained for each unit of the\n * lexicographically second asset (B). For 'B_PER_A', it calculates how much of the lexicographically second asset (B)\n * is obtained for each unit of the lexicographically first asset (A).\n *\n * The returned AssetAmount is represented in the decimal format of the asset that is being received in the swap operation.\n * In 'A_PER_B' direction, the lexicographically first asset (A) is received, so the AssetAmount will be in the decimal format\n * of Asset A. In 'B_PER_A' direction, the lexicographically second asset (B) is received, so the AssetAmount will be in the decimal format of Asset B.\n *\n * @param {TRatioDirection} direction - The direction of the swap: 'A_PER_B' means the first asset lexicographically is received and the second is given, 'B_PER_A' means the second asset lexicographically is received and the first is given.\n * @param {[IRatioCalculationAsset, IRatioCalculationAsset]} assets - An array of two assets involved in the swap. The order of the assets in this array does not matter as they will be sorted lexicographically by their assetId inside the function.\n *\n * @returns {TSwapRatio} The calculated swap ratio in different representations.\n *\n * @example\n *\n * ```ts\n * const asset1 = { quantity: 100, decimals: 0, assetId: 'B' };\n * const asset2 = { quantity: 2000000, decimals: 6, assetId: 'A' };\n * const amount = getSwapRatio('A_PER_B', [asset1, asset2]);\n * const sameAmount = getSwapRatio('A_PER_B', [asset2, asset1]);\n * console.log(amount.ratioAsFraction); // Returns a Fraction class of the ratio.\n * console.log(sameAmount.ratioAsFraction); // Same as above.\n * ```\n */\nexport function getSwapRatio(\n direction: TRatioDirection,\n assets: [IRatioCalculationAsset, IRatioCalculationAsset],\n): IRatioCalculationResult {\n let calculatedAmount: AssetAmount;\n let rawRatio: string;\n const adaIds = [\"\", \".\", \"ada.lovelace\"];\n\n const [firstAsset, secondAsset] = assets.sort((a, b) => {\n const isASpecial = adaIds.includes(a.assetId);\n const isBSpecial = adaIds.includes(b.assetId);\n\n if (isASpecial && !isBSpecial) {\n return -1;\n }\n\n if (!isASpecial && isBSpecial) {\n return 1;\n }\n\n return a.assetId.localeCompare(b.assetId);\n });\n\n if (direction === \"A_PER_B\") {\n rawRatio = getAssetsRatio(firstAsset.quantity, secondAsset.quantity);\n calculatedAmount = AssetAmount.fromValue(\n Number(rawRatio) * 10 ** (secondAsset.decimals - firstAsset.decimals),\n firstAsset.decimals,\n );\n } else {\n rawRatio = getAssetsRatio(secondAsset.quantity, firstAsset.quantity);\n calculatedAmount = AssetAmount.fromValue(\n Number(rawRatio) * 10 ** (firstAsset.decimals - secondAsset.decimals),\n secondAsset.decimals,\n );\n }\n\n return {\n calculatedAmount: calculatedAmount,\n display: calculatedAmount.value.toString(),\n ratioAsFraction: Fraction.asFraction(rawRatio),\n isDivisible: calculatedAmount.decimals > 0,\n belowMinimumRatio: rawRatio.toString() === \"0\",\n };\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,SAAA,GAAAD,OAAA;AACA,IAAAE,WAAA,GAAAF,OAAA;AAA+C,SAAAG,eAAAC,CAAA,EAAAC,CAAA,WAAAC,eAAA,CAAAF,CAAA,KAAAG,qBAAA,CAAAH,CAAA,EAAAC,CAAA,KAAAG,2BAAA,CAAAJ,CAAA,EAAAC,CAAA,KAAAI,gBAAA;AAAA,SAAAA,iBAAA,cAAAC,SAAA;AAAA,SAAAF,4BAAAJ,CAAA,EAAAO,CAAA,QAAAP,CAAA,2BAAAA,CAAA,SAAAQ,iBAAA,CAAAR,CAAA,EAAAO,CAAA,OAAAE,CAAA,MAAAC,QAAA,CAAAC,IAAA,CAAAX,CAAA,EAAAY,KAAA,6BAAAH,CAAA,IAAAT,CAAA,CAAAa,WAAA,KAAAJ,CAAA,GAAAT,CAAA,CAAAa,WAAA,CAAAC,IAAA,aAAAL,CAAA,cAAAA,CAAA,GAAAM,KAAA,CAAAC,IAAA,CAAAhB,CAAA,oBAAAS,CAAA,+CAAAQ,IAAA,CAAAR,CAAA,IAAAD,iBAAA,CAAAR,CAAA,EAAAO,CAAA;AAAA,SAAAC,kBA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+G,eAAe,EAAEhF,kBAAQ,CAAC0B,UAAU,CAACkC,QAAQ,CAAC;IAC9CqB,WAAW,EAAEtB,gBAAgB,CAACmB,QAAQ,GAAG,CAAC;IAC1CI,iBAAiB,EAAEtB,QAAQ,CAAC3F,QAAQ,CAAC,CAAC,KAAK;EAC7C,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"ConstantProductPool.js","names":["_asset","require","_fraction","_bigintMath","_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","getFirstLp","exports","b","sqrt","getLp","calculateLiquidity","aReserve","bReserve","totalLp","Error","bInUnitsOfA","aChange","bChange","actualDepositedA","actualDepositedB","newLpTokens","newTotalLpTokens","nextTotalLp","generatedLp","shareAfterDeposit","SharedPoolMath","getShare","addLiquidity","Fraction","quotient","lp","share","requiredB","getTokensForLp","getSwapOutput","input","inputReserve","outputReserve","fee","roundOutputUp","asFraction","lt","ZERO","gt","ONE","feeDiff","denominator","numerator","outputNumerator","outputDenominator","output","safeOutput","inputLpFee","nextInputReserve","nextOutputReserve","amountInLessFee","idealPrice","actualPrice","priceImpact","subtract","divide","getSwapInput","gte","BigInt","getAssetsRatio","firstValue","secondValue","first","second","greaterThan","getSwapRatio","direction","assets","calculatedAmount","rawRatio","adaIds","_assets$sort","sort","isASpecial","includes","assetId","isBSpecial","localeCompare","_assets$sort2","firstAsset","secondAsset","quantity","AssetAmount","fromValue","Number","Math","pow","decimals","display","ratioAsFraction","isDivisible","belowMinimumRatio"],"sources":["../../../src/PoolMath/ConstantProductPool.ts"],"sourcesContent":["import { AssetAmount } from \"@sundaeswap/asset\";\nimport { Fraction, type TFractionLike } from \"@sundaeswap/fraction\";\nimport { sqrt } from \"@sundaeswap/bigint-math\";\nimport { SharedPoolMath } from \"./index.js\";\n\n/**\n * Get the lp token amount for a, b\n * @param a tokenA amount\n * @param b tokenB amount\n * @returns the minted lp token amount\n */\nexport const getFirstLp = (a: bigint, b: bigint) => sqrt(a * b);\n\n/**\n * @deprecated\n */\nexport const getLp = getFirstLp;\n\n/**\n * Calculate the Add (Mixed-Deposit) Liquidity parameters\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 * @throws {Error} If the pool doesn't have enough liquidity.\n * @throws {Error} If either of the deposit amounts is zero.\n * @returns {Object} An object containing:\n * - nextTotalLp: The total lp tokens for the pool after the deposit.\n * - generatedLp: The amount of lp tokens generated by the deposit.\n * - shareAfterDeposit: The depositor's share of the pool after the deposit.\n */\nexport const calculateLiquidity = (\n a: bigint,\n b: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n) => {\n if (aReserve === 0n || bReserve === 0n) {\n throw new Error(\"Not enough pool liquidity\");\n }\n\n if (a === 0n || b === 0n) {\n throw new Error(\"Cannot use a deposit asset amount of 0\");\n }\n\n const bInUnitsOfA = (b * aReserve) / bReserve;\n\n let aChange: bigint;\n let bChange: bigint;\n\n if (bInUnitsOfA > a) {\n bChange = (bReserve * (bInUnitsOfA - a)) / aReserve;\n aChange = 0n;\n } else {\n aChange = a - bInUnitsOfA;\n bChange = 0n;\n }\n\n // Subtract off the surplus as returned to the user\n const actualDepositedA = a - aChange;\n const actualDepositedB = b - bChange;\n\n // Calculate LP Tokens\n const newLpTokens = (actualDepositedA * totalLp) / aReserve;\n const newTotalLpTokens = totalLp + newLpTokens;\n\n return {\n nextTotalLp: newTotalLpTokens,\n generatedLp: newLpTokens,\n shareAfterDeposit: SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),\n bChange,\n aChange,\n actualDepositedA,\n actualDepositedB,\n };\n};\n\n/**\n * @deprecated\n *\n * Use {@link calculateLiquidity} instead.\n */\nexport const addLiquidity = (\n a: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n) => {\n const nextTotalLp = new Fraction(totalLp * (a + aReserve), aReserve).quotient;\n const lp = nextTotalLp - totalLp;\n const b = new Fraction(bReserve * a, aReserve);\n const share = SharedPoolMath.getShare(lp, nextTotalLp);\n\n if (b.quotient === 0n) {\n throw new Error(\n \"The provided a asset is not enough to equal at least 1 of the b asset.\",\n );\n }\n\n return {\n nextTotalLp,\n /** @deprecated */\n lp,\n generatedLp: lp,\n /** @deprecated */\n b: b.quotient,\n requiredB: b.quotient,\n /** @deprecated */\n share,\n shareAfterDeposit: share,\n };\n};\n\n/**\n * Get the token amounts the given lp represents\n * @param lp the lp amount\n * @param aReserve the pool's reserveA amount\n * @param bReserve the pool's reserveB amount\n * @param totalLp the pool's total minted lp currently\n * @returns [a, b] token amounts\n */\nexport const getTokensForLp = (\n lp: bigint,\n aReserve: bigint,\n bReserve: bigint,\n totalLp: bigint,\n): SharedPoolMath.TPair => [\n new Fraction(lp * aReserve, totalLp).quotient,\n new Fraction(lp * bReserve, totalLp).quotient,\n];\n\n/**\n * Holds the calculated outcome of a swap\n */\nexport type TSwapOutcome = {\n input: bigint;\n output: bigint;\n inputLpFee: bigint;\n nextInputReserve: bigint;\n nextOutputReserve: bigint;\n priceImpact: Fraction;\n};\n\n/**\n * Calculate swap outcome for a given input and pool parameters (input tokens, output tokens, fee).\n * Throws if\n * - any of the arguments are negative\n * - fee is greater than or equal 1\n *\n * @param input The given amount of tokens to be swapped\n * @param inputReserve The amount of tokens in the input reserve\n * @param outputReserve The amount of tokens in the output reserve\n * @param fee The liquidity provider fee\n * @returns The swap details\n */\nexport const getSwapOutput = (\n input: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n fee: TFractionLike,\n roundOutputUp?: boolean,\n): TSwapOutcome => {\n if (input <= 0 || inputReserve <= 0 || outputReserve <= 0)\n throw new Error(\"Input and reserves must be positive\");\n\n fee = Fraction.asFraction(fee);\n if (fee.lt(Fraction.ZERO) || fee.gt(Fraction.ONE))\n throw new Error(\"fee must be between 0 and 1\");\n\n const feeDiff = fee.denominator - fee.numerator;\n const outputNumerator = outputReserve * input * feeDiff;\n const outputDenominator = inputReserve * fee.denominator + input * feeDiff;\n const output = new Fraction(outputNumerator, outputDenominator);\n\n const safeOutput = roundOutputUp\n ? (outputNumerator + outputDenominator - 1n) / outputDenominator\n : output.quotient;\n\n const inputLpFee = new Fraction(input * fee.numerator, fee.denominator)\n .quotient;\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - safeOutput;\n\n // PRICEIMPACT: \"priceImpact\" is slightly misleadingly named in the industry as a whole\n // just by it's name, it would imply that it's the percentage difference between\n // the current price and the price after the swap, but it's actually the percentage\n // difference between the real price of your swap, and the price implied by the current\n // reserves; We got this wrong in v1, but this aligns it with the industry standard\n // Source: https://dailydefi.org/articles/price-impact-and-how-to-calculate/\n const amountInLessFee = input - inputLpFee;\n const idealPrice = new Fraction(inputReserve, outputReserve);\n const actualPrice = new Fraction(amountInLessFee, safeOutput);\n const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n return {\n input,\n output: safeOutput,\n inputLpFee,\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n/**\n * Calculate input required for a swap outcome for a given output and pool parameters (input tokens, output tokens, fee).\n * Throws if\n * - any of the arguments are negative\n * - fee is greater than or equal 1\n * - output is greater than or equal to output reserve\n *\n * @param output\n * @param inputReserve\n * @param outputReserve\n * @param fee\n * @returns The swap details\n */\nexport const getSwapInput = (\n output: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n fee: TFractionLike,\n): TSwapOutcome => {\n if (output <= 0 || inputReserve <= 0 || outputReserve <= 0)\n throw new Error(\"Output and reserves must be positive\");\n\n if (output >= outputReserve)\n throw new Error(\"Output must be less than output reserve\");\n\n fee = Fraction.asFraction(fee);\n if (fee.lt(Fraction.ZERO) || fee.gte(Fraction.ONE))\n throw new Error(\"fee must be [0,1)\");\n\n const feeDiff = BigInt(fee.denominator - fee.numerator);\n const input =\n new Fraction(\n inputReserve * output * fee.denominator,\n (outputReserve - output) * feeDiff,\n ).quotient + 1n;\n\n const inputLpFee = new Fraction(input * fee.numerator, fee.denominator)\n .quotient;\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - output;\n\n // See PRICEIMPACT\n const amountInLessFee = input - inputLpFee;\n const idealPrice = new Fraction(inputReserve, outputReserve);\n const actualPrice = new Fraction(amountInLessFee, output);\n const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n\n return {\n input,\n output,\n inputLpFee,\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n };\n};\n\n/**\n * Calculates the ratio between two values.\n *\n * @param {TFractionLike} firstValue - The first value for the ratio calculation.\n * @param {TFractionLike} secondValue - The second value for the ratio calculation.\n * @returns {string|null} The ratio of the first value to the second value, expressed as a string in base 10. If either of the inputs is zero or negative, or if either input is missing, the function returns null.\n * @throws {Error} Will throw an error if the inputs are not valid for the Fraction class's `asFraction` method.\n */\nexport const getAssetsRatio = (\n firstValue: TFractionLike,\n secondValue: TFractionLike,\n) => {\n const first = Fraction.asFraction(firstValue ?? 0);\n const second = Fraction.asFraction(secondValue ?? 0);\n\n if (!first.greaterThan(0) || !second.greaterThan(0)) {\n return \"0\";\n }\n\n return first.divide(second).toString(10);\n};\n\n/**\n * Calculates the swap ratio between two assets and returns an AssetAmount instance representing this ratio.\n *\n * The assets are first sorted lexicographically by their assetId to ensure any calculation will match\n * pool ratios (which are also sorted lexicographically when created). The direction of the swap determines the calculation.\n * For 'A_PER_B', it calculates how much of the lexicographically first asset (A) is obtained for each unit of the\n * lexicographically second asset (B). For 'B_PER_A', it calculates how much of the lexicographically second asset (B)\n * is obtained for each unit of the lexicographically first asset (A).\n *\n * The returned AssetAmount is represented in the decimal format of the asset that is being received in the swap operation.\n * In 'A_PER_B' direction, the lexicographically first asset (A) is received, so the AssetAmount will be in the decimal format\n * of Asset A. In 'B_PER_A' direction, the lexicographically second asset (B) is received, so the AssetAmount will be in the decimal format of Asset B.\n *\n * @param {TRatioDirection} direction - The direction of the swap: 'A_PER_B' means the first asset lexicographically is received and the second is given, 'B_PER_A' means the second asset lexicographically is received and the first is given.\n * @param {[IRatioCalculationAsset, IRatioCalculationAsset]} assets - An array of two assets involved in the swap. The order of the assets in this array does not matter as they will be sorted lexicographically by their assetId inside the function.\n *\n * @returns {TSwapRatio} The calculated swap ratio in different representations.\n *\n * @example\n *\n * ```ts\n * const asset1 = { quantity: 100, decimals: 0, assetId: 'B' };\n * const asset2 = { quantity: 2000000, decimals: 6, assetId: 'A' };\n * const amount = getSwapRatio('A_PER_B', [asset1, asset2]);\n * const sameAmount = getSwapRatio('A_PER_B', [asset2, asset1]);\n * console.log(amount.ratioAsFraction); // Returns a Fraction class of the ratio.\n * console.log(sameAmount.ratioAsFraction); // Same as above.\n * ```\n */\nexport function getSwapRatio(\n direction: SharedPoolMath.TRatioDirection,\n assets: [\n SharedPoolMath.IRatioCalculationAsset,\n SharedPoolMath.IRatioCalculationAsset,\n ],\n): SharedPoolMath.IRatioCalculationResult {\n let calculatedAmount: AssetAmount;\n let rawRatio: string;\n const adaIds = [\"\", \".\", \"ada.lovelace\"];\n\n const [firstAsset, secondAsset] = assets.sort((a, b) => {\n const isASpecial = adaIds.includes(a.assetId);\n const isBSpecial = adaIds.includes(b.assetId);\n\n if (isASpecial && !isBSpecial) {\n return -1;\n }\n\n if (!isASpecial && isBSpecial) {\n return 1;\n }\n\n return a.assetId.localeCompare(b.assetId);\n });\n\n if (direction === \"A_PER_B\") {\n rawRatio = getAssetsRatio(firstAsset.quantity, secondAsset.quantity);\n calculatedAmount = AssetAmount.fromValue(\n Number(rawRatio) * 10 ** (secondAsset.decimals - firstAsset.decimals),\n firstAsset.decimals,\n );\n } else {\n rawRatio = getAssetsRatio(secondAsset.quantity, firstAsset.quantity);\n calculatedAmount = AssetAmount.fromValue(\n Number(rawRatio) * 10 ** (firstAsset.decimals - secondAsset.decimals),\n secondAsset.decimals,\n );\n }\n\n return {\n calculatedAmount: calculatedAmount,\n display: calculatedAmount.value.toString(),\n ratioAsFraction: Fraction.asFraction(rawRatio),\n isDivisible: calculatedAmount.decimals > 0,\n belowMinimumRatio: rawRatio.toString() === \"0\",\n };\n}\n"],"mappings":";;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,SAAA,GAAAD,OAAA;AACA,IAAAE,WAAA,GAAAF,OAAA;AACA,IAAAG,MAAA,GAAAH,OAAA;AAA4C,SAAAI,eAAAC,CAAA,EAAAC,CAAA,WAAAC,eAAA,CAAAF,CAAA,KAAAG,qBAAA,CAAAH,CAAA,EAAAC,CAAA,KAAAG,2BAAA,CAAAJ,CAAA,EAAAC,CAAA,KAAAI,gBAAA;AAAA,SAAAA,iBAAA,cAAAC,SAAA;AAAA,SAAAF,4BAAAJ,CAAA,EAAAO,CAAA,QAAAP,CAAA,2BAAAA,CAAA,SAAAQ,iBAAA,CAAAR,CAAA,EAAAO,CAAA,OAAAE,CAAA,MAAAC,QAAA,CAAAC,IAAA,CAAAX,CAAA,EAAAY,KAAA,6BAAAH,CAAA,IAAAT,CAAA,CAAAa,WAAA,KAAAJ,CAAA,GAAAT,CAAA,CAAAa,WAAA,CAAAC,IAAA,aAAAL,CAAA,cAAAA,CAAA,GAAAM,KAAA,CAAAC,IAAA,CAAAhB,CAAA,oBAAAS,CAAA,+CAAAQ,IAAA,CAAAR,CAAA,IAAAD,iBAAA,CAAAR,CAAA,EAAAO,CAAA;AAAA,SAAAC,kBAAAR,CAAA,EAAAO,CAAA,aAAAA,CAAA,IAAAA,CAAA,GAAAP,CAAA,CAAAkB,MAAA,MAAAX,CAAA,GAAAP,CAAA,CAAAkB,MAAA,YAAAjB,CAAA,MAAAkB,CAAA,GAAAJ,KAAA,CAAAR,CAAA,GAAAN,CAAA,GAAAM,CAAA,EAAAN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B,IAAIZ,SAAS,KAAK,SAAS,EAAE;IAC3BG,QAAQ,GAAGV,cAAc,CAACoB,UAAU,CAACE,QAAQ,EAAED,WAAW,CAACC,QAAQ,CAAC;IACpEb,gBAAgB,GAAGc,kBAAW,CAACC,SAAS,CACtCC,MAAM,CAACf,QAAQ,CAAC,GAAAgB,IAAA,CAAAC,GAAA,CAAG,EAAE,EAAKN,WAAW,CAACO,QAAQ,GAAGR,UAAU,CAACQ,QAAQ,CAAC,EACrER,UAAU,CAACQ,QACb,CAAC;EACH,CAAC,MAAM;IACLlB,QAAQ,GAAGV,cAAc,CAACqB,WAAW,CAACC,QAAQ,EAAEF,UAAU,CAACE,QAAQ,CAAC;IACpEb,gBAAgB,GAAGc,kBAAW,CAACC,SAAS,CACtCC,MAAM,CAACf,QAAQ,CAAC,GAAAgB,IAAA,CAAAC,GAAA,CAAG,EAAE,EAAKP,UAAU,CAACQ,QAAQ,GAAGP,WAAW,CAACO,QAAQ,CAAC,EACrEP,WAAW,CAACO,QACd,CAAC;EACH;EAEA,OAAO;IACLnB,gBAAgB,EAAEA,gBAAgB;IAClCoB,OAAO,EAAEpB,gBAAgB,CAACtE,KAAK,CAACrB,QAAQ,CAAC,CAAC;IAC1CgH,eAAe,EAAElE,kBAAQ,CAACY,UAAU,CAACkC,QAAQ,CAAC;IAC9CqB,WAAW,EAAEtB,gBAAgB,CAACmB,QAAQ,GAAG,CAAC;IAC1CI,iBAAiB,EAAEtB,QAAQ,CAAC5F,QAAQ,CAAC,CAAC,KAAK;EAC7C,CAAC;AACH","ignoreList":[]}
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getShare = void 0;
7
+ var _fraction = require("@sundaeswap/fraction");
8
+ /**
9
+ * The direction of a ratio (A per B or B per A)
10
+ */
11
+
12
+ /**
13
+ * Asset used in a ratio calculation
14
+ */
15
+
16
+ /**
17
+ * The result of a ratio calculation on a pool
18
+ */
19
+
20
+ /**
21
+ * The amounts for a token pair
22
+ */
23
+
24
+ /**
25
+ * Get the share ratio as Fraction
26
+ * @param lp
27
+ * @param totalLp
28
+ * @returns
29
+ */
30
+ var getShare = exports.getShare = function getShare(lp, totalLp) {
31
+ return new _fraction.Fraction(lp, totalLp);
32
+ };
33
+ //# sourceMappingURL=SharedPoolMath.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SharedPoolMath.js","names":["_fraction","require","getShare","exports","lp","totalLp","Fraction"],"sources":["../../../src/PoolMath/SharedPoolMath.ts"],"sourcesContent":["import { AssetAmount } from \"@sundaeswap/asset\";\nimport { Fraction } from \"@sundaeswap/fraction\";\n\n/**\n * The direction of a ratio (A per B or B per A)\n */\nexport type TRatioDirection = \"A_PER_B\" | \"B_PER_A\";\n\n/**\n * Asset used in a ratio calculation\n */\nexport interface IRatioCalculationAsset {\n assetId: string;\n quantity: bigint;\n decimals: number;\n}\n\n/**\n * The result of a ratio calculation on a pool\n */\nexport interface IRatioCalculationResult {\n calculatedAmount: AssetAmount;\n ratioAsFraction: Fraction;\n display: string;\n isDivisible: boolean;\n belowMinimumRatio: boolean;\n}\n\n/**\n * The amounts for a token pair\n */\nexport type TPair = [bigint, bigint];\n\n/**\n * Get the share ratio as Fraction\n * @param lp\n * @param totalLp\n * @returns\n */\nexport const getShare = (lp: bigint, totalLp: bigint) =>\n new Fraction(lp, totalLp);\n"],"mappings":";;;;;;AACA,IAAAA,SAAA,GAAAC,OAAA;AAEA;AACA;AACA;;AAGA;AACA;AACA;;AAOA;AACA;AACA;;AASA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACO,IAAMC,QAAQ,GAAAC,OAAA,CAAAD,QAAA,GAAG,SAAXA,QAAQA,CAAIE,EAAU,EAAEC,OAAe;EAAA,OAClD,IAAIC,kBAAQ,CAACF,EAAE,EAAEC,OAAO,CAAC;AAAA","ignoreList":[]}
@@ -0,0 +1,414 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getFirstLp = exports.calculateLiquidity = exports.RESERVE_PRECISION = exports.FEE_PRECISION = exports.A_PRECISION = void 0;
7
+ exports.getNewY = getNewY;
8
+ exports.getPrice = getPrice;
9
+ exports.getSumInvariant = getSumInvariant;
10
+ exports.getTokensForLp = exports.getSwapOutput = exports.getSwapInput = void 0;
11
+ exports.liquidityInvariant = liquidityInvariant;
12
+ var _index = require("./index.js");
13
+ var _fraction = require("@sundaeswap/fraction");
14
+ /**
15
+ * Validates that a given sum invariant (D) satisfies the liquidity invariant equation
16
+ * for the Stableswaps curve. This function checks if D is within the valid range by
17
+ * evaluating the invariant function at D and D+1.
18
+ *
19
+ * The liquidity invariant ensures that the curve equation is satisfied:
20
+ * 4A * 4xy * D + D^3 - (4xy * 4A * (x + y) + 4xy * D) should be <= 0 at D and > 0 at D+1
21
+ *
22
+ * @param {bigint} assetA - The reserve amount of asset A (already scaled by RESERVE_PRECISION).
23
+ * @param {bigint} assetB - The reserve amount of asset B (already scaled by RESERVE_PRECISION).
24
+ * @param {bigint} linearAmplification - The amplification coefficient for the pool.
25
+ * @param {bigint} newSumInvariant - The proposed sum invariant (D) to validate.
26
+ * @returns {boolean} True if the sum invariant satisfies the liquidity invariant equation, false otherwise.
27
+ */
28
+ function liquidityInvariant(assetA, assetB, linearAmplification, newSumInvariant) {
29
+ // 4 * A * 4 * (x*y) * D + D^3 - (4(x*y) * (4A(x + y) + D))
30
+ // 4A * 4xy * D + D^3 - (4xy * 4a * (x + y) + 4xy * D)
31
+ // 16Axy * D + D^3 - (16Axy * (x + y) + 4xy * D)
32
+ var four_a = 4n * linearAmplification;
33
+ var four_x_y = 4n * assetA * assetB;
34
+ var d_plus_one = newSumInvariant + 1n;
35
+ var d_cubed = newSumInvariant * newSumInvariant * newSumInvariant;
36
+ var d_plus_one_cubed = d_plus_one * d_plus_one * d_plus_one;
37
+ var x_plus_y = assetA + assetB;
38
+ var sixteen_a_x_y = four_a * four_x_y;
39
+ var sixteen_a_x_y_x_plus_y = sixteen_a_x_y * x_plus_y;
40
+ var f1 = sixteen_a_x_y * newSumInvariant + d_cubed - (sixteen_a_x_y_x_plus_y + four_x_y * newSumInvariant);
41
+ var f2 = sixteen_a_x_y * d_plus_one + d_plus_one_cubed - (sixteen_a_x_y_x_plus_y + four_x_y * d_plus_one);
42
+ return f1 <= 0n && f2 > 0n;
43
+ }
44
+
45
+ /**
46
+ * Precision factor for the amplification coefficient calculations.
47
+ * Used to scale the amplification factor for more precise arithmetic operations.
48
+ */
49
+ var A_PRECISION = exports.A_PRECISION = 200n;
50
+
51
+ /**
52
+ * Precision factor for reserve calculations in the Stableswaps curve.
53
+ * Reserves are multiplied by this value to maintain precision during calculations.
54
+ * This allows for accurate fractional calculations with integer arithmetic.
55
+ */
56
+ var RESERVE_PRECISION = exports.RESERVE_PRECISION = 1000000000000n;
57
+
58
+ /**
59
+ * Precision factor for fee calculations, representing basis points.
60
+ * A value of 10,000 means fees are calculated with 0.01% precision (1 basis point).
61
+ */
62
+ var FEE_PRECISION = exports.FEE_PRECISION = 10000n;
63
+
64
+ /**
65
+ * Calculates the sum invariant (D) for a Stableswaps pool using Newton's method.
66
+ * The sum invariant represents the total value in the pool and is used to determine
67
+ * the fair exchange rate between assets.
68
+ *
69
+ * This function iteratively solves for D in the Stableswaps invariant equation:
70
+ * Ann * sum + D_p * 2 = Ann * D + D_p * 3
71
+ * where D_p = D^3 / (4 * x * y) and Ann = A * n^n (with n=2)
72
+ *
73
+ * The iteration continues until convergence (difference <= 1) or fails after 255 iterations.
74
+ *
75
+ * @param {bigint} a - The amplification coefficient for the pool (will be scaled by A_PRECISION).
76
+ * @param {bigint} x - The reserve amount of the first asset (will be scaled by RESERVE_PRECISION).
77
+ * @param {bigint} y - The reserve amount of the second asset (will be scaled by RESERVE_PRECISION).
78
+ * @returns {bigint} The calculated sum invariant (D) scaled by RESERVE_PRECISION.
79
+ * @throws {Error} If the amplification coefficient is not positive.
80
+ * @throws {Error} If convergence fails after 255 iterations.
81
+ */
82
+ function getSumInvariant(a, x, y) {
83
+ if (a <= 0n) {
84
+ throw new Error("Amplification coefficient must be positive.");
85
+ }
86
+ x = x * RESERVE_PRECISION;
87
+ y = y * RESERVE_PRECISION;
88
+ a = a * A_PRECISION;
89
+ var sum = x + y;
90
+ if (sum === 0n) {
91
+ return 0n;
92
+ }
93
+ var d = sum;
94
+ var ann = a * 2n;
95
+ for (var i = 0; i < 255; i++) {
96
+ var d_p = d * d * d / (4n * x * y);
97
+ var d_prev = d;
98
+ d = (ann * sum / 100n + d_p * 2n) * d / ((ann - 100n) * d / 100n + 3n * d_p);
99
+ if (d > d_prev) {
100
+ if (d - d_prev <= 1) {
101
+ if (liquidityInvariant(x, y, a / A_PRECISION, d)) {
102
+ return d;
103
+ } else {
104
+ return d - 1n;
105
+ }
106
+ }
107
+ } else {
108
+ if (d_prev - d <= 1) {
109
+ if (liquidityInvariant(x, y, a / A_PRECISION, d)) {
110
+ return d;
111
+ } else {
112
+ return d - 1n;
113
+ }
114
+ }
115
+ }
116
+ }
117
+ throw new Error("Failed to converge on D value after 255 iterations.");
118
+ }
119
+
120
+ /**
121
+ * Calculates the new Y reserve value given a new X reserve value and the sum invariant.
122
+ * This function uses Newton's method to iteratively solve for Y in the Stableswaps equation
123
+ * while maintaining the pool's invariant (D).
124
+ *
125
+ * The function solves: Y^2 + (sum + (D * A_PRECISION) / (2 * Ann) - D) * Y - c = 0
126
+ * where c is derived from D and the pool parameters.
127
+ *
128
+ * This is used during swaps to determine the output reserve after an input is added.
129
+ *
130
+ * @param {bigint} newX - The new reserve amount for asset X (will be scaled by RESERVE_PRECISION internally).
131
+ * @param {bigint} aRaw - The raw amplification coefficient for the pool (will be scaled by A_PRECISION).
132
+ * @param {bigint} sumInvariant - The pool's sum invariant (D), already scaled.
133
+ * @returns {bigint} The calculated Y reserve value scaled by RESERVE_PRECISION.
134
+ * @throws {Error} If convergence fails after 255 iterations.
135
+ */
136
+ function getNewY(newX, aRaw, sumInvariant) {
137
+ newX = newX * RESERVE_PRECISION;
138
+ var sum = newX;
139
+ var yPrev;
140
+ var c = sumInvariant;
141
+ var ann = aRaw * A_PRECISION * 2n;
142
+ c = c * sumInvariant / (newX * 2n);
143
+ c = c * sumInvariant * A_PRECISION / 2n;
144
+ c = c / (ann * 2n);
145
+ var b = sum + sumInvariant * A_PRECISION / 2n / ann;
146
+ var y = sumInvariant;
147
+ for (var i = 0; i < 255; i++) {
148
+ yPrev = y;
149
+ y = (y * y + c) / (y * 2n + b - sumInvariant);
150
+ if (y > yPrev) {
151
+ if (y - yPrev <= 1n) {
152
+ if (liquidityInvariant(newX, y, aRaw, sumInvariant)) {
153
+ return y;
154
+ } else {
155
+ return y + 1n;
156
+ }
157
+ }
158
+ } else {
159
+ if (yPrev - y <= 1n) {
160
+ if (liquidityInvariant(newX, y, aRaw, sumInvariant)) {
161
+ return y;
162
+ } else {
163
+ return y + 1n;
164
+ }
165
+ }
166
+ }
167
+ }
168
+ throw new Error("Failed to converge on y value after 255 iterations.");
169
+ }
170
+
171
+ /**
172
+ * Calculates the initial LP token amount for the first liquidity provision to a pool.
173
+ * This is used when bootstrapping a new pool with initial reserves of assets A and B.
174
+ *
175
+ * The LP tokens minted are derived from the sum invariant (D) divided by the reserve precision,
176
+ * effectively representing the pool's total value at inception.
177
+ *
178
+ * @param {bigint} a - The initial amount of token A being deposited.
179
+ * @param {bigint} b - The initial amount of token B being deposited.
180
+ * @param {bigint} laf - The linear amplification factor for the pool.
181
+ * @returns {bigint} The amount of LP tokens to mint for the first liquidity provision.
182
+ */
183
+ var getFirstLp = exports.getFirstLp = function getFirstLp(a, b, laf) {
184
+ return getSumInvariant(laf, a, b) / RESERVE_PRECISION;
185
+ };
186
+
187
+ /**
188
+ * Calculates the liquidity parameters for adding liquidity to a Stableswaps pool.
189
+ * This function supports mixed deposits where both assets can be deposited in any proportion.
190
+ *
191
+ * The calculation is based on the change in the sum invariant (D) before and after the deposit.
192
+ * LP tokens are minted proportionally to the increase in D relative to the old D value.
193
+ *
194
+ * TODO: Investigate way to optimize actual deposited amounts
195
+ *
196
+ * @param {bigint} a - The amount of token A to deposit.
197
+ * @param {bigint} b - The amount of token B to deposit.
198
+ * @param {bigint} aReserve - The current reserve of token A in the pool.
199
+ * @param {bigint} bReserve - The current reserve of token B in the pool.
200
+ * @param {bigint} totalLp - The total LP tokens for the pool before the deposit.
201
+ * @param {bigint} laf - The linear amplification factor of the pool.
202
+ * @throws {Error} If the pool doesn't have enough liquidity (both reserves are zero).
203
+ * @throws {Error} If both deposit amounts are zero.
204
+ * @returns {Object} An object containing:
205
+ * - nextTotalLp: The total LP tokens for the pool after the deposit.
206
+ * - generatedLp: The amount of LP tokens generated by the deposit.
207
+ * - shareAfterDeposit: The depositor's share of the pool after the deposit (as a Fraction).
208
+ * - aChange: Always 0n for Stableswaps (no refund needed).
209
+ * - bChange: Always 0n for Stableswaps (no refund needed).
210
+ * - actualDepositedA: The actual amount of A deposited (always equal to input a).
211
+ * - actualDepositedB: The actual amount of B deposited (always equal to input b).
212
+ */
213
+ var calculateLiquidity = exports.calculateLiquidity = function calculateLiquidity(a, b, aReserve, bReserve, totalLp, laf) {
214
+ if (aReserve === 0n && bReserve === 0n) {
215
+ throw new Error("Not enough pool liquidity");
216
+ }
217
+ if (a === 0n && b === 0n) {
218
+ throw new Error("Cannot use a deposit asset amount of 0");
219
+ }
220
+ var oldSumInvariant = getSumInvariant(laf, aReserve, bReserve);
221
+ var newSumInvariant = getSumInvariant(laf, aReserve + a, bReserve + b);
222
+ var newLpTokens = (newSumInvariant - oldSumInvariant) * totalLp / oldSumInvariant;
223
+ var newTotalLpTokens = totalLp + newLpTokens;
224
+ return {
225
+ nextTotalLp: newTotalLpTokens,
226
+ generatedLp: newLpTokens,
227
+ shareAfterDeposit: _index.SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),
228
+ aChange: 0n,
229
+ bChange: 0n,
230
+ actualDepositedA: a,
231
+ actualDepositedB: b
232
+ };
233
+ };
234
+
235
+ /**
236
+ * Calculates the token amounts that a given LP token amount represents when withdrawing
237
+ * from a Stableswaps pool. The withdrawal is proportional to the LP tokens being redeemed
238
+ * relative to the total LP supply.
239
+ *
240
+ * This uses a simple linear proportion: amount = (lp * reserve) / totalLp for each asset.
241
+ *
242
+ * @param {bigint} lp - The amount of LP tokens being redeemed.
243
+ * @param {bigint} aReserve - The pool's current reserve amount of token A.
244
+ * @param {bigint} bReserve - The pool's current reserve amount of token B.
245
+ * @param {bigint} totalLp - The pool's total minted LP tokens currently in circulation.
246
+ * @returns {SharedPoolMath.TPair} A tuple [a, b] containing the amounts of tokens A and B to withdraw.
247
+ */
248
+ var getTokensForLp = exports.getTokensForLp = function getTokensForLp(lp, aReserve, bReserve, totalLp) {
249
+ return [new _fraction.Fraction(lp * aReserve, totalLp).quotient, new _fraction.Fraction(lp * bReserve, totalLp).quotient];
250
+ };
251
+
252
+ /**
253
+ * Represents the complete outcome of a swap operation in a Stableswaps pool.
254
+ * Contains all relevant information about the swap including amounts, fees, updated reserves,
255
+ * and price impact.
256
+ */
257
+
258
+ /**
259
+ * Calculates the output amount and all swap parameters for a given input amount in a Stableswaps pool.
260
+ * This function determines how many output tokens will be received for a given input, accounting for
261
+ * the Stableswaps curve, LP fees, and protocol fees.
262
+ *
263
+ * The calculation process:
264
+ * 1. Validates inputs and fees
265
+ * 2. Calculates the current sum invariant (D)
266
+ * 3. Determines the new Y value after adding input to X
267
+ * 4. Calculates raw output and applies fees (LP + protocol)
268
+ * 5. Computes price impact by comparing ideal vs actual execution price
269
+ *
270
+ * @param {bigint} input - The amount of input tokens to swap.
271
+ * @param {bigint} inputReserve - The current reserve amount of the input token in the pool.
272
+ * @param {bigint} outputReserve - The current reserve amount of the output token in the pool.
273
+ * @param {TFractionLike} fee - The liquidity provider fee as a fraction (e.g., 0.003 for 0.3%).
274
+ * @param {TFractionLike} protocolFee - The protocol fee as a fraction.
275
+ * @param {bigint} laf - The linear amplification factor of the pool.
276
+ * @param {boolean} [roundOutputUp] - Optional flag to round output up instead of down (default: false).
277
+ * @returns {TSwapOutcome} The complete swap outcome including output, fees, reserves, and price impact.
278
+ * @throws {Error} If input or reserves are not positive.
279
+ * @throws {Error} If fee is not in the range [0, 1).
280
+ * @throws {Error} If protocol fee is not in the range [0, 1).
281
+ * @throws {Error} If combined fee is greater than or equal to 1.
282
+ */
283
+ var getSwapOutput = exports.getSwapOutput = function getSwapOutput(input, inputReserve, outputReserve, fee, protocolFee, laf, roundOutputUp) {
284
+ if (input <= 0 || inputReserve <= 0 || outputReserve <= 0) throw new Error("Input and reserves must be positive");
285
+ fee = _fraction.Fraction.asFraction(fee);
286
+ if (fee.lt(_fraction.Fraction.ZERO) || fee.gte(_fraction.Fraction.ONE)) throw new Error("fee must be between 0 and 1");
287
+ protocolFee = _fraction.Fraction.asFraction(protocolFee);
288
+ if (protocolFee.lt(_fraction.Fraction.ZERO) || protocolFee.gte(_fraction.Fraction.ONE)) throw new Error("protocolFee must be between 0 and 1");
289
+ var combinedFee = fee.add(protocolFee);
290
+ if (combinedFee.gte(_fraction.Fraction.ONE)) throw new Error("Combined fee must be less than 1");
291
+ var sumInvariant = getSumInvariant(laf, inputReserve, outputReserve);
292
+ var nextInputReserve = inputReserve + input;
293
+ var newY = getNewY(nextInputReserve, laf, sumInvariant);
294
+ var deltaYPrec = outputReserve * RESERVE_PRECISION - newY;
295
+ var deltaY = new _fraction.Fraction(deltaYPrec, RESERVE_PRECISION);
296
+ var totalFee = combinedFee.multiply(FEE_PRECISION).multiply(deltaY.quotient).add(_fraction.Fraction.asFraction(FEE_PRECISION - 1n)).divide(FEE_PRECISION).quotient;
297
+ var totalProtocolFee = protocolFee.multiply(totalFee).divide(combinedFee).quotient;
298
+ var totalLpFee = totalFee - totalProtocolFee;
299
+ var output = deltaY.subtract(totalFee);
300
+ var safeOutput = roundOutputUp ? (output.numerator + output.denominator - 1n) / output.denominator : output.quotient;
301
+ var nextOutputReserve = outputReserve - safeOutput - totalProtocolFee;
302
+
303
+ // PRICEIMPACT: "priceImpact" is slightly misleadingly named in the industry as a whole
304
+ // just by it's name, it would imply that it's the percentage difference between
305
+ // the current price and the price after the swap, but it's actually the percentage
306
+ // difference between the real price of your swap, and the price implied by the current
307
+ // reserves; We got this wrong in v1, but this aligns it with the industry standard
308
+ // Source: https://dailydefi.org/articles/price-impact-and-how-to-calculate/
309
+ var idealPrice = getPrice(inputReserve, outputReserve, laf);
310
+ var actualPrice = new _fraction.Fraction(input, safeOutput);
311
+ var priceImpact = _fraction.Fraction.ONE.subtract(idealPrice.divide(actualPrice));
312
+ return {
313
+ input: input,
314
+ output: safeOutput,
315
+ outputLpFee: totalLpFee,
316
+ outputProtocolFee: totalProtocolFee,
317
+ nextInputReserve: nextInputReserve,
318
+ nextOutputReserve: nextOutputReserve,
319
+ nextSumInvariant: getSumInvariant(laf, nextInputReserve, nextOutputReserve),
320
+ priceImpact: priceImpact
321
+ };
322
+ };
323
+
324
+ /**
325
+ * Calculates the current price (exchange rate) of asset A in terms of asset B for a Stableswaps pool.
326
+ * The price is derived from the Stableswaps curve equation and takes into account the amplification factor.
327
+ *
328
+ * The calculation uses the formula:
329
+ * price = (xpA + (dR * aReserve) / bReserve) / (xpA + dR)
330
+ * where xpA = (Ann * aReserve) / A_PRECISION and dR is derived from the sum invariant
331
+ *
332
+ * @param {bigint} aReserve - The current reserve amount of asset A in the pool.
333
+ * @param {bigint} bReserve - The current reserve amount of asset B in the pool.
334
+ * @param {bigint} laf - The linear amplification factor of the pool.
335
+ * @returns {Fraction} The price of asset A in terms of asset B as a Fraction.
336
+ */
337
+ function getPrice(aReserve, bReserve, laf) {
338
+ // dx_0 / dx_1 only, however can have any number of coins in pool
339
+ var ann = laf * 2n * A_PRECISION;
340
+ var sumInvariant = getSumInvariant(laf, aReserve, bReserve) / RESERVE_PRECISION;
341
+ // D / n^n with n = 2
342
+ var dR = sumInvariant / 4n;
343
+ dR = dR * sumInvariant / aReserve;
344
+ dR = dR * sumInvariant / bReserve;
345
+ var xpA = ann * aReserve / A_PRECISION;
346
+ var p = new _fraction.Fraction(xpA + dR * aReserve / bReserve, xpA + dR);
347
+ return p;
348
+ }
349
+
350
+ /**
351
+ * Calculates the required input amount and all swap parameters for a desired output amount in a Stableswaps pool.
352
+ * This is the reverse operation of getSwapOutput - given how much you want to receive, it determines
353
+ * how much you need to provide as input, accounting for fees and the Stableswaps curve.
354
+ *
355
+ * The calculation process:
356
+ * 1. Validates inputs, fees, and output constraints
357
+ * 2. Calculates raw output needed before fees
358
+ * 3. Determines the new X value to achieve the desired Y reduction
359
+ * 4. Calculates required input and separates LP and protocol fees
360
+ * 5. Computes price impact by comparing ideal vs actual execution price
361
+ *
362
+ * @param {bigint} output - The desired amount of output tokens to receive.
363
+ * @param {bigint} inputReserve - The current reserve amount of the input token in the pool.
364
+ * @param {bigint} outputReserve - The current reserve amount of the output token in the pool.
365
+ * @param {TFractionLike} fee - The liquidity provider fee as a fraction (e.g., 0.003 for 0.3%).
366
+ * @param {TFractionLike} protocolFee - The protocol fee as a fraction.
367
+ * @param {bigint} laf - The linear amplification factor of the pool.
368
+ * @returns {TSwapOutcome} The complete swap outcome including required input, fees, reserves, and price impact.
369
+ * @throws {Error} If output or reserves are not positive.
370
+ * @throws {Error} If output is greater than or equal to the output reserve.
371
+ * @throws {Error} If fee is not in the range [0, 1).
372
+ * @throws {Error} If protocol fee is not in the range [0, 1).
373
+ * @throws {Error} If combined fee is greater than or equal to 1.
374
+ */
375
+ var getSwapInput = exports.getSwapInput = function getSwapInput(output, inputReserve, outputReserve, fee, protocolFee, laf) {
376
+ if (output <= 0 || inputReserve <= 0 || outputReserve <= 0) throw new Error("Output and reserves must be positive");
377
+ if (output >= outputReserve) throw new Error("Output must be less than output reserve");
378
+ fee = _fraction.Fraction.asFraction(fee);
379
+ if (fee.lt(_fraction.Fraction.ZERO) || fee.gte(_fraction.Fraction.ONE)) throw new Error("fee must be [0,1)");
380
+ protocolFee = _fraction.Fraction.asFraction(protocolFee);
381
+ if (protocolFee.lt(_fraction.Fraction.ZERO) || protocolFee.gte(_fraction.Fraction.ONE)) throw new Error("protocolFee must be between 0 and 1");
382
+ var combinedFee = fee.add(protocolFee);
383
+ if (combinedFee.gte(_fraction.Fraction.ONE)) throw new Error("Combined fee must be less than 1");
384
+
385
+ // output = rawOutput * (1-fee)
386
+ // rawOutput = output / (1-fee)
387
+ var rawOutputF = _fraction.Fraction.asFraction(output).divide(_fraction.Fraction.ONE.sub(combinedFee));
388
+ var rawOutput = (rawOutputF.numerator + rawOutputF.denominator - 1n) / rawOutputF.denominator;
389
+ var sumInvariant = getSumInvariant(laf, inputReserve, outputReserve);
390
+ var newX = getNewY(outputReserve - rawOutput, laf, sumInvariant);
391
+ var input = (newX - inputReserve * RESERVE_PRECISION + RESERVE_PRECISION - 1n) / RESERVE_PRECISION;
392
+ var totalFee = (combinedFee.multiply(FEE_PRECISION).quotient * rawOutput + FEE_PRECISION - 1n) / FEE_PRECISION;
393
+ var totalProtocolFee = protocolFee.multiply(totalFee).divide(combinedFee).quotient;
394
+ var totalLpFee = totalFee - totalProtocolFee;
395
+ var nextInputReserve = inputReserve + input;
396
+ var nextOutputReserve = outputReserve - output - totalProtocolFee;
397
+
398
+ // See PRICEIMPACT
399
+ var idealPrice = getPrice(inputReserve, outputReserve, laf);
400
+ var actualPrice = new _fraction.Fraction(input, output);
401
+ var priceImpact = _fraction.Fraction.ONE.subtract(idealPrice.divide(actualPrice));
402
+ var nextSumInvariant = getSumInvariant(laf, nextInputReserve, nextOutputReserve);
403
+ return {
404
+ input: input,
405
+ output: output,
406
+ outputLpFee: totalLpFee,
407
+ outputProtocolFee: totalProtocolFee,
408
+ nextInputReserve: nextInputReserve,
409
+ nextOutputReserve: nextOutputReserve,
410
+ priceImpact: priceImpact,
411
+ nextSumInvariant: nextSumInvariant
412
+ };
413
+ };
414
+ //# sourceMappingURL=StableSwapsPool.js.map