Added JSON support to BigNumber (#1010).
This commit is contained in:
parent
17fdca8994
commit
8facc1a530
@ -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);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((<any>value).toHexString) {
|
// Hexable interface (takes piority)
|
||||||
value = (<any>value).toHexString();
|
if (anyValue.toHexString) {
|
||||||
if (typeof(value) === "string") {
|
const hex = anyValue.toHexString();
|
||||||
return BigNumber.from(value);
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user