@sen-use/web3
Version:
The library for Sentre
64 lines (63 loc) • 2.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.utilsBN = void 0;
const anchor_1 = require("@project-serum/anchor");
exports.utilsBN = {
/**
* Add decimals to the number
* @param num
* @param decimals
* @returns
*/
decimalize: (num, decimals) => {
if (!num)
return new anchor_1.BN(0);
if (decimals < 0 || decimals % 1 !== 0)
throw new Error('decimals must be an integer greater than zero');
const n = num.toString();
const m = n.split('.');
if (m.length > 2)
throw new Error('Invalid number');
if (!decimals)
return new anchor_1.BN(m[0]);
if (m.length === 1)
return new anchor_1.BN(num).mul(new anchor_1.BN(Math.pow(10, decimals)));
if (m[1].length >= decimals)
return new anchor_1.BN(m[0] + m[1].substring(0, decimals));
else
return new anchor_1.BN(m[0] + m[1] + '0'.repeat(decimals - m[1].length));
},
/**
* Remove decimals from the number
* @param numBN
* @param decimals
* @returns
*/
undecimalize: (numBN, decimals) => {
if (decimals < 0 || decimals % 1 !== 0)
throw new Error('decimals must be an integer greater than zero');
if (!numBN)
return '0';
const n = numBN.toString();
if (!decimals)
return n;
let integer = n.length > decimals ? n.substring(0, n.length - decimals) : '0';
let fraction = '';
if (n.length > decimals)
fraction = n.substring(n.length - decimals, n.length);
else if (n.length === decimals)
fraction = n;
else
fraction = '0'.repeat(decimals - n.length) + n;
fraction = fraction.split('');
while (fraction[fraction.length - 1] === '0')
fraction.pop();
fraction = fraction.join('');
if (!fraction)
return integer;
return integer + '.' + fraction;
},
toNumber: (numBN) => {
return Number(exports.utilsBN.undecimalize(numBN, 0));
},
};