@sundaeswap/math 0.0.0-dev-20251017200647 → 0.0.0-dev-20251112162958

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 +293 -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 +277 -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 +97 -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 +4 -1
  27. package/src/PoolMath/ConstantProductPool.ts +10 -45
  28. package/src/PoolMath/SharedPoolMath.ts +41 -0
  29. package/src/PoolMath/StableSwapsPool.ts +401 -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,C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Q,CAAC,CAAC;IAC1C+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,CAA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AW,GAAAF,aAAA;EAe9B,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,293 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getFirstLp = exports.feePrecision = exports.calculateLiquidity = exports.aPrecision = 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
+ exports.reservePrecision = void 0;
13
+ var _index = require("./index.js");
14
+ var _fraction = require("@sundaeswap/fraction");
15
+ function liquidityInvariant(assetA, assetB, linearAmplification, newSumInvariant) {
16
+ // 4 * A * 4 * (x*y) * D + D^3 - (4(x*y) * (4A(x + y) + D))
17
+ // 4A * 4xy * D + D^3 - (4xy * 4a * (x + y) + 4xy * D)
18
+ // 16Axy * D + D^3 - (16Axy * (x + y) + 4xy * D)
19
+ var four_a = 4n * linearAmplification;
20
+ var four_x_y = 4n * assetA * assetB;
21
+ var d_plus_one = newSumInvariant + 1n;
22
+ var d_cubed = newSumInvariant * newSumInvariant * newSumInvariant;
23
+ var d_plus_one_cubed = d_plus_one * d_plus_one * d_plus_one;
24
+ var x_plus_y = assetA + assetB;
25
+ var sixteen_a_x_y = four_a * four_x_y;
26
+ var sixteen_a_x_y_x_plus_y = sixteen_a_x_y * x_plus_y;
27
+ var f1 = sixteen_a_x_y * newSumInvariant + d_cubed - (sixteen_a_x_y_x_plus_y + four_x_y * newSumInvariant);
28
+ 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);
29
+ return f1 <= 0n && f2 > 0n;
30
+ }
31
+ var aPrecision = exports.aPrecision = 200n;
32
+ var reservePrecision = exports.reservePrecision = 1000000000000n;
33
+ var feePrecision = exports.feePrecision = 10000n;
34
+ function getSumInvariant(a, x, y) {
35
+ if (a <= 0n) {
36
+ throw new Error("Amplification coefficient must be positive.");
37
+ }
38
+ x = x * reservePrecision;
39
+ y = y * reservePrecision;
40
+ a = a * aPrecision;
41
+ var sum = x + y;
42
+ if (sum === 0n) {
43
+ return 0n;
44
+ }
45
+ var d = sum;
46
+ var ann = a * 2n;
47
+ for (var i = 0; i < 255; i++) {
48
+ var d_p = d * d * d / (4n * x * y);
49
+ var d_prev = d;
50
+ d = (ann * sum / 100n + d_p * 2n) * d / ((ann - 100n) * d / 100n + 3n * d_p);
51
+ if (d > d_prev) {
52
+ if (d - d_prev <= 1) {
53
+ if (liquidityInvariant(x, y, a / aPrecision, d)) {
54
+ return d;
55
+ } else {
56
+ return d - 1n;
57
+ }
58
+ }
59
+ } else {
60
+ if (d_prev - d <= 1) {
61
+ if (liquidityInvariant(x, y, a / aPrecision, d)) {
62
+ return d;
63
+ } else {
64
+ return d - 1n;
65
+ }
66
+ }
67
+ }
68
+ }
69
+ throw new Error("Failed to converge on D value after 255 iterations.");
70
+ }
71
+ function getNewY(newX, aRaw, sumInvariant) {
72
+ newX = newX * reservePrecision;
73
+ var sum = newX;
74
+ var yPrev;
75
+ var c = sumInvariant;
76
+ var ann = aRaw * aPrecision * 2n;
77
+ c = c * sumInvariant / (newX * 2n);
78
+ c = c * sumInvariant * aPrecision / 2n;
79
+ c = c / (ann * 2n);
80
+ var b = sum + sumInvariant * aPrecision / 2n / ann;
81
+ var y = sumInvariant;
82
+ for (var i = 0; i < 255; i++) {
83
+ yPrev = y;
84
+ y = (y * y + c) / (y * 2n + b - sumInvariant);
85
+ if (y > yPrev) {
86
+ if (y - yPrev <= 1n) {
87
+ if (liquidityInvariant(newX, y, aRaw, sumInvariant)) {
88
+ return y;
89
+ } else {
90
+ return y + 1n;
91
+ }
92
+ }
93
+ } else {
94
+ if (yPrev - y <= 1n) {
95
+ if (liquidityInvariant(newX, y, aRaw, sumInvariant)) {
96
+ return y;
97
+ } else {
98
+ return y + 1n;
99
+ }
100
+ }
101
+ }
102
+ }
103
+ throw new Error("failed to converge on y value after 255 iterations.");
104
+ }
105
+
106
+ /**
107
+ * Get the lp token amount for a, b
108
+ * @param a tokenA amount
109
+ * @param b tokenB amount
110
+ * @returns the minted lp token amount
111
+ */
112
+ var getFirstLp = exports.getFirstLp = function getFirstLp(a, b, laf) {
113
+ return getSumInvariant(laf, a, b) / reservePrecision;
114
+ };
115
+
116
+ /**
117
+ * Calculate the Add (Mixed-Deposit) Liquidity parameters
118
+ *
119
+ * TODO: Investigate way to optimize actualdeposited amounts
120
+ *
121
+ * @param {bigint} a - The amount of token A to deposit.
122
+ * @param {bigint} b - The amount of token B to deposit.
123
+ * @param {bigint} aReserve - The current reserve of token A in the pool.
124
+ * @param {bigint} bReserve - The current reserve of token B in the pool.
125
+ * @param {bigint} totalLp - The total lp tokens for the pool before the deposit.
126
+ * @param {bigint} laf - The linear amplifciation factor of the pool.
127
+ * @throws {Error} If the pool doesn't have enough liquidity.
128
+ * @throws {Error} If either of the deposit amounts is zero.
129
+ * @returns {Object} An object containing:
130
+ * - nextTotalLp: The total lp tokens for the pool after the deposit.
131
+ * - generatedLp: The amount of lp tokens generated by the deposit.
132
+ * - shareAfterDeposit: The depositor's share of the pool after the deposit.
133
+ */
134
+ var calculateLiquidity = exports.calculateLiquidity = function calculateLiquidity(a, b, aReserve, bReserve, totalLp, laf) {
135
+ if (aReserve === 0n && bReserve === 0n) {
136
+ throw new Error("Not enough pool liquidity");
137
+ }
138
+ if (a === 0n && b === 0n) {
139
+ throw new Error("Cannot use a deposit asset amount of 0");
140
+ }
141
+ var oldSumInvariant = getSumInvariant(laf, aReserve, bReserve);
142
+ var newSumInvariant = getSumInvariant(laf, aReserve + a, bReserve + b);
143
+ var newLpTokens = (newSumInvariant - oldSumInvariant) * totalLp / oldSumInvariant;
144
+ var newTotalLpTokens = totalLp + newLpTokens;
145
+ return {
146
+ nextTotalLp: newTotalLpTokens,
147
+ generatedLp: newLpTokens,
148
+ shareAfterDeposit: _index.SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),
149
+ aChange: 0n,
150
+ bChange: 0n,
151
+ actualDepositedA: a,
152
+ actualDepositedB: b
153
+ };
154
+ };
155
+
156
+ /**
157
+ * Get the token amounts the given lp represents
158
+ * @param lp the lp amount
159
+ * @param aReserve the pool's reserveA amount
160
+ * @param bReserve the pool's reserveB amount
161
+ * @param totalLp the pool's total minted lp currently
162
+ * @returns [a, b] token amounts
163
+ */
164
+ var getTokensForLp = exports.getTokensForLp = function getTokensForLp(lp, aReserve, bReserve, totalLp) {
165
+ return [new _fraction.Fraction(lp * aReserve, totalLp).quotient, new _fraction.Fraction(lp * bReserve, totalLp).quotient];
166
+ };
167
+
168
+ /**
169
+ * Holds the calculated outcome of a swap
170
+ */
171
+
172
+ /**
173
+ * Calculate swap outcome for a given input and pool parameters (input tokens, output tokens, fee).
174
+ * Throws if
175
+ * - any of the arguments are negative
176
+ * - fee is greater than or equal 1
177
+ *
178
+ * @param input The given amount of tokens to be swapped
179
+ * @param inputReserve The amount of tokens in the input reserve
180
+ * @param outputReserve The amount of tokens in the output reserve
181
+ * @param fee The liquidity provider fee
182
+ * @param protocolFee The protocol fee
183
+ * @param laf The linear amplification factor
184
+ * @returns The swap details
185
+ */
186
+ var getSwapOutput = exports.getSwapOutput = function getSwapOutput(input, inputReserve, outputReserve, fee, protocolFee, laf, roundOutputUp) {
187
+ if (input <= 0 || inputReserve <= 0 || outputReserve <= 0) throw new Error("Input and reserves must be positive");
188
+ fee = _fraction.Fraction.asFraction(fee);
189
+ if (fee.lt(_fraction.Fraction.ZERO) || fee.gte(_fraction.Fraction.ONE)) throw new Error("fee must be between 0 and 1");
190
+ protocolFee = _fraction.Fraction.asFraction(protocolFee);
191
+ if (protocolFee.lt(_fraction.Fraction.ZERO) || protocolFee.gte(_fraction.Fraction.ONE)) throw new Error("protocolFee must be between 0 and 1");
192
+ var combinedFee = fee.add(protocolFee);
193
+ if (combinedFee.gte(_fraction.Fraction.ONE)) throw new Error("Combined fee must be less than 1");
194
+ var sumInvariant = getSumInvariant(laf, inputReserve, outputReserve);
195
+ var nextInputReserve = inputReserve + input;
196
+ var newY = getNewY(nextInputReserve, laf, sumInvariant);
197
+ var deltaYPrec = outputReserve * reservePrecision - newY;
198
+ var deltaY = new _fraction.Fraction(deltaYPrec, reservePrecision);
199
+ var totalFee = combinedFee.multiply(feePrecision).multiply(deltaY.quotient).add(_fraction.Fraction.asFraction(feePrecision - 1n)).divide(feePrecision).quotient;
200
+ var totalProtocolFee = protocolFee.multiply(totalFee).divide(combinedFee).quotient;
201
+ var totalLpFee = totalFee - totalProtocolFee;
202
+ var output = deltaY.subtract(totalFee);
203
+ var safeOutput = roundOutputUp ? (output.numerator + output.denominator - 1n) / output.denominator : output.quotient;
204
+ var nextOutputReserve = outputReserve - safeOutput - totalProtocolFee;
205
+
206
+ // PRICEIMPACT: "priceImpact" is slightly misleadingly named in the industry as a whole
207
+ // just by it's name, it would imply that it's the percentage difference between
208
+ // the current price and the price after the swap, but it's actually the percentage
209
+ // difference between the real price of your swap, and the price implied by the current
210
+ // reserves; We got this wrong in v1, but this aligns it with the industry standard
211
+ // Source: https://dailydefi.org/articles/price-impact-and-how-to-calculate/
212
+ var idealPrice = getPrice(inputReserve, outputReserve, laf);
213
+ var actualPrice = new _fraction.Fraction(input, safeOutput);
214
+ var priceImpact = _fraction.Fraction.ONE.subtract(idealPrice.divide(actualPrice));
215
+ return {
216
+ input: input,
217
+ output: safeOutput,
218
+ outputLpFee: totalLpFee,
219
+ outputProtocolFee: totalProtocolFee,
220
+ nextInputReserve: nextInputReserve,
221
+ nextOutputReserve: nextOutputReserve,
222
+ nextSumInvariant: getSumInvariant(laf, nextInputReserve, nextOutputReserve),
223
+ priceImpact: priceImpact
224
+ };
225
+ };
226
+ function getPrice(aReserve, bReserve, laf) {
227
+ // dx_0 / dx_1 only, however can have any number of coins in pool
228
+ var ann = laf * 2n * aPrecision;
229
+ var sumInvariant = getSumInvariant(laf, aReserve, bReserve) / reservePrecision;
230
+ // D / n^n with n = 2
231
+ var dR = sumInvariant / 4n;
232
+ dR = dR * sumInvariant / aReserve;
233
+ dR = dR * sumInvariant / bReserve;
234
+ var xpA = ann * aReserve / aPrecision;
235
+ var p = new _fraction.Fraction(xpA + dR * aReserve / bReserve, xpA + dR);
236
+ return p;
237
+ }
238
+
239
+ /**
240
+ * Calculate input required for a swap outcome for a given output and pool parameters (input tokens, output tokens, fee).
241
+ * Throws if
242
+ * - any of the arguments are negative
243
+ * - fee is greater than or equal 1
244
+ * - output is greater than or equal to output reserve
245
+ *
246
+ * @param output
247
+ * @param inputReserve
248
+ * @param outputReserve
249
+ * @param fee
250
+ * @param protocolFee The protocol fee
251
+ * @param laf The linear amplification factor
252
+ * @returns The swap details
253
+ */
254
+ var getSwapInput = exports.getSwapInput = function getSwapInput(output, inputReserve, outputReserve, fee, protocolFee, laf) {
255
+ if (output <= 0 || inputReserve <= 0 || outputReserve <= 0) throw new Error("Output and reserves must be positive");
256
+ if (output >= outputReserve) throw new Error("Output must be less than output reserve");
257
+ fee = _fraction.Fraction.asFraction(fee);
258
+ if (fee.lt(_fraction.Fraction.ZERO) || fee.gte(_fraction.Fraction.ONE)) throw new Error("fee must be [0,1)");
259
+ protocolFee = _fraction.Fraction.asFraction(protocolFee);
260
+ if (protocolFee.lt(_fraction.Fraction.ZERO) || protocolFee.gte(_fraction.Fraction.ONE)) throw new Error("protocolFee must be between 0 and 1");
261
+ var combinedFee = fee.add(protocolFee);
262
+ if (combinedFee.gte(_fraction.Fraction.ONE)) throw new Error("Combined fee must be less than 1");
263
+
264
+ // output = rawOutput * (1-fee)
265
+ // rawOutput = output / (1-fee)
266
+ var rawOutputF = _fraction.Fraction.asFraction(output).divide(_fraction.Fraction.ONE.sub(combinedFee));
267
+ var rawOutput = (rawOutputF.numerator + rawOutputF.denominator - 1n) / rawOutputF.denominator;
268
+ var sumInvariant = getSumInvariant(laf, inputReserve, outputReserve);
269
+ var newX = getNewY(outputReserve - rawOutput, laf, sumInvariant);
270
+ var input = (newX - inputReserve * reservePrecision + reservePrecision - 1n) / reservePrecision;
271
+ var totalFee = (combinedFee.multiply(feePrecision).quotient * rawOutput + feePrecision - 1n) / feePrecision;
272
+ var totalProtocolFee = protocolFee.multiply(totalFee).divide(combinedFee).quotient;
273
+ var totalLpFee = totalFee - totalProtocolFee;
274
+ var nextInputReserve = inputReserve + input;
275
+ var nextOutputReserve = outputReserve - output - totalProtocolFee;
276
+
277
+ // See PRICEIMPACT
278
+ var idealPrice = getPrice(inputReserve, outputReserve, laf);
279
+ var actualPrice = new _fraction.Fraction(input, output);
280
+ var priceImpact = _fraction.Fraction.ONE.subtract(idealPrice.divide(actualPrice));
281
+ var nextSumInvariant = getSumInvariant(laf, nextInputReserve, nextOutputReserve);
282
+ return {
283
+ input: input,
284
+ output: output,
285
+ outputLpFee: totalLpFee,
286
+ outputProtocolFee: totalProtocolFee,
287
+ nextInputReserve: nextInputReserve,
288
+ nextOutputReserve: nextOutputReserve,
289
+ priceImpact: priceImpact,
290
+ nextSumInvariant: nextSumInvariant
291
+ };
292
+ };
293
+ //# sourceMappingURL=StableSwapsPool.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"StableSwapsPool.js","names":["_index","require","_fraction","liquidityInvariant","assetA","assetB","linearAmplification","newSumInvariant","four_a","four_x_y","d_plus_one","d_cubed","d_plus_one_cubed","x_plus_y","sixteen_a_x_y","sixteen_a_x_y_x_plus_y","f1","f2","aPrecision","exports","reservePrecision","feePrecision","getSumInvariant","a","x","y","Error","sum","d","ann","i","d_p","d_prev","getNewY","newX","aRaw","sumInvariant","yPrev","c","b","getFirstLp","laf","calculateLiquidity","aReserve","bReserve","totalLp","oldSumInvariant","newLpTokens","newTotalLpTokens","nextTotalLp","generatedLp","shareAfterDeposit","SharedPoolMath","getShare","aChange","bChange","actualDepositedA","actualDepositedB","getTokensForLp","lp","Fraction","quotient","getSwapOutput","input","inputReserve","outputReserve","fee","protocolFee","roundOutputUp","asFraction","lt","ZERO","gte","ONE","combinedFee","add","nextInputReserve","newY","deltaYPrec","deltaY","totalFee","multiply","divide","totalProtocolFee","totalLpFee","output","subtract","safeOutput","numerator","denominator","nextOutputReserve","idealPrice","getPrice","actualPrice","priceImpact","outputLpFee","outputProtocolFee","nextSumInvariant","dR","xpA","p","getSwapInput","rawOutputF","sub","rawOutput"],"sources":["../../../src/PoolMath/StableSwapsPool.ts"],"sourcesContent":["import { SharedPoolMath } from \"./index.js\";\nimport { Fraction, type TFractionLike } from \"@sundaeswap/fraction\";\n\nexport function liquidityInvariant(\n assetA: bigint,\n assetB: bigint,\n linearAmplification: bigint,\n newSumInvariant: bigint,\n) {\n // 4 * A * 4 * (x*y) * D + D^3 - (4(x*y) * (4A(x + y) + D))\n // 4A * 4xy * D + D^3 - (4xy * 4a * (x + y) + 4xy * D)\n // 16Axy * D + D^3 - (16Axy * (x + y) + 4xy * D)\n const four_a = 4n * linearAmplification;\n const four_x_y = 4n * assetA * assetB;\n const d_plus_one = newSumInvariant + 1n;\n const d_cubed = newSumInvariant * newSumInvariant * newSumInvariant;\n const d_plus_one_cubed = d_plus_one * d_plus_one * d_plus_one;\n const x_plus_y = assetA + assetB;\n const sixteen_a_x_y = four_a * four_x_y;\n const sixteen_a_x_y_x_plus_y = sixteen_a_x_y * x_plus_y;\n const f1 =\n sixteen_a_x_y * newSumInvariant +\n d_cubed -\n (sixteen_a_x_y_x_plus_y + four_x_y * newSumInvariant);\n const f2 =\n sixteen_a_x_y * d_plus_one +\n d_plus_one_cubed -\n (sixteen_a_x_y_x_plus_y + four_x_y * d_plus_one);\n return f1 <= 0n && f2 > 0n;\n}\n\nexport const aPrecision = 200n;\nexport const reservePrecision = 1_000_000_000_000n;\nexport const feePrecision = 10_000n;\n\nexport function getSumInvariant(a: bigint, x: bigint, y: bigint): bigint {\n if (a <= 0n) {\n throw new Error(\"Amplification coefficient must be positive.\");\n }\n x = x * reservePrecision;\n y = y * reservePrecision;\n a = a * aPrecision;\n const sum: bigint = x + y;\n if (sum === 0n) {\n return 0n;\n }\n\n let d = sum;\n const ann = a * 2n;\n for (let i = 0; i < 255; i++) {\n const d_p = (d * d * d) / (4n * x * y);\n const d_prev = d;\n\n d =\n (((ann * sum) / 100n + d_p * 2n) * d) /\n (((ann - 100n) * d) / 100n + 3n * d_p);\n\n if (d > d_prev) {\n if (d - d_prev <= 1) {\n if (liquidityInvariant(x, y, a / aPrecision, d)) {\n return d;\n } else {\n return d - 1n;\n }\n }\n } else {\n if (d_prev - d <= 1) {\n if (liquidityInvariant(x, y, a / aPrecision, d)) {\n return d;\n } else {\n return d - 1n;\n }\n }\n }\n }\n throw new Error(\"Failed to converge on D value after 255 iterations.\");\n}\n\nexport function getNewY(\n newX: bigint,\n aRaw: bigint,\n sumInvariant: bigint,\n): bigint {\n newX = newX * reservePrecision;\n const sum = newX;\n let yPrev: bigint;\n let c = sumInvariant;\n const ann = aRaw * aPrecision * 2n;\n\n c = (c * sumInvariant) / (newX * 2n);\n c = (c * sumInvariant * aPrecision) / 2n;\n c = c / (ann * 2n);\n const b = sum + (sumInvariant * aPrecision) / 2n / ann;\n let y = sumInvariant;\n for (let i = 0; i < 255; i++) {\n yPrev = y;\n y = (y * y + c) / (y * 2n + b - sumInvariant);\n if (y > yPrev) {\n if (y - yPrev <= 1n) {\n if (liquidityInvariant(newX, y, aRaw, sumInvariant)) {\n return y;\n } else {\n return y + 1n;\n }\n }\n } else {\n if (yPrev - y <= 1n) {\n if (liquidityInvariant(newX, y, aRaw, sumInvariant)) {\n return y;\n } else {\n return y + 1n;\n }\n }\n }\n }\n throw new Error(\"failed to converge on y value after 255 iterations.\");\n}\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, laf: bigint) =>\n getSumInvariant(laf, a, b) / reservePrecision;\n\n/**\n * Calculate the Add (Mixed-Deposit) Liquidity parameters\n *\n * TODO: Investigate way to optimize actualdeposited amounts\n *\n * @param {bigint} a - The amount of token A to deposit.\n * @param {bigint} b - The amount of token B to deposit.\n * @param {bigint} aReserve - The current reserve of token A in the pool.\n * @param {bigint} bReserve - The current reserve of token B in the pool.\n * @param {bigint} totalLp - The total lp tokens for the pool before the deposit.\n * @param {bigint} laf - The linear amplifciation factor of the pool.\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 laf: 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 oldSumInvariant = getSumInvariant(laf, aReserve, bReserve);\n\n const newSumInvariant = getSumInvariant(laf, aReserve + a, bReserve + b);\n\n const newLpTokens =\n ((newSumInvariant - oldSumInvariant) * totalLp) / oldSumInvariant;\n\n const newTotalLpTokens = totalLp + newLpTokens;\n\n return {\n nextTotalLp: newTotalLpTokens,\n generatedLp: newLpTokens,\n shareAfterDeposit: SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),\n aChange: 0n,\n bChange: 0n,\n actualDepositedA: a,\n actualDepositedB: b,\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 outputLpFee: bigint;\n outputProtocolFee: bigint;\n nextInputReserve: bigint;\n nextOutputReserve: bigint;\n nextSumInvariant: 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 * @param protocolFee The protocol fee\n * @param laf The linear amplification factor\n * @returns The swap details\n */\nexport const getSwapOutput = (\n input: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n fee: TFractionLike,\n protocolFee: TFractionLike,\n laf: bigint,\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.gte(Fraction.ONE))\n throw new Error(\"fee must be between 0 and 1\");\n\n protocolFee = Fraction.asFraction(protocolFee);\n if (protocolFee.lt(Fraction.ZERO) || protocolFee.gte(Fraction.ONE))\n throw new Error(\"protocolFee must be between 0 and 1\");\n\n const combinedFee = fee.add(protocolFee);\n if (combinedFee.gte(Fraction.ONE))\n throw new Error(\"Combined fee must be less than 1\");\n const sumInvariant = getSumInvariant(laf, inputReserve, outputReserve);\n const nextInputReserve = inputReserve + input;\n const newY = getNewY(nextInputReserve, laf, sumInvariant);\n\n const deltaYPrec = outputReserve * reservePrecision - newY;\n const deltaY = new Fraction(deltaYPrec, reservePrecision);\n const totalFee = combinedFee\n .multiply(feePrecision)\n .multiply(deltaY.quotient)\n .add(Fraction.asFraction(feePrecision - 1n))\n .divide(feePrecision).quotient;\n const totalProtocolFee = protocolFee\n .multiply(totalFee)\n .divide(combinedFee).quotient;\n const totalLpFee = totalFee - totalProtocolFee;\n const output = deltaY.subtract(totalFee);\n const safeOutput = roundOutputUp\n ? (output.numerator + output.denominator - 1n) / output.denominator\n : output.quotient;\n const nextOutputReserve = outputReserve - safeOutput - totalProtocolFee;\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 idealPrice = getPrice(inputReserve, outputReserve, laf);\n const actualPrice = new Fraction(input, safeOutput);\n const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n return {\n input,\n output: safeOutput,\n outputLpFee: totalLpFee,\n outputProtocolFee: totalProtocolFee,\n nextInputReserve,\n nextOutputReserve,\n nextSumInvariant: getSumInvariant(laf, nextInputReserve, nextOutputReserve),\n priceImpact,\n };\n};\n\nexport function getPrice(\n aReserve: bigint,\n bReserve: bigint,\n laf: bigint,\n): Fraction {\n // dx_0 / dx_1 only, however can have any number of coins in pool\n const ann = laf * 2n * aPrecision;\n const sumInvariant =\n getSumInvariant(laf, aReserve, bReserve) / reservePrecision;\n // D / n^n with n = 2\n let dR = sumInvariant / 4n;\n dR = (dR * sumInvariant) / aReserve;\n dR = (dR * sumInvariant) / bReserve;\n const xpA = (ann * aReserve) / aPrecision;\n const p = new Fraction(xpA + (dR * aReserve) / bReserve, xpA + dR);\n return p;\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 * @param protocolFee The protocol fee\n * @param laf The linear amplification factor\n * @returns The swap details\n */\nexport const getSwapInput = (\n output: bigint,\n inputReserve: bigint,\n outputReserve: bigint,\n fee: TFractionLike,\n protocolFee: TFractionLike,\n laf: bigint,\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 protocolFee = Fraction.asFraction(protocolFee);\n if (protocolFee.lt(Fraction.ZERO) || protocolFee.gte(Fraction.ONE))\n throw new Error(\"protocolFee must be between 0 and 1\");\n\n const combinedFee = fee.add(protocolFee);\n if (combinedFee.gte(Fraction.ONE))\n throw new Error(\"Combined fee must be less than 1\");\n\n // output = rawOutput * (1-fee)\n // rawOutput = output / (1-fee)\n const rawOutputF = Fraction.asFraction(output).divide(\n Fraction.ONE.sub(combinedFee),\n );\n const rawOutput =\n (rawOutputF.numerator + rawOutputF.denominator - 1n) /\n rawOutputF.denominator;\n const sumInvariant = getSumInvariant(laf, inputReserve, outputReserve);\n const newX = getNewY(outputReserve - rawOutput, laf, sumInvariant);\n const input =\n (newX - inputReserve * reservePrecision + reservePrecision - 1n) /\n reservePrecision;\n\n const totalFee =\n (combinedFee.multiply(feePrecision).quotient * rawOutput +\n feePrecision -\n 1n) /\n feePrecision;\n const totalProtocolFee = protocolFee\n .multiply(totalFee)\n .divide(combinedFee).quotient;\n\n const totalLpFee = totalFee - totalProtocolFee;\n\n const nextInputReserve = inputReserve + input;\n const nextOutputReserve = outputReserve - output - totalProtocolFee;\n\n // See PRICEIMPACT\n const idealPrice = getPrice(inputReserve, outputReserve, laf);\n const actualPrice = new Fraction(input, output);\n const priceImpact = Fraction.ONE.subtract(idealPrice.divide(actualPrice));\n\n const nextSumInvariant = getSumInvariant(\n laf,\n nextInputReserve,\n nextOutputReserve,\n );\n\n return {\n input,\n output,\n outputLpFee: totalLpFee,\n outputProtocolFee: totalProtocolFee,\n nextInputReserve,\n nextOutputReserve,\n priceImpact,\n nextSumInvariant,\n };\n};\n"],"mappings":";;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;A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CAACT,MAAM,CAACW,WAAW,CAAC,CAAC;EAEzE,IAAMI,gBAAgB,GAAG3E,eAAe,CACtCmB,GAAG,EACHmC,gBAAgB,EAChBc,iBACF,CAAC;EAED,OAAO;IACL3B,KAAK,EAALA,KAAK;IACLsB,MAAM,EAANA,MAAM;IACNU,WAAW,EAAEX,UAAU;IACvBY,iBAAiB,EAAEb,gBAAgB;IACnCP,gBAAgB,EAAhBA,gBAAgB;IAChBc,iBAAiB,EAAjBA,iBAAiB;IACjBI,WAAW,EAAXA,WAAW;IACXG,gBAAgB,EAAhBA;EACF,CAAC;AACH,CAAC","ignoreList":[]}
@@ -4,8 +4,12 @@ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" ==
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.ConstantProductPool = void 0;
7
+ exports.StableSwapsPool = exports.SharedPoolMath = exports.ConstantProductPool = void 0;
8
8
  var _ConstantProductPool = _interopRequireWildcard(require("./ConstantProductPool.js"));
9
9
  exports.ConstantProductPool = _ConstantProductPool;
10
+ var _StableSwapsPool = _interopRequireWildcard(require("./StableSwapsPool.js"));
11
+ exports.StableSwapsPool = _StableSwapsPool;
12
+ var _SharedPoolMath = _interopRequireWildcard(require("./SharedPoolMath.js"));
13
+ exports.SharedPoolMath = _SharedPoolMath;
10
14
  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); }
11
15
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/PoolMath/index.ts"],"sourcesContent":["export * as ConstantProductPool from \"./ConstantProductPool.js\";\n"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/PoolMath/index.ts"],"sourcesContent":["export * as ConstantProductPool from \"./ConstantProductPool.js\";\nexport * as StableSwapsPool from \"./StableSwapsPool.js\";\nexport * as SharedPoolMath from \"./SharedPoolMath.js\";\n"],"mappings":"","ignoreList":[]}