Skip to content

Commit

Permalink
Added JSON support to BigNumber (#1010).
Browse files Browse the repository at this point in the history
  • Loading branch information
ricmoo committed Aug 25, 2020
1 parent 17fdca8 commit 8facc1a
Showing 1 changed file with 32 additions and 11 deletions.
43 changes: 32 additions & 11 deletions packages/bignumber/src.ts/bignumber.ts
Expand Up @@ -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; }

Expand Down Expand Up @@ -225,22 +229,39 @@ export class BigNumber implements Hexable {
return BigNumber.from(String(value));
}

if (typeof(value) === "bigint") {
return BigNumber.from((<any>value).toString());
}
const anyValue = <any>value;

if (isBytes(value)) {
return BigNumber.from(hexlify(value));
if (typeof(anyValue) === "bigint") {
return BigNumber.from(anyValue.toString());
}

if ((<any>value)._hex && isHexString((<any>value)._hex)) {
return BigNumber.from((<any>value)._hex);
if (isBytes(anyValue)) {
return BigNumber.from(hexlify(anyValue));
}

if ((<any>value).toHexString) {
value = (<any>value).toHexString();
if (typeof(value) === "string") {
return BigNumber.from(value);
if (anyValue) {

// 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);
}
}
}
}

Expand Down

0 comments on commit 8facc1a

Please sign in to comment.