@sundaeswap/math 0.0.0-dev-20250814200018 → 0.0.0-dev-20250819140139

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.
@@ -3,12 +3,13 @@
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; } }
@@ -30,16 +31,6 @@ var getFirstLp = exports.getFirstLp = function getFirstLp(a, b) {
30
31
  */
31
32
  var getLp = exports.getLp = getFirstLp;
32
33
 
33
- /**
34
- * Get the share ratio as Fraction
35
- * @param lp
36
- * @param totalLp
37
- * @returns
38
- */
39
- var getShare = exports.getShare = function getShare(lp, totalLp) {
40
- return new _fraction.Fraction(lp, totalLp);
41
- };
42
-
43
34
  /**
44
35
  * Calculate the Add (Mixed-Deposit) Liquidity parameters
45
36
  *
@@ -83,7 +74,7 @@ var calculateLiquidity = exports.calculateLiquidity = function calculateLiquidit
83
74
  return {
84
75
  nextTotalLp: newTotalLpTokens,
85
76
  generatedLp: newLpTokens,
86
- shareAfterDeposit: getShare(newLpTokens, newTotalLpTokens),
77
+ shareAfterDeposit: _index.SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),
87
78
  bChange: bChange,
88
79
  aChange: aChange,
89
80
  actualDepositedA: actualDepositedA,
@@ -100,7 +91,7 @@ var addLiquidity = exports.addLiquidity = function addLiquidity(a, aReserve, bRe
100
91
  var nextTotalLp = new _fraction.Fraction(totalLp * (a + aReserve), aReserve).quotient;
101
92
  var lp = nextTotalLp - totalLp;
102
93
  var b = new _fraction.Fraction(bReserve * a, aReserve);
103
- var share = getShare(lp, nextTotalLp);
94
+ var share = _index.SharedPoolMath.getShare(lp, nextTotalLp);
104
95
  if (b.quotient === 0n) {
105
96
  throw new Error("The provided a asset is not enough to equal at least 1 of the b asset.");
106
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\";\nimport {\n IRatioCalculationAsset,\n IRatioCalculationResult,\n TPair,\n TRatioDirection,\n} from \"./SharedPoolMath\";\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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AAAC,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,CAACrE,KAAK,CAACrB,QAAQ,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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
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
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
+ };
6
33
  //# sourceMappingURL=SharedPoolMath.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"SharedPoolMath.js","names":[],"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"],"mappings":"","ignoreList":[]}
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":[]}
@@ -3,11 +3,15 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.aPrecision = void 0;
6
+ exports.getFirstLp = exports.calculateLiquidity = exports.aPrecision = void 0;
7
7
  exports.getNewY = getNewY;
8
+ exports.getPrice = getPrice;
8
9
  exports.getSumInvariant = getSumInvariant;
10
+ exports.getTokensForLp = exports.getSwapOutput = void 0;
9
11
  exports.liquidityInvariant = liquidityInvariant;
10
12
  exports.reservePrecision = void 0;
13
+ var _index = require("./index.js");
14
+ var _fraction = require("@sundaeswap/fraction");
11
15
  function liquidityInvariant(assetA, assetB, linearAmplification, newSumInvariant) {
12
16
  // 4 * A * 4 * (x*y) * D + D^3 - (4(x*y) * (4A(x + y) + D))
13
17
  // 4A * 4xy * D + D^3 - (4xy * 4a * (x + y) + 4xy * D)
@@ -97,4 +101,133 @@ function getNewY(newX, aRaw, sumInvariant) {
97
101
  }
98
102
  throw new Error("failed to converge on y value after 255 iterations.");
99
103
  }
104
+
105
+ /**
106
+ * Get the lp token amount for a, b
107
+ * @param a tokenA amount
108
+ * @param b tokenB amount
109
+ * @returns the minted lp token amount
110
+ */
111
+ var getFirstLp = exports.getFirstLp = function getFirstLp(a, b, laf) {
112
+ return getSumInvariant(laf, a, b);
113
+ };
114
+
115
+ /**
116
+ * Calculate the Add (Mixed-Deposit) Liquidity parameters
117
+ *
118
+ * TODO: Investigate way to optimize actualdeposited amounts
119
+ *
120
+ * @param {bigint} a - The amount of token A to deposit.
121
+ * @param {bigint} b - The amount of token B to deposit.
122
+ * @param {bigint} aReserve - The current reserve of token A in the pool.
123
+ * @param {bigint} bReserve - The current reserve of token B in the pool.
124
+ * @param {bigint} totalLp - The total lp tokens for the pool before the deposit.
125
+ * @param {bigint} laf - The linear amplifciation factor of the pool.
126
+ * @throws {Error} If the pool doesn't have enough liquidity.
127
+ * @throws {Error} If either of the deposit amounts is zero.
128
+ * @returns {Object} An object containing:
129
+ * - nextTotalLp: The total lp tokens for the pool after the deposit.
130
+ * - generatedLp: The amount of lp tokens generated by the deposit.
131
+ * - shareAfterDeposit: The depositor's share of the pool after the deposit.
132
+ */
133
+ var calculateLiquidity = exports.calculateLiquidity = function calculateLiquidity(a, b, aReserve, bReserve, totalLp, laf) {
134
+ if (aReserve === 0n && bReserve === 0n) {
135
+ throw new Error("Not enough pool liquidity");
136
+ }
137
+ if (a === 0n && b === 0n) {
138
+ throw new Error("Cannot use a deposit asset amount of 0");
139
+ }
140
+ var oldSumInvariant = getSumInvariant(laf, aReserve, bReserve);
141
+ var newSumInvariant = getSumInvariant(laf, aReserve + a, bReserve + b);
142
+ var newLpTokens = (newSumInvariant - oldSumInvariant) * totalLp / oldSumInvariant;
143
+ var newTotalLpTokens = totalLp + newLpTokens;
144
+ return {
145
+ nextTotalLp: newTotalLpTokens,
146
+ generatedLp: newLpTokens,
147
+ shareAfterDeposit: _index.SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),
148
+ aChange: 0n,
149
+ bChange: 0n,
150
+ actualDepositedA: a,
151
+ actualDepositedB: b
152
+ };
153
+ };
154
+
155
+ /**
156
+ * Get the token amounts the given lp represents
157
+ * @param lp the lp amount
158
+ * @param aReserve the pool's reserveA amount
159
+ * @param bReserve the pool's reserveB amount
160
+ * @param totalLp the pool's total minted lp currently
161
+ * @returns [a, b] token amounts
162
+ */
163
+ var getTokensForLp = exports.getTokensForLp = function getTokensForLp(lp, aReserve, bReserve, totalLp) {
164
+ return [new _fraction.Fraction(lp * aReserve, totalLp).quotient, new _fraction.Fraction(lp * bReserve, totalLp).quotient];
165
+ };
166
+
167
+ /**
168
+ * Holds the calculated outcome of a swap
169
+ */
170
+
171
+ /**
172
+ * Calculate swap outcome for a given input and pool parameters (input tokens, output tokens, fee).
173
+ * Throws if
174
+ * - any of the arguments are negative
175
+ * - fee is greater than or equal 1
176
+ *
177
+ * @param input The given amount of tokens to be swapped
178
+ * @param inputReserve The amount of tokens in the input reserve
179
+ * @param outputReserve The amount of tokens in the output reserve
180
+ * @param fee The liquidity provider fee
181
+ * @param protocolFee The protocol fee
182
+ * @param laf The linear amplification factor
183
+ * @returns The swap details
184
+ */
185
+ var getSwapOutput = exports.getSwapOutput = function getSwapOutput(input, inputReserve, outputReserve, fee, protocolFee, laf, roundOutputUp) {
186
+ if (input <= 0 || inputReserve <= 0 || outputReserve <= 0) throw new Error("Input and reserves must be positive");
187
+ fee = _fraction.Fraction.asFraction(fee);
188
+ if (fee.lt(_fraction.Fraction.ZERO) || fee.gte(_fraction.Fraction.ONE)) throw new Error("fee must be between 0 and 1");
189
+ protocolFee = _fraction.Fraction.asFraction(protocolFee);
190
+ if (protocolFee.lt(_fraction.Fraction.ZERO) || protocolFee.gte(_fraction.Fraction.ONE)) throw new Error("protocolFee must be between 0 and 1");
191
+ var combinedFee = fee.add(protocolFee);
192
+ if (combinedFee.gte(_fraction.Fraction.ONE)) throw new Error("Combined fee must be less than 1");
193
+ var sumInvariant = getSumInvariant(laf, inputReserve, outputReserve);
194
+ var nextInputReserve = inputReserve + input;
195
+ var newY = getNewY(nextInputReserve, laf, sumInvariant);
196
+ var deltaYPrec = outputReserve * reservePrecision - newY;
197
+ var deltaY = new _fraction.Fraction(deltaYPrec, reservePrecision);
198
+ var totalFee = combinedFee.multiply(deltaY);
199
+ var totalProtocolFee = protocolFee.multiply(deltaY);
200
+ var totalLpFee = totalFee.quotient - totalProtocolFee.quotient;
201
+ var output = deltaY.subtract(totalFee);
202
+ var safeOutput = roundOutputUp ? (output.numerator + output.denominator - 1n) / output.denominator : output.quotient;
203
+ var nextOutputReserve = outputReserve - safeOutput + totalLpFee;
204
+
205
+ // PRICEIMPACT: "priceImpact" is slightly misleadingly named in the industry as a whole
206
+ // just by it's name, it would imply that it's the percentage difference between
207
+ // the current price and the price after the swap, but it's actually the percentage
208
+ // difference between the real price of your swap, and the price implied by the current
209
+ // reserves; We got this wrong in v1, but this aligns it with the industry standard
210
+ // Source: https://dailydefi.org/articles/price-impact-and-how-to-calculate/
211
+ var idealPrice = getPrice(inputReserve, outputReserve, laf);
212
+ var actualPrice = new _fraction.Fraction(input, safeOutput);
213
+ var priceImpact = _fraction.Fraction.ONE.subtract(idealPrice.divide(actualPrice));
214
+ return {
215
+ input: input,
216
+ output: safeOutput,
217
+ outputLpFee: totalLpFee,
218
+ outputProtocolFee: totalProtocolFee.quotient,
219
+ nextInputReserve: nextInputReserve,
220
+ nextOutputReserve: nextOutputReserve,
221
+ nextSumInvariant: getSumInvariant(laf, nextInputReserve, nextOutputReserve),
222
+ priceImpact: priceImpact
223
+ };
224
+ };
225
+ function getPrice(aReserve, bReserve, laf) {
226
+ var dA = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 100n;
227
+ dA = aReserve <= dA ? aReserve - 1n : dA;
228
+ var sumInvariant = getSumInvariant(laf, aReserve, bReserve);
229
+ var lowY = getNewY(aReserve + dA, laf, sumInvariant);
230
+ var highY = getNewY(aReserve - dA, laf, sumInvariant);
231
+ return new _fraction.Fraction(2n * dA * reservePrecision, highY - lowY);
232
+ }
100
233
  //# sourceMappingURL=StableSwapsPool.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"StableSwapsPool.js","names":["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","getSumInvariant","a","x","y","Error","sum","d","ann","i","d_p","d_prev","getNewY","newX","aRaw","sumInvariant","yPrev","c","b"],"sources":["../../../src/PoolMath/StableSwapsPool.ts"],"sourcesContent":["export 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;\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 = 0n;\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"],"mappings":";;;;;;;;;;AAAO,SAASA,kBAAkBA,CAChCC,MAAc,EACdC,MAAc,EACdC,mBAA2B,EAC3BC,eAAuB,EACvB;EACA;EACA;EACA;EACA,IAAM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,GAAGM,IAAI,GAAGhB,UAAU,GAAG,EAAE;EAElCmB,CAAC,GAAIA,CAAC,GAAGF,YAAY,IAAKF,IAAI,GAAG,EAAE,CAAC;EACpCI,CAAC,GAAIA,CAAC,GAAGF,YAAY,GAAGjB,UAAU,GAAI,EAAE;EACxCmB,CAAC,GAAGA,CAAC,IAAIT,GAAG,GAAG,EAAE,CAAC;EAClB,IAAMU,CAAC,GAAGZ,GAAG,GAAIS,YAAY,GAAGjB,UAAU,GAAI,EAAE,GAAGU,GAAG;EACtD,IAAIJ,CAAC,GAAGW,YAAY;EACpB,KAAK,IAAIN,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAG,GAAG,EAAEA,CAAC,EAAE,EAAE;IAC5BO,KAAK,GAAGZ,CAAC;IACTA,CAAC,GAAG,CAACA,CAAC,GAAGA,CAAC,GAAGa,CAAC,KAAKb,CAAC,GAAG,EAAE,GAAGc,CAAC,GAAGH,YAAY,CAAC;IAC7C,IAAIX,CAAC,GAAGY,KAAK,EAAE;MACb,IAAIZ,CAAC,GAAGY,KAAK,IAAI,EAAE,EAAE;QACnB,IAAIjC,kBAAkB,CAAC8B,IAAI,EAAET,CAAC,EAAEU,IAAI,EAAEC,YAAY,CAAC,EAAE;UACnD,OAAOX,CAAC;QACV,CAAC,MAAM;UACL,OAAOA,CAAC,GAAG,EAAE;QACf;MACF;IACF,CAAC,MAAM;MACL,IAAIY,KAAK,GAAGZ,CAAC,IAAI,EAAE,EAAE;QACnB,IAAIrB,kBAAkB,CAAC8B,IAAI,EAAET,CAAC,EAAEU,IAAI,EAAEC,YAAY,CAAC,EAAE;UACnD,OAAOX,CAAC;QACV,CAAC,MAAM;UACL,OAAOA,CAAC,GAAG,EAAE;QACf;MACF;IACF;EACF;EACA,MAAM,IAAIC,KAAK,CAAC,qDAAqD,CAAC;AACxE","ignoreList":[]}
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","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","totalProtocolFee","totalLpFee","output","subtract","safeOutput","numerator","denominator","nextOutputReserve","idealPrice","getPrice","actualPrice","priceImpact","divide","outputLpFee","outputProtocolFee","nextSumInvariant","dA","arguments","length","undefined","lowY","highY"],"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;\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 = 0n;\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);\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\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\n const totalFee = combinedFee.multiply(deltaY);\n const totalProtocolFee = protocolFee.multiply(deltaY);\n\n const totalLpFee = totalFee.quotient - totalProtocolFee.quotient;\n\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 + totalLpFee;\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.quotient,\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 dA: bigint = 100n,\n): Fraction {\n dA = aReserve <= dA ? aReserve - 1n : dA;\n const sumInvariant = getSumInvariant(laf, aReserve, bReserve);\n const lowY = getNewY(aReserve + dA, laf, sumInvariant);\n const highY = getNewY(aReserve - dA, laf, sumInvariant);\n return new Fraction(2n * dA * reservePrecision, highY - lowY);\n}\n"],"mappings":";;;;;;;;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,S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";
3
3
  import { sqrt } from "@sundaeswap/bigint-math";
