Skip to content

Commit b8a8f6f

Browse files
committed
enh(utils/parse.ts): update logic, better string/numberLike handling
1 parent c2eec02 commit b8a8f6f

File tree

2 files changed

+22
-13
lines changed

2 files changed

+22
-13
lines changed

lib/index.d.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@ interface AddEtherToken {
2626
interface Parse {
2727
toHex: (n: number) => string
2828
hexToInt: (s: string) => number
29-
toWei: (s: number) => number
30-
toTxWei: (n: number) => string
31-
weiToEth: (n: number) => number
29+
toWei: (s: number | string) => string
30+
toTxWei: (n: number | string) => string
31+
weiToEth: (n: number | string) => number
3232
txWeiToEth: (s: string) => number
3333
}
3434

lib/utils/parse.ts

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,27 @@
1-
const toHex = (n: number) => {
2-
if (n < 0) {
3-
// Handle negative overflow
4-
n = 0xffffffff + n + 1
5-
}
6-
return `0x${n.toString(16).toUpperCase()}`
7-
}
1+
/** expands to `000000000000000000` */
2+
const ZERO_GAP = "0".repeat(18) as any
3+
4+
const toHex = (n: number) => `0x${n.toString(16).toUpperCase()}`
85

96
const hexToInt = (str: string) => parseInt(str, 16)
107

11-
const toWei = (n: number) => n * 10 ** 18
8+
const toWei = (n: number | string) => {
9+
// Avoid returning ZERO_GAP for n==0
10+
if (n == 0) return "0"
11+
const [intPart = 0, decPart] = `${n}`.split(".")
12+
// Be optimistic that input is an int
13+
let fillGap = ZERO_GAP
14+
if (decPart) {
15+
// If decimal part exists we get it's [decPart]x10^-18 value
16+
fillGap = Math.round((`0.${decPart}` as any) * 1e18)
17+
}
18+
// If `intPart == 0` we just return decimal part value
19+
return `${intPart == 0 ? "" : intPart}${fillGap}`
20+
}
1221

13-
const toTxWei = (n: number) => toHex(toWei(n))
22+
const toTxWei = (n: number | string) => toHex(parseInt(toWei(n)))
1423

15-
const weiToEth = (n: number) => n * 10 ** -18
24+
const weiToEth = (n: string | number) => (n as any) / 1e18
1625

1726
const txWeiToEth = (s: string) => weiToEth(hexToInt(s))
1827

0 commit comments

Comments
 (0)