lotus-sdk
Version:
Central repository for several classes of tools for integrating with, and building for, the Lotusia ecosystem
107 lines (106 loc) • 2.99 kB
JavaScript
import { Preconditions } from './util/preconditions.js';
const UNITS = {
XPI: [1e6, 6],
mXPI: [1e3, 3],
uXPI: [1e2, 2],
bits: [1e2, 2],
satoshis: [1, 0],
};
export class Unit {
_value;
static XPI = 'XPI';
static mXPI = 'mXPI';
static uXPI = 'uXPI';
static bits = 'bits';
static satoshis = 'satoshis';
constructor(amount, code) {
if (typeof code === 'number') {
if (code <= 0) {
throw new Error(`Invalid exchange rate: ${code}`);
}
amount = amount / code;
code = Unit.XPI;
}
this._value = this._from(amount, code);
Object.keys(UNITS).forEach(key => {
Object.defineProperty(this, key, {
get: () => this.to(key),
enumerable: true,
});
});
}
static fromObject(data) {
Preconditions.checkArgument(typeof data === 'object', 'data', 'Argument is expected to be an object');
return new Unit(data.amount, data.code);
}
static fromXPI(amount) {
return new Unit(amount, Unit.XPI);
}
static fromMillis(amount) {
return new Unit(amount, Unit.mXPI);
}
static fromMilis = Unit.fromMillis;
static fromMicros(amount) {
return new Unit(amount, Unit.bits);
}
static fromBits = Unit.fromMicros;
static fromSatoshis(amount) {
if (typeof amount === 'bigint') {
return new Unit(Number(amount), Unit.satoshis);
}
return new Unit(amount, Unit.satoshis);
}
static fromFiat(amount, rate) {
return new Unit(amount, rate);
}
_from(amount, code) {
if (!UNITS[code]) {
throw new Error(`Unrecognized unit code: ${code}`);
}
return BigInt(Math.round(amount * UNITS[code][0]));
}
to(code) {
if (typeof code === 'number') {
if (code <= 0) {
throw new Error(`Invalid exchange rate: ${code}`);
}
return parseFloat((this.to(Unit.XPI) * code).toFixed(2));
}
if (!UNITS[code]) {
throw new Error(`Unrecognized unit code: ${code}`);
}
const divisor = BigInt(UNITS[code][0]);
const value = Number(this._value) / Number(divisor);
return parseFloat(value.toFixed(UNITS[code][1]));
}
toXPI() {
return this.to(Unit.XPI);
}
toMillis() {
return this.to(Unit.mXPI);
}
toMilis = this.toMillis;
toMicros() {
return this.to(Unit.bits);
}
toBits = this.toMicros;
toSatoshis() {
return this._value;
}
atRate(rate) {
return this.to(rate);
}
toString() {
return this._value.toString() + ' satoshis';
}
toObject() {
return {
amount: this.to(Unit.XPI),
code: Unit.XPI,
};
}
toJSON = this.toObject;
inspect() {
return '<Unit: ' + this.toString() + '>';
}
}