4
+ import { SharedPoolMath } from "./index.js";
5
+
4
6
  /**
5
7
  * Get the lp token amount for a, b
6
8
  * @param a tokenA amount
@@ -14,14 +16,6 @@ export const getFirstLp = (a, b) => sqrt(a * b);
14
16
  */
15
17
  export const getLp = getFirstLp;
16
18
 
17
- /**
18
- * Get the share ratio as Fraction
19
- * @param lp
20
- * @param totalLp
21
- * @returns
22
- */
23
- export const getShare = (lp, totalLp) => new Fraction(lp, totalLp);
24
-
25
19
  /**
26
20
  * Calculate the Add (Mixed-Deposit) Liquidity parameters
27
21
  *
@@ -65,7 +59,7 @@ export const calculateLiquidity = (a, b, aReserve, bReserve, totalLp) => {
65
59
  return {
66
60
  nextTotalLp: newTotalLpTokens,
67
61
  generatedLp: newLpTokens,
68
- shareAfterDeposit: getShare(newLpTokens, newTotalLpTokens),
62
+ shareAfterDeposit: SharedPoolMath.getShare(newLpTokens, newTotalLpTokens),
69
63
  bChange,
70
64
  aChange,
71
65
  actualDepositedA,
@@ -82,7 +76,7 @@ export const addLiquidity = (a, aReserve, bReserve, totalLp) => {
82
76
  const nextTotalLp = new Fraction(totalLp * (a + aReserve), aReserve).quotient;
83
77
  const lp = nextTotalLp - totalLp;
84
78
  const b = new Fraction(bReserve * a, aReserve);
85
- const share = getShare(lp, nextTotalLp);
79
+ const share = SharedPoolMath.getShare(lp, nextTotalLp);
86
80
  if (b.quotient === 0n) {
87
81
  throw new Error("The provided a asset is not enough to equal at least 1 of the b asset.");
88
82
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ConstantProductPool.js","names":["AssetAmount","Fraction","sqrt","getFirstLp","a","b","getLp","getShare","lp","totalLp","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","toString","getSwapRatio","direction","assets","calculatedAmount","rawRatio","adaIds","firstAsset","secondAsset","sort","isASpecial","includes","assetId","isBSpecial","localeCompare","quantity","fromValue","Number","decimals","display","value","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 {\n IRatioCalculationAsset,\n IRatioCalculationResult,\n TPair,\n TRatioDirection,\n} from \"./SharedPoolMath\";\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,SAASA,WAAW,QAAQ,mBAAmB;AAC/C,SAASC,QAAQ,QAA4B,sBAAsB;AACnE,SAASC,IAAI,QAAQ,yBAAyB;AAQ9C;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,UAAU,GAAGA,CAACC,CAAS,EAAEC,CAAS,KAAKH,IAAI,CAACE,CAAC,GAAGC,CAAC,CAAC;;AAE/D;AACA;AACA;AACA,OAAO,MAAMC,KAAK,GAAGH,UAAU;;AAE/B;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMI,QAAQ,GAAGA,CAACC,EAAU,EAAEC,OAAe,KA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BAAgB,EAAEA,gBAAgB;IAClCe,OAAO,EAAEf,gBAAgB,CAACgB,KAAK,CAACpB,QAAQ,CAAC,CAAC;IAC1CqB,eAAe,EAAErF,QAAQ,CAACkC,UAAU,CAACmC,QAAQ,CAAC;IAC9CiB,WAAW,EAAElB,gBAAgB,CAACc,QAAQ,GAAG,CAAC;IAC1CK,iBAAiB,EAAElB,QAAQ,CAACL,QAAQ,CAAC,CAAC,KAAK;EAC7C,CAAC;AACH","ignoreList":[]}
1
+ {"version":3,"file":"ConstantProductPool.js","names":["AssetAmount","Fraction","sqrt","SharedPoolMath","getFirstLp","a","b","getLp","calculateLiquidity","aReserve","bReserve","totalLp","Error","bInUnitsOfA","aChange","bChange","actualDepositedA","actualDepositedB","newLpTokens","newTotalLpTokens","nextTotalLp","generatedLp","shareAfterDeposit","getShare","addLiquidity","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","toString","getSwapRatio","direction","assets","calculatedAmount","rawRatio","adaIds","firstAsset","secondAsset","sort","isASpecial","includes","assetId","isBSpecial","localeCompare","quantity","fromValue","Number","decimals","display","value","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,SAASA,WAAW,QAAQ,mBAAmB;AAC/C,SAASC,QAAQ,QAA4B,sBAAsB;AACnE,SAASC,IAAI,QAAQ,yBAAyB;AAC9C,SAASC,cAAc,QAAQ,YAAY;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,UAAU,GAAGA,CAACC,CAAS,EAAEC,CAAS,KAAKJ,IAAI,CAACG,CAAC,GAAGC,CAAC,CAAC;;AAE/D;AACA;AACA;AACA,OAAO,MAAMC,KAAK,GAAGH,UAAU;;AAE/B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMI,kBAAkB,GAAGA,CAChCH,CAAS,EACTC,CAAS,EACTG,QAAgB,EAChBC,QAAgB,EAChBC,OAAe,KACZ;EACH,IAAIF,QAAQ,KAAK,EAAE,IAAIC,QAAQ,KAAK,EAAE,EAAE;IACtC,MAAM,IAAIE,KAAK,CAAC,2BAA2B,CAAC;EAC9C;EAEA,IAAIP,CAAC,KAAK,EAAE,IAAIC,CAAC,KAAK,EAAE,EAAE;IACxB,MAAM,IAAIM,KAAK,CAAC,wCAAwC,CAAC;EAC3D;EAEA,MAAMC,WAAW,GAAIP,CAAC,GAAGG,QAAQ,GAAIC,QAAQ;EAE7C,IAAII,OAAe;EACnB,IAAIC,OAAe;EAEnB,IAAIF,WAAW,GAAGR,CAAC,EAAE;IACnBU,OAAO,GAAIL,QAAQ,IAAIG,WAAW,GAAGR,CAAC,CAAC,GAAII,QAAQ;IACnDK,OAAO,GAAG,EAAE;EACd,CAAC,MAAM;IACLA,OAAO,GAAGT,CAAC,GAAGQ,WAAW;IACzBE,OAAO,GAAG,EAAE;EACd;;EAEA;EACA,MAAMC,gBAAgB,GAAGX,CAA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ACZ,QAAQ,CAAC,GAAG,EAAE,KAAKG,WAAW,CAACU,QAAQ,GAAGX,UAAU,CAACW,QAAQ,CAAC,EACrEX,UAAU,CAACW,QACb,CAAC;EACH,CAAC,MAAM;IACLb,QAAQ,GAAGX,cAAc,CAACc,WAAW,CAACO,QAAQ,EAAER,UAAU,CAACQ,QAAQ,CAAC;IACpEX,gBAAgB,GAAGtE,WAAW,CAACkF,SAAS,CACtCC,MAAM,CAACZ,QAAQ,CAAC,GAAG,EAAE,KAAKE,UAAU,CAACW,QAAQ,GAAGV,WAAW,CAACU,QAAQ,CAAC,EACrEV,WAAW,CAACU,QACd,CAAC;EACH;EAEA,OAAO;IACLd,gBAAgB,EAAEA,gBAAgB;IAClCe,OAAO,EAAEf,gBAAgB,CAACgB,KAAK,CAACpB,QAAQ,CAAC,CAAC;IAC1CqB,eAAe,EAAEtF,QAAQ,CAACmC,UAAU,CAACmC,QAAQ,CAAC;IAC9CiB,WAAW,EAAElB,gBAAgB,CAACc,QAAQ,GAAG,CAAC;IAC1CK,iBAAiB,EAAElB,QAAQ,CAACL,QAAQ,CAAC,CAAC,KAAK;EAC7C,CAAC;AACH","ignoreList":[]}
@@ -1,2 +1,26 @@
1
- export {};
1
+ import { Fraction } from "@sundaeswap/fraction";
2
+
3
+ /**
4
+ * The direction of a ratio (A per B or B per A)
5
+ */
6
+
7
+ /**
8
+ * Asset used in a ratio calculation
9
+ */
10
+
11
+ /**
12
+ * The result of a ratio calculation on a pool
13
+ */
14
+
15
+ /**
16
+ * The amounts for a token pair
17
+ */
18
+
19
+ /**
20
+ * Get the share ratio as Fraction
21
+ * @param lp
22
+ * @param totalLp
23
+ * @returns
24
+ */
25
+ export const getShare = (lp, totalLp) => new Fraction(lp, totalLp);
2
26
  //# sourceMappingURL=SharedPoolMath.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"SharedPoolMath.js","names":[],"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"],"mappings":"","ignoreList":[]}
1
+ {"version":3,"file":"SharedPoolMath.js","names":["Fraction","getShare","lp","totalLp"],"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,SAASA,QAAQ,QAAQ,sBAAsB;;AAE/C;AACA;AACA;;AAGA;AACA;AACA;;AAOA;AACA;AACA;;AASA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,QAAQ,GAAGA,CAACC,EAAU,EAAEC,OAAe,KAClD,IAAIH,QAAQ,CAACE,EAAE,EAAEC,OAAO,CAAC","ignoreList":[]}