ethers.js/src.ts/utils/fixednumber.ts

644 lines
22 KiB
TypeScript
Raw Normal View History

2022-11-28 05:50:34 +03:00
/**
* The **FixedNumber** class permits using values with decimal places,
* using fixed-pont math.
*
* Fixed-point math is still based on integers under-the-hood, but uses an
* internal offset to store fractional components below, and each operation
* corrects for this after each operation.
2022-11-28 05:50:34 +03:00
*
2022-12-03 05:23:13 +03:00
* @_section: api/utils/fixed-point-math:Fixed-Point Maths [about-fixed-point-math]
2022-11-28 05:50:34 +03:00
*/
import { getBytes } from "./data.js";
import { assert, assertArgument, assertPrivate } from "./errors.js";
2022-11-30 21:46:26 +03:00
import {
2022-12-10 02:21:45 +03:00
getBigInt, fromTwos, mask, toBigInt
2022-11-30 21:46:26 +03:00
} from "./maths.js";
import { defineProperties } from "./properties.js";
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
import type { BigNumberish, BytesLike } from "./index.js";
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
const BN_N1 = BigInt(-1);
const BN_0 = BigInt(0);
const BN_1 = BigInt(1);
const BN_5 = BigInt(5);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
const _guard = { };
2022-09-05 23:14:43 +03:00
// Constant to pull zeros from for multipliers
2022-11-30 21:46:26 +03:00
let Zeros = "0000";
while (Zeros.length < 80) { Zeros += Zeros; }
2022-09-05 23:14:43 +03:00
// Returns a string "1" followed by decimal "0"s
2022-11-30 21:46:26 +03:00
function getTens(decimals: number): bigint {
let result = Zeros;
while (result.length < decimals) { result += result; }
return BigInt("1" + result.substring(0, decimals));
}
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
/*
* Returns a new FixedFormat for %%value%%.
*
* If %%value%% is specified as a ``number``, the bit-width is
* 128 bits and %%value%% is used for the ``decimals``.
*
* A string %%value%% may begin with ``fixed`` or ``ufixed``
* for signed and unsigned respectfully. If no other properties
* are specified, the bit-width is 128-bits with 18 decimals.
*
* To specify the bit-width and demicals, append them separated
* by an ``"x"`` to the %%value%%.
*
* For example, ``ufixed128x18`` describes an unsigned, 128-bit
* wide format with 18 decimals.
*
* If %%value%% is an other object, its properties for ``signed``,
* ``width`` and ``decimals`` are checked.
*/
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* A description of a fixed-point arithmetic field.
*
* When specifying the fixed format, the values override the default of
* a ``fixed128x18``, which implies a signed 128-bit value with 18
* decimals of precision.
*
* The alias ``fixed`` and ``ufixed`` can be used for ``fixed128x18`` and
* ``ufixed128x18`` respectively.
2022-11-28 05:50:34 +03:00
*
2022-11-30 21:46:26 +03:00
* When a fixed format string begins with a ``u``, it indicates the field
* is unsigned, so any negative values will overflow. The first number
* indicates the bit-width and the second number indicates the decimal
* precision.
*
* When a ``number`` is used for a fixed format, it indicates the number
* of decimal places, and the default width and signed-ness will be used.
*
* The bit-width must be byte aligned and the decimals can be at most 80.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
export type FixedFormat = number | string | {
signed?: boolean,
width?: number,
decimals?: number
};
function checkValue(val: bigint, format: _FixedFormat, safeOp?: string): bigint {
const width = BigInt(format.width);
if (format.signed) {
const limit = (BN_1 << (width - BN_1));
assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
operation: <string>safeOp, fault: "overflow", value: val
});
if (val > BN_0) {
val = fromTwos(mask(val, width), width);
} else {
val = -fromTwos(mask(-val, width), width);
}
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
} else {
const limit = (BN_1 << width);
assert(safeOp == null || (val >= 0 && val < limit), "overflow", "NUMERIC_FAULT", {
operation: <string>safeOp, fault: "overflow", value: val
});
val = (((val % limit) + limit) % limit) & (limit - BN_1);
}
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
return val;
}
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
type _FixedFormat = { signed: boolean, width: number, decimals: number, name: string }
function getFormat(value?: FixedFormat): _FixedFormat {
if (typeof(value) === "number") { value = `fixed128x${value}` }
let signed = true;
let width = 128;
let decimals = 18;
if (typeof(value) === "string") {
// Parse the format string
if (value === "fixed") {
// defaults...
} else if (value === "ufixed") {
signed = false;
} else {
const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
assertArgument(match, "invalid fixed format", "format", value);
signed = (match[1] !== "u");
width = parseInt(match[2]);
decimals = parseInt(match[3]);
}
} else if (value) {
// Extract the values from the object
const v: any = value;
const check = (key: string, type: string, defaultValue: any): any => {
if (v[key] == null) { return defaultValue; }
assertArgument(typeof(v[key]) === type,
"invalid fixed format (" + key + " not " + type +")", "format." + key, v[key]);
return v[key];
}
signed = check("signed", "boolean", signed);
width = check("width", "number", width);
decimals = check("decimals", "number", decimals);
}
assertArgument((width % 8) === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width);
assertArgument(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
const name = (signed ? "": "u") + "fixed" + String(width) + "x" + String(decimals);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
return { signed, width, decimals, name };
}
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
function toString(val: bigint, decimals: number) {
let negative = "";
if (val < BN_0) {
negative = "-";
val *= BN_N1;
2022-09-05 23:14:43 +03:00
}
2022-11-30 21:46:26 +03:00
let str = val.toString();
// No decimal point for whole values
2022-11-30 23:39:59 +03:00
if (decimals === 0) { return (negative + str); }
2022-11-30 21:46:26 +03:00
2022-11-30 23:39:59 +03:00
// Pad out to the whole component (including a whole digit)
while (str.length <= decimals) { str = Zeros + str; }
2022-11-30 21:46:26 +03:00
// Insert the decimal point
const index = str.length - decimals;
str = str.substring(0, index) + "." + str.substring(index);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
// Trim the whole component (leaving at least one 0)
while (str[0] === "0" && str[1] !== ".") {
str = str.substring(1);
}
// Trim the decimal component (leaving at least one 0)
while (str[str.length - 1] === "0" && str[str.length - 2] !== ".") {
str = str.substring(0, str.length - 1);
}
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
return (negative + str);
2022-09-05 23:14:43 +03:00
}
2022-11-30 21:46:26 +03:00
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* A FixedNumber represents a value over its [[FixedFormat]]
* arithmetic field.
*
* A FixedNumber can be used to perform math, losslessly, on
* values which have decmial places.
*
* A FixedNumber has a fixed bit-width to store values in, and stores all
* values internally by multiplying the value by 10 raised to the power of
* %%decimals%%.
*
* If operations are performed that cause a value to grow too high (close to
* positive infinity) or too low (close to negative infinity), the value
* is said to //overflow//.
*
* For example, an 8-bit signed value, with 0 decimals may only be within
* the range ``-128`` to ``127``; so ``-128 - 1`` will overflow and become
* ``127``. Likewise, ``127 + 1`` will overflow and become ``-127``.
*
* Many operation have a normal and //unsafe// variant. The normal variant
* will throw a [[NumericFaultError]] on any overflow, while the //unsafe//
* variant will silently allow overflow, corrupting its value value.
2022-11-28 05:50:34 +03:00
*
2022-11-30 21:46:26 +03:00
* If operations are performed that cause a value to become too small
* (close to zero), the value loses precison and is said to //underflow//.
*
* For example, an value with 1 decimal place may store a number as small
* as ``0.1``, but the value of ``0.1 / 2`` is ``0.05``, which cannot fit
* into 1 decimal place, so underflow occurs which means precision is lost
* and the value becomes ``0``.
*
* Some operations have a normal and //signalling// variant. The normal
* variant will silently ignore underflow, while the //signalling// variant
* will thow a [[NumericFaultError]] on underflow.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
export class FixedNumber {
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
/**
* The specific fixed-point arithmetic field for this value.
*/
readonly format!: string;
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
readonly #format: _FixedFormat;
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
// The actual value (accounting for decimals)
#val: bigint;
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
// A base-10 value to multiple values by to maintain the magnitude
readonly #tens: bigint;
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
/**
* This is a property so console.log shows a human-meaningful value.
*
* @private
*/
readonly _value!: string;
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
// Use this when changing this file to get some typing info,
// but then switch to any to mask the internal type
//constructor(guard: any, value: bigint, format: _FixedFormat) {
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
/**
* @private
*/
constructor(guard: any, value: bigint, format: any) {
assertPrivate(guard, _guard, "FixedNumber");
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
this.#val = value;
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
this.#format = format;
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
const _value = toString(value, format.decimals);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
defineProperties<FixedNumber>(this, { format: format.name, _value });
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
this.#tens = getTens(format.decimals);
}
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
* If true, negative values are permitted, otherwise only
* positive values and zero are allowed.
*/
2022-11-30 21:46:26 +03:00
get signed(): boolean { return this.#format.signed; }
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* The number of bits available to store the value.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
get width(): number { return this.#format.width; }
2022-11-28 05:50:34 +03:00
/**
* The number of decimal places in the fixed-point arithment field.
*/
2022-11-30 21:46:26 +03:00
get decimals(): number { return this.#format.decimals; }
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* The value as an integer, based on the smallest unit the
* [[decimals]] allow.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
get value(): bigint { return this.#val; }
#checkFormat(other: FixedNumber): void {
assertArgument(this.format === other.format,
"incompatible format; use fixedNumber.toFormat", "other", other);
}
#checkValue(val: bigint, safeOp?: string): FixedNumber {
/*
const width = BigInt(this.width);
if (this.signed) {
const limit = (BN_1 << (width - BN_1));
assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
operation: <string>safeOp, fault: "overflow", value: val
});
if (val > BN_0) {
val = fromTwos(mask(val, width), width);
} else {
val = -fromTwos(mask(-val, width), width);
}
} else {
const masked = mask(val, width);
assert(safeOp == null || (val >= 0 && val === masked), "overflow", "NUMERIC_FAULT", {
operation: <string>safeOp, fault: "overflow", value: val
});
val = masked;
}
*/
val = checkValue(val, this.#format, safeOp);
return new FixedNumber(_guard, val, this.#format);
}
#add(o: FixedNumber, safeOp?: string): FixedNumber {
this.#checkFormat(o);
return this.#checkValue(this.#val + o.#val, safeOp);
}
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Returns a new [[FixedNumber]] with the result of %%this%% added
* to %%other%%, ignoring overflow.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
addUnsafe(other: FixedNumber): FixedNumber { return this.#add(other); }
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Returns a new [[FixedNumber]] with the result of %%this%% added
* to %%other%%. A [[NumericFaultError]] is thrown if overflow
* occurs.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
add(other: FixedNumber): FixedNumber { return this.#add(other, "add"); }
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
#sub(o: FixedNumber, safeOp?: string): FixedNumber {
this.#checkFormat(o);
return this.#checkValue(this.#val - o.#val, safeOp);
2022-09-05 23:14:43 +03:00
}
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Returns a new [[FixedNumber]] with the result of %%other%% subtracted
* from %%this%%, ignoring overflow.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
subUnsafe(other: FixedNumber): FixedNumber { return this.#sub(other); }
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
/**
* Returns a new [[FixedNumber]] with the result of %%other%% subtracted
* from %%this%%. A [[NumericFaultError]] is thrown if overflow
* occurs.
*/
sub(other: FixedNumber): FixedNumber { return this.#sub(other, "sub"); }
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
#mul(o: FixedNumber, safeOp?: string): FixedNumber {
this.#checkFormat(o);
return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp);
}
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
/**
* Returns a new [[FixedNumber]] with the result of %%this%% multiplied
* by %%other%%, ignoring overflow and underflow (precision loss).
*/
mulUnsafe(other: FixedNumber): FixedNumber { return this.#mul(other); }
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
/**
* Returns a new [[FixedNumber]] with the result of %%this%% multiplied
* by %%other%%. A [[NumericFaultError]] is thrown if overflow
* occurs.
*/
mul(other: FixedNumber): FixedNumber { return this.#mul(other, "mul"); }
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
/**
* Returns a new [[FixedNumber]] with the result of %%this%% multiplied
* by %%other%%. A [[NumericFaultError]] is thrown if overflow
* occurs or if underflow (precision loss) occurs.
*/
mulSignal(other: FixedNumber): FixedNumber {
this.#checkFormat(other);
const value = this.#val * other.#val;
assert((value % this.#tens) === BN_0, "precision lost during signalling mul", "NUMERIC_FAULT", {
operation: "mulSignal", fault: "underflow", value: this
});
return this.#checkValue(value / this.#tens, "mulSignal");
2022-09-05 23:14:43 +03:00
}
2022-11-30 21:46:26 +03:00
#div(o: FixedNumber, safeOp?: string): FixedNumber {
assert(o.#val !== BN_0, "division by zero", "NUMERIC_FAULT", {
operation: "div", fault: "divide-by-zero", value: this
});
this.#checkFormat(o);
return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp);
}
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Returns a new [[FixedNumber]] with the result of %%this%% divided
* by %%other%%, ignoring underflow (precision loss). A
* [[NumericFaultError]] is thrown if overflow occurs.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
divUnsafe(other: FixedNumber): FixedNumber { return this.#div(other); }
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Returns a new [[FixedNumber]] with the result of %%this%% divided
* by %%other%%, ignoring underflow (precision loss). A
* [[NumericFaultError]] is thrown if overflow occurs.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
div(other: FixedNumber): FixedNumber { return this.#div(other, "div"); }
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
/**
* Returns a new [[FixedNumber]] with the result of %%this%% divided
* by %%other%%. A [[NumericFaultError]] is thrown if underflow
* (precision loss) occurs.
*/
divSignal(other: FixedNumber): FixedNumber {
assert(other.#val !== BN_0, "division by zero", "NUMERIC_FAULT", {
operation: "div", fault: "divide-by-zero", value: this
});
this.#checkFormat(other);
const value = (this.#val * this.#tens);
assert((value % other.#val) === BN_0, "precision lost during signalling div", "NUMERIC_FAULT", {
operation: "divSignal", fault: "underflow", value: this
});
return this.#checkValue(value / other.#val, "divSignal");
2022-09-05 23:14:43 +03:00
}
2022-11-30 21:46:26 +03:00
/**
* Returns a comparison result between %%this%% and %%other%%.
*
* This is suitable for use in sorting, where ``-1`` implies %%this%%
* is smaller, ``1`` implies %%other%% is larger and ``0`` implies
* both are equal.
*/
cmp(other: FixedNumber): number {
let a = this.value, b = other.value;
// Coerce a and b to the same magnitude
const delta = this.decimals - other.decimals;
if (delta > 0) {
b *= getTens(delta);
} else if (delta < 0) {
a *= getTens(-delta);
}
// Comnpare
if (a < b) { return -1; }
if (a > b) { return -1; }
return 0;
}
2022-09-05 23:14:43 +03:00
/**
2022-11-30 21:46:26 +03:00
* Returns true if %%other%% is equal to %%this%%.
*/
2022-11-30 21:46:26 +03:00
eq(other: FixedNumber): boolean { return this.cmp(other) === 0; }
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Returns true if %%other%% is less than to %%this%%.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
lt(other: FixedNumber): boolean { return this.cmp(other) < 0; }
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Returns true if %%other%% is less than or equal to %%this%%.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
lte(other: FixedNumber): boolean { return this.cmp(other) <= 0; }
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Returns true if %%other%% is greater than to %%this%%.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
gt(other: FixedNumber): boolean { return this.cmp(other) > 0; }
/**
* Returns true if %%other%% is greater than or equal to %%this%%.
*/
gte(other: FixedNumber): boolean { return this.cmp(other) >= 0; }
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
* Returns a new [[FixedNumber]] which is the largest **integer**
* that is less than or equal to %%this%%.
*
* The decimal component of the result will always be ``0``.
*/
2022-09-05 23:14:43 +03:00
floor(): FixedNumber {
2022-11-30 21:46:26 +03:00
let val = this.#val;
if (this.#val < BN_0) { val -= this.#tens - BN_1; }
val = (this.#val / this.#tens) * this.#tens;
return this.#checkValue(val, "floor");
2022-09-05 23:14:43 +03:00
}
2022-11-28 05:50:34 +03:00
/**
* Returns a new [[FixedNumber]] which is the smallest **integer**
* that is greater than or equal to %%this%%.
*
* The decimal component of the result will always be ``0``.
*/
2022-09-05 23:14:43 +03:00
ceiling(): FixedNumber {
2022-11-30 21:46:26 +03:00
let val = this.#val;
if (this.#val > BN_0) { val += this.#tens - BN_1; }
val = (this.#val / this.#tens) * this.#tens;
return this.#checkValue(val, "ceiling");
2022-09-05 23:14:43 +03:00
}
2022-11-28 05:50:34 +03:00
/**
* Returns a new [[FixedNumber]] with the decimal component
2022-11-30 21:46:26 +03:00
* rounded up on ties at %%decimals%% places.
2022-11-28 05:50:34 +03:00
*/
2022-09-05 23:14:43 +03:00
round(decimals?: number): FixedNumber {
if (decimals == null) { decimals = 0; }
2022-11-30 21:46:26 +03:00
// Not enough precision to not already be rounded
if (decimals >= this.decimals) { return this; }
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
const delta = this.decimals - decimals;
const bump = BN_5 * getTens(delta - 1);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
let value = this.value + bump;
const tens = getTens(delta);
value = (value / tens) * tens;
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
checkValue(value, this.#format, "round");
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
return new FixedNumber(_guard, value, this.#format);
2022-09-05 23:14:43 +03:00
}
2022-11-28 05:50:34 +03:00
/**
* Returns true if %%this%% is equal to ``0``.
*/
2022-11-30 21:46:26 +03:00
isZero(): boolean { return (this.#val === BN_0); }
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
* Returns true if %%this%% is less than ``0``.
*/
2022-11-30 21:46:26 +03:00
isNegative(): boolean { return (this.#val < BN_0); }
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
* Returns the string representation of %%this%%.
*/
2022-11-30 21:46:26 +03:00
toString(): string { return this._value; }
2022-09-05 23:14:43 +03:00
2022-11-28 05:50:34 +03:00
/**
* Returns a float approximation.
*
* Due to IEEE 754 precission (or lack thereof), this function
* can only return an approximation and most values will contain
* rounding errors.
*/
2022-09-05 23:14:43 +03:00
toUnsafeFloat(): number { return parseFloat(this.toString()); }
2022-11-28 05:50:34 +03:00
/**
* Return a new [[FixedNumber]] with the same value but has had
* its field set to %%format%%.
*
* This will throw if the value cannot fit into %%format%%.
*/
2022-11-30 21:46:26 +03:00
toFormat(format: FixedFormat): FixedNumber {
return FixedNumber.fromString(this.toString(), format);
2022-09-05 23:14:43 +03:00
}
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Creates a new [[FixedNumber]] for %%value%% divided by
2022-11-28 05:50:34 +03:00
* %%decimal%% places with %%format%%.
*
2022-11-30 21:46:26 +03:00
* This will throw a [[NumericFaultError]] if %%value%% (once adjusted
* for %%decimals%%) cannot fit in %%format%%, either due to overflow
* or underflow (precision loss).
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
static fromValue(_value: BigNumberish, decimals?: number, _format?: FixedFormat): FixedNumber {
2022-11-28 05:50:34 +03:00
if (decimals == null) { decimals = 0; }
2022-11-30 21:46:26 +03:00
const format = getFormat(_format);
let value = getBigInt(_value, "value");
const delta = decimals - format.decimals;
if (delta > 0) {
const tens = getTens(delta);
assert((value % tens) === BN_0, "value loses precision for format", "NUMERIC_FAULT", {
operation: "fromValue", fault: "underflow", value: _value
});
value /= tens;
} else if (delta < 0) {
value *= getTens(-delta);
}
checkValue(value, format, "fromValue");
return new FixedNumber(_guard, value, format);
2022-09-05 23:14:43 +03:00
}
2022-11-28 05:50:34 +03:00
/**
* Creates a new [[FixedNumber]] for %%value%% with %%format%%.
*
2022-11-30 21:46:26 +03:00
* This will throw a [[NumericFaultError]] if %%value%% cannot fit
* in %%format%%, either due to overflow or underflow (precision loss).
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
static fromString(_value: string, _format?: FixedFormat): FixedNumber {
const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/);
assertArgument(match && (match[2].length + match[3].length) > 0, "invalid FixedNumber string value", "value", _value);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
const format = getFormat(_format);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
let whole = (match[2] || "0"), decimal = (match[3] || "");
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
// Pad out the decimals
while (decimal.length < format.decimals) { decimal += Zeros; }
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
// Check precision is safe
assert(decimal.substring(format.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", {
operation: "fromString", fault: "underflow", value: _value
});
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
// Remove extra padding
decimal = decimal.substring(0, format.decimals);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
const value = BigInt(match[1] + whole + decimal)
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
checkValue(value, format, "fromString");
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
return new FixedNumber(_guard, value, format);
2022-09-05 23:14:43 +03:00
}
2022-11-28 05:50:34 +03:00
/**
2022-11-30 21:46:26 +03:00
* Creates a new [[FixedNumber]] with the big-endian representation
* %%value%% with %%format%%.
*
* This will throw a [[NumericFaultError]] if %%value%% cannot fit
* in %%format%% due to overflow.
2022-11-28 05:50:34 +03:00
*/
2022-11-30 21:46:26 +03:00
static fromBytes(_value: BytesLike, _format?: FixedFormat): FixedNumber {
let value = toBigInt(getBytes(_value, "value"));
const format = getFormat(_format);
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
if (format.signed) { value = fromTwos(value, format.width); }
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
checkValue(value, format, "fromBytes");
2022-09-05 23:14:43 +03:00
2022-11-30 21:46:26 +03:00
return new FixedNumber(_guard, value, format);
2022-09-05 23:14:43 +03:00
}
}
2022-11-30 21:46:26 +03:00
//const f1 = FixedNumber.fromString("12.56", "fixed16x2");
//const f2 = FixedNumber.fromString("0.3", "fixed16x2");
//console.log(f1.divSignal(f2));
//const BUMP = FixedNumber.from("0.5");