@melonproject/token-math
Version:
A small helper library to do precision safe calculations
61 lines (60 loc) • 1.9 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const BigInteger_1 = __importDefault(require("../bigInteger/BigInteger"));
const createToken_1 = __importDefault(require("../token/createToken"));
const appendDecimals_1 = __importDefault(require("../token/appendDecimals"));
const toBI_1 = __importDefault(require("../bigInteger/toBI"));
const toBigInteger = (token, value) => {
if (typeof value === "string" && value.replace(",", ".").includes("."))
return appendDecimals_1.default(token, value);
if (typeof value === "string")
return new BigInteger_1.default(value);
if (typeof value === "number")
return appendDecimals_1.default(token, value.toString());
return toBI_1.default(value);
};
/**
* Shortcut to create a quantity. If second argument is a number,
* the according decimals are appended automatically. So shortest call:
*
* ```typescript
* let someMelons = createQuantity('MLN', 2.34);
*
* // results in:
* someMelons = {
* token: {
* symbol: 'MLN',
* decimals: 18
* }
* quantity: new BigInteger('2340000000000000000');
* }
* ```
*
* This only works if the last argument is a number. Otherwise:
*
* ```typescript
* let someMelons = createQuantity('MLN', "234");
*
* // results in
* someMelons = {
* token: {
* symbol: 'MLN',
* decimals: 18
* }
* quantity: new BigInteger('234');
* }
*/
const createQuantity = (tokenOrSymbol, quantityArg) => {
const token = typeof tokenOrSymbol === "string"
? createToken_1.default(tokenOrSymbol)
: tokenOrSymbol;
const quantity = toBigInteger(token, quantityArg);
return {
token,
quantity
};
};
exports.default = createQuantity;