@melonproject/token-math
Version:
A small helper library to do precision safe calculations
38 lines (37 loc) • 2.08 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const appendDecimals_1 = __importDefault(require("../token/appendDecimals"));
const createQuantity_1 = __importDefault(require("../quantity/createQuantity"));
const divide_1 = __importDefault(require("../bigInteger/divide"));
const multiply_1 = __importDefault(require("../bigInteger/multiply"));
const power_1 = __importDefault(require("../bigInteger/power"));
const toBI_1 = __importDefault(require("../bigInteger/toBI"));
/**
* Takes a price and normalizes it:
* Brings the base quantity to 1.0 and changes the quote value accordingly.
*
* Warning: This is a destructive operation (?).
*
* Example: For a token with 4 decimals the normalized base quantity is:
* 10000
*/
const normalize = (price) => {
const base = createQuantity_1.default(price.base.token, 1);
const decimalsDifference = price.base.token.decimals - price.quote.token.decimals;
const quoteQuantityIgnoreDecimals = divide_1.default(multiply_1.default(appendDecimals_1.default(price.quote.token, 1), price.quote.quantity,
// Add the sum of quote + base decimals to prevent loss of information during division
power_1.default(toBI_1.default(10), toBI_1.default(price.quote.token.decimals + price.base.token.decimals))), price.base.quantity);
const decimalsDifferenceFactor = power_1.default(toBI_1.default(10), toBI_1.default(decimalsDifference));
const withDecimalsCleaned = divide_1.default(decimalsDifference >= 0
? multiply_1.default(quoteQuantityIgnoreDecimals, decimalsDifferenceFactor)
: divide_1.default(quoteQuantityIgnoreDecimals, decimalsDifferenceFactor), power_1.default(toBI_1.default(10), toBI_1.default(price.quote.token.decimals + price.base.token.decimals)));
const quote = createQuantity_1.default(price.quote.token, withDecimalsCleaned);
return {
base,
quote
};
};
exports.default = normalize;