Added JSON support to BigNumber (#1010).

This commit is contained in:
Richard Moore 2020-08-24 23:15:03 -04:00
parent 17fdca8994
commit 8facc1a530
No known key found for this signature in database
GPG Key ID: 665176BE8E9DC651

@ -198,6 +198,10 @@ export class BigNumber implements Hexable {
return this._hex; return this._hex;
} }
toJSON(key?: string): any {
return { type: "BigNumber", hex: this.toHexString() };
}
static from(value: any): BigNumber { static from(value: any): BigNumber {
if (value instanceof BigNumber) { return value; } if (value instanceof BigNumber) { return value; }
@ -225,22 +229,39 @@ export class BigNumber implements Hexable {
return BigNumber.from(String(value)); return BigNumber.from(String(value));
} }
if (typeof(value) === "bigint") { const anyValue = <any>value;
return BigNumber.from((<any>value).toString());
if (typeof(anyValue) === "bigint") {
return BigNumber.from(anyValue.toString());
} }
if (isBytes(value)) { if (isBytes(anyValue)) {
return BigNumber.from(hexlify(value)); return BigNumber.from(hexlify(anyValue));
} }
if ((<any>value)._hex && isHexString((<any>value)._hex)) { if (anyValue) {
return BigNumber.from((<any>value)._hex);
// Hexable interface (takes piority)
if (anyValue.toHexString) {
const hex = anyValue.toHexString();
if (typeof(hex) === "string") {
return BigNumber.from(hex);
} }
if ((<any>value).toHexString) { } else {
value = (<any>value).toHexString(); // For now, handle legacy JSON-ified values (goes away in v6)
if (typeof(value) === "string") { let hex = anyValue._hex;
return BigNumber.from(value);
// New-form JSON
if (hex == null && anyValue.type === "BigNumber") {
hex = anyValue.hex;
}
if (typeof(hex) === "string") {
if (isHexString(hex) || (hex[0] === "-" && isHexString(hex.substring(1)))) {
return BigNumber.from(hex);
}
}
} }
} }