-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathfixednumber.ts
363 lines (273 loc) · 12.2 KB
/
fixednumber.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
"use strict";
import { arrayify, BytesLike, hexZeroPad, isBytes } from "@ethersproject/bytes";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
import { BigNumber, BigNumberish, isBigNumberish } from "./bignumber";
const _constructorGuard = { };
const Zero = BigNumber.from(0);
const NegativeOne = BigNumber.from(-1);
function throwFault(message: string, fault: string, operation: string, value?: any): never {
const params: any = { fault: fault, operation: operation };
if (value !== undefined) { params.value = value; }
return logger.throwError(message, Logger.errors.NUMERIC_FAULT, params);
}
// Constant to pull zeros from for multipliers
let zeros = "0";
while (zeros.length < 256) { zeros += zeros; }
// Returns a string "1" followed by decimal "0"s
function getMultiplier(decimals: BigNumberish): string {
if (typeof(decimals) !== "number") {
try {
decimals = BigNumber.from(decimals).toNumber();
} catch (e) { }
}
if (typeof(decimals) === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) {
return ("1" + zeros.substring(0, decimals));
}
return logger.throwArgumentError("invalid decimal size", "decimals", decimals);
}
export function formatFixed(value: BigNumberish, decimals?: string | BigNumberish): string {
if (decimals == null) { decimals = 0; }
const multiplier = getMultiplier(decimals);
// Make sure wei is a big number (convert as necessary)
value = BigNumber.from(value);
const negative = value.lt(Zero);
if (negative) { value = value.mul(NegativeOne); }
let fraction = value.mod(multiplier).toString();
while (fraction.length < multiplier.length - 1) { fraction = "0" + fraction; }
// Strip training 0
fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
const whole = value.div(multiplier).toString();
value = whole + "." + fraction;
if (negative) { value = "-" + value; }
return value;
}
export function parseFixed(value: string, decimals?: BigNumberish): BigNumber {
if (decimals == null) { decimals = 0; }
const multiplier = getMultiplier(decimals);
if (typeof(value) !== "string" || !value.match(/^-?[0-9.,]+$/)) {
logger.throwArgumentError("invalid decimal value", "value", value);
}
if (multiplier.length - 1 === 0) {
return BigNumber.from(value);
}
// Is it negative?
const negative = (value.substring(0, 1) === "-");
if (negative) { value = value.substring(1); }
if (value === ".") {
logger.throwArgumentError("missing value", "value", value);
}
// Split it into a whole and fractional part
const comps = value.split(".");
if (comps.length > 2) {
logger.throwArgumentError("too many decimal points", "value", value);
}
let whole = comps[0], fraction = comps[1];
if (!whole) { whole = "0"; }
if (!fraction) { fraction = "0"; }
// Prevent underflow
if (fraction.length > multiplier.length - 1) {
throwFault("fractional component exceeds decimals", "underflow", "parseFixed");
}
// Fully pad the string with zeros to get to wei
while (fraction.length < multiplier.length - 1) { fraction += "0"; }
const wholeValue = BigNumber.from(whole);
const fractionValue = BigNumber.from(fraction);
let wei = (wholeValue.mul(multiplier)).add(fractionValue);
if (negative) { wei = wei.mul(NegativeOne); }
return wei;
}
export class FixedFormat {
readonly signed: boolean;
readonly width: number;
readonly decimals: number;
readonly name: string;
readonly _multiplier: string;
constructor(constructorGuard: any, signed: boolean, width: number, decimals: number) {
if (constructorGuard !== _constructorGuard) {
logger.throwError("cannot use FixedFormat constructor; use FixedFormat.from", Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new FixedFormat"
});
}
this.signed = signed;
this.width = width;
this.decimals = decimals;
this.name = (signed ? "": "u") + "fixed" + String(width) + "x" + String(decimals);
this._multiplier = getMultiplier(decimals);
Object.freeze(this);
}
static from(value: any): FixedFormat {
if (value instanceof FixedFormat) { return value; }
let signed = true;
let width = 128;
let decimals = 18;
if (typeof(value) === "string") {
if (value === "fixed") {
// defaults...
} else if (value === "ufixed") {
signed = false;
} else if (value != null) {
const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
if (!match) { logger.throwArgumentError("invalid fixed format", "format", value); }
signed = (match[1] !== "u");
width = parseInt(match[2]);
decimals = parseInt(match[3]);
}
} else if (value) {
const check = (key: string, type: string, defaultValue: any): any => {
if (value[key] == null) { return defaultValue; }
if (typeof(value[key]) !== type) {
logger.throwArgumentError("invalid fixed format (" + key + " not " + type +")", "format." + key, value[key]);
}
return value[key];
}
signed = check("signed", "boolean", signed);
width = check("width", "number", width);
decimals = check("decimals", "number", decimals);
}
if (width % 8) {
logger.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width);
}
if (decimals > 80) {
logger.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals);
}
return new FixedFormat(_constructorGuard, signed, width, decimals);
}
}
export class FixedNumber {
readonly format: FixedFormat;
readonly _hex: string;
readonly _value: string;
readonly _isFixedNumber: boolean;
constructor(constructorGuard: any, hex: string, value: string, format?: FixedFormat) {
logger.checkNew(new.target, FixedNumber);
if (constructorGuard !== _constructorGuard) {
logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from", Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new FixedFormat"
});
}
this.format = format;
this._hex = hex;
this._value = value;
this._isFixedNumber = true;
Object.freeze(this);
}
_checkFormat(other: FixedNumber): void {
if (this.format.name !== other.format.name) {
logger.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other);
}
}
addUnsafe(other: FixedNumber): FixedNumber {
this._checkFormat(other);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.add(b), this.format.decimals, this.format);
}
subUnsafe(other: FixedNumber): FixedNumber {
this._checkFormat(other);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format);
}
mulUnsafe(other: FixedNumber): FixedNumber {
this._checkFormat(other);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format);
}
divUnsafe(other: FixedNumber): FixedNumber {
this._checkFormat(other);
const a = parseFixed(this._value, this.format.decimals);
const b = parseFixed(other._value, other.format.decimals);
return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format);
}
// @TODO: Support other rounding algorithms
round(decimals?: number): FixedNumber {
if (decimals == null) { decimals = 0; }
if (decimals < 0 || decimals > 80 || (decimals % 1)) {
logger.throwArgumentError("invalid decimal count", "decimals", decimals);
}
// If we are already in range, we're done
let comps = this.toString().split(".");
if (comps[1].length <= decimals) { return this; }
// Bump the value up by the 0.00...0005
const bump = "0." + zeros.substring(0, decimals) + "5";
comps = this.addUnsafe(FixedNumber.fromString(bump, this.format))._value.split(".");
// Now it is safe to truncate
return FixedNumber.fromString(comps[0] + "." + comps[1].substring(0, decimals));
}
isZero(): boolean {
return (this._value === "0.0");
}
toString(): string { return this._value; }
toHexString(width?: number): string {
if (width == null) { return this._hex; }
if (width % 8) { logger.throwArgumentError("invalid byte width", "width", width); }
const hex = BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString();
return hexZeroPad(hex, width / 8);
}
toUnsafeFloat(): number { return parseFloat(this.toString()); }
toFormat(format: FixedFormat | string): FixedNumber {
return FixedNumber.fromString(this._value, format);
}
static fromValue(value: BigNumber, decimals?: BigNumberish, format?: FixedFormat | string): FixedNumber {
// If decimals looks more like a format, and there is no format, shift the parameters
if (format == null && decimals != null && !isBigNumberish(decimals)) {
format = decimals;
decimals = null;
}
if (decimals == null) { decimals = 0; }
if (format == null) { format = "fixed"; }
return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format));
}
static fromString(value: string, format?: FixedFormat | string): FixedNumber {
if (format == null) { format = "fixed"; }
const fixedFormat = FixedFormat.from(format);
const numeric = parseFixed(value, fixedFormat.decimals);
if (!fixedFormat.signed && numeric.lt(Zero)) {
throwFault("unsigned value cannot be negative", "overflow", "value", value);
}
let hex: string = null;
if (fixedFormat.signed) {
hex = numeric.toTwos(fixedFormat.width).toHexString();
} else {
hex = numeric.toHexString();
hex = hexZeroPad(hex, fixedFormat.width / 8);
}
const decimal = formatFixed(numeric, fixedFormat.decimals);
return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
}
static fromBytes(value: BytesLike, format?: FixedFormat | string): FixedNumber {
if (format == null) { format = "fixed"; }
const fixedFormat = FixedFormat.from(format);
if (arrayify(value).length > fixedFormat.width / 8) {
throw new Error("overflow");
}
let numeric = BigNumber.from(value);
if (fixedFormat.signed) { numeric = numeric.fromTwos(fixedFormat.width); }
const hex = numeric.toTwos((fixedFormat.signed ? 0: 1) + fixedFormat.width).toHexString();
const decimal = formatFixed(numeric, fixedFormat.decimals);
return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
}
static from(value: any, format?: FixedFormat | string) {
if (typeof(value) === "string") {
return FixedNumber.fromString(value, format);
}
if (isBytes(value)) {
return FixedNumber.fromBytes(value, format);
}
try {
return FixedNumber.fromValue(value, 0, format);
} catch (error) {
// Allow NUMERIC_FAULT to bubble up
if (error.code !== Logger.errors.INVALID_ARGUMENT) {
throw error;
}
}
return logger.throwArgumentError("invalid FixedNumber value", "value", value);
}
static isFixedNumber(value: any): value is FixedNumber {
return !!(value && value._isFixedNumber);
}
}