From 8facc1a5305b1f699aa3afc5a0a692abe7927652 Mon Sep 17 00:00:00 2001 From: Richard Moore Date: Mon, 24 Aug 2020 23:15:03 -0400 Subject: [PATCH] Added JSON support to BigNumber (#1010). --- packages/bignumber/src.ts/bignumber.ts | 43 +++++++++++++++++++------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/packages/bignumber/src.ts/bignumber.ts b/packages/bignumber/src.ts/bignumber.ts index 8bf9197a..285eb1ea 100644 --- a/packages/bignumber/src.ts/bignumber.ts +++ b/packages/bignumber/src.ts/bignumber.ts @@ -198,6 +198,10 @@ export class BigNumber implements Hexable { return this._hex; } + toJSON(key?: string): any { + return { type: "BigNumber", hex: this.toHexString() }; + } + static from(value: any): BigNumber { if (value instanceof BigNumber) { return value; } @@ -225,22 +229,39 @@ export class BigNumber implements Hexable { return BigNumber.from(String(value)); } - if (typeof(value) === "bigint") { - return BigNumber.from((value).toString()); + const anyValue = value; + + if (typeof(anyValue) === "bigint") { + return BigNumber.from(anyValue.toString()); } - if (isBytes(value)) { - return BigNumber.from(hexlify(value)); + if (isBytes(anyValue)) { + return BigNumber.from(hexlify(anyValue)); } - if ((value)._hex && isHexString((value)._hex)) { - return BigNumber.from((value)._hex); - } + if (anyValue) { - if ((value).toHexString) { - value = (value).toHexString(); - if (typeof(value) === "string") { - return BigNumber.from(value); + // Hexable interface (takes piority) + if (anyValue.toHexString) { + const hex = anyValue.toHexString(); + if (typeof(hex) === "string") { + return BigNumber.from(hex); + } + + } else { + // For now, handle legacy JSON-ified values (goes away in v6) + let hex = anyValue._hex; + + // 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); + } + } } }