-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathbignumber.ts
More file actions
66 lines (58 loc) · 1.51 KB
/
Copy pathbignumber.ts
File metadata and controls
66 lines (58 loc) · 1.51 KB
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
/**
* Utility functions for handling BigNumber objects in payloads
*/
/**
* Interface representing a BigNumber object as it comes from the frontend
*/
interface BigNumberObject {
type: "BigNumber";
hex: string;
}
/**
* Type guard to check if an object is a BigNumber object
*/
function isBigNumberObject(obj: unknown): obj is BigNumberObject {
return (
typeof obj === "object" &&
obj !== null &&
"type" in obj &&
"hex" in obj &&
obj.type === "BigNumber" &&
typeof obj.hex === "string"
);
}
/**
* Converts a BigNumber object to a stringified bigint
*/
function bigNumberToStringifiedBigInt(bigNumberObj: BigNumberObject): string {
// Convert hex string to bigint, then to string
return BigInt(bigNumberObj.hex).toString();
}
/**
* Recursively transforms all BigNumber objects in an arbitrary object/array
* into stringified bigints
*/
export function transformBigNumbers(obj: unknown): unknown {
// Handle null/undefined
if (obj === null || obj === undefined) {
return obj;
}
// Handle BigNumber objects
if (isBigNumberObject(obj)) {
return bigNumberToStringifiedBigInt(obj);
}
// Handle arrays
if (Array.isArray(obj)) {
return obj.map(transformBigNumbers);
}
// Handle objects
if (typeof obj === "object") {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = transformBigNumbers(value);
}
return result;
}
// Handle primitives (string, number, boolean, etc.)
return obj;
}