UNPKG

@swaptoshi/dex-module

Version:

Klayr decentralized exchange (dex) on-chain module

49 lines 2.29 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.decodePriceSqrt = decodePriceSqrt; exports.encodePriceSqrt = encodePriceSqrt; exports.encodeFeeGrowth = encodeFeeGrowth; exports.decodeFeeGrowth = decodeFeeGrowth; exports.inversePriceSqrt = inversePriceSqrt; const decimal_js_1 = require("decimal.js"); const bignumber_js_1 = require("bignumber.js"); const int_1 = require("../stores/library/int"); const core_1 = require("../stores/library/core"); decimal_js_1.default.set({ toExpPos: 9999999, toExpNeg: -9999999 }); bignumber_js_1.default.config({ EXPONENTIAL_AT: 999999, DECIMAL_PLACES: 40 }); const TEN = int_1.Uint.from(10); const FIVE_SIG_FIGS_POW = new decimal_js_1.default(10).pow(5); function decodePriceSqrt(sqrtRatioX96, decimalsToken0 = 8, decimalsToken1 = 8, inverse = false, disableFiveSigPrecision = false) { const ratioNum = new decimal_js_1.default(sqrtRatioX96) .div(2 ** 96) .pow(2) .toPrecision(5); let ratio = new decimal_js_1.default(ratioNum); if (decimalsToken1 < decimalsToken0) { ratio = ratio.mul(TEN.pow(decimalsToken0 - decimalsToken1).toString()); } else if (decimalsToken0 < decimalsToken1) { ratio = ratio.div(TEN.pow(decimalsToken1 - decimalsToken0).toString()); } if (inverse) { ratio = ratio.pow(-1); } if (!disableFiveSigPrecision && ratio.lessThan(FIVE_SIG_FIGS_POW)) { return ratio.toPrecision(5); } return ratio.toString(); } function encodePriceSqrt(reserve1, reserve0) { return int_1.Uint.from(new bignumber_js_1.default(reserve1.toString()).div(reserve0.toString()).sqrt().multipliedBy(new bignumber_js_1.default(2).pow(96)).integerValue(3).toString()); } function encodeFeeGrowth(feeGrowth, liquidity) { return core_1.FullMath.mulDiv(feeGrowth, core_1.FixedPoint128.Q128, liquidity); } function decodeFeeGrowth(feeGrowthX128, liquidity) { return core_1.FullMath.mulDiv(feeGrowthX128, liquidity, core_1.FixedPoint128.Q128); } function inversePriceSqrt(sqrtRatioX96, decimalsToken0 = 8, decimalsToken1 = 8) { const invertedPrice = decodePriceSqrt(sqrtRatioX96, decimalsToken0, decimalsToken1, true, true); return encodePriceSqrt(invertedPrice, 1).toString(); } //# sourceMappingURL=price.js.map