-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (78 loc) · 1.83 KB
/
index.js
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
const ethers = require("ethers");
function isObject(o) {
return typeof o === "object" && o !== null && !!Object.keys(o).length;
}
function isBN(bn) {
const result = Object.keys(bn).length === 2 && (bn.type === "BigNumber" || bn.type === "BigInt") && /^0x(?:[a-fA-F0-9]{2})*$/.test(bn.hex || "");
return result;
}
function convert(bn) {
try {
if (bn.type === "BigNumber") {
return ethers.BigNumber.from(bn.hex);
} else if (bn.type === "BigInt") {
return BigInt(bn.hex);
}
} catch (e) {}
return bn;
}
function bigNumberify(key, value) {
if (typeof key === "string" && typeof value === "function") {
let obj = JSON.parse(key);
if (isBN(obj)) {
return convert(JSON.parse(key));
} else {
return obj;
}
} else if (typeof key === "object") {
return scan(key);
} else {
return typeof value === "object" && isBN(value)
? convert(value)
: value;
}
}
function stringify(key, value) {
if (typeof value === "bigint") {
// Change the key and value if the person is alive
let hex = value.toString(16);
if (hex.length % 2) {
hex = '0' + hex;
}
return 'status', {
type: "BigInt",
hex: '0x' + hex,
};
}
return value;
}
bigNumberify.stringify = stringify;
function scan(obj) {
const manage = (item, i) => {
if (isObject(item[i])) {
if (isBN(item[i])) {
item[i] = convert(item[i]);
} else {
item[i] = bigNumberify(item[i]);
}
}
};
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
try {
manage(obj, i);
} catch (e) {}
}
} else if (isObject(obj)) {
if (isBN(obj)) {
obj = convert(obj);
} else
for (let i in obj) {
try {
manage(obj, i);
} catch (e) {}
}
}
return obj;
}
module.exports = bigNumberify;