-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathunits.go
More file actions
97 lines (88 loc) · 2.21 KB
/
units.go
File metadata and controls
97 lines (88 loc) · 2.21 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package eth
import (
"math"
"math/big"
"strconv"
)
// Conversion factors
const (
WeiPerEth float64 = 1e18
WeiPerGwei float64 = 1e9
WeiPerMilliEth float64 = 1e15
)
// Convert wei to eth
func WeiToEth(wei *big.Int) float64 {
if wei == nil {
return 0
}
var weiFloat big.Float
var eth big.Float
weiFloat.SetInt(wei)
eth.Quo(&weiFloat, big.NewFloat(WeiPerEth))
eth64, _ := eth.Float64()
return eth64
}
// Convert eth to wei
func EthToWei(eth float64) *big.Int {
var ethFloat big.Float
var weiFloat big.Float
var wei big.Int
ethFloat.SetString(strconv.FormatFloat(eth, 'f', -1, 64))
weiFloat.Mul(ðFloat, big.NewFloat(WeiPerEth))
weiFloat.Int(&wei)
return &wei
}
// Convert wei to gigawei
func WeiToGwei(wei *big.Int) float64 {
if wei == nil {
return 0
}
var weiFloat big.Float
var gwei big.Float
weiFloat.SetInt(wei)
gwei.Quo(&weiFloat, big.NewFloat(WeiPerGwei))
gwei64, _ := gwei.Float64()
return gwei64
}
// Convert gigawei to wei
func GweiToWei(gwei float64) *big.Int {
var gweiFloat big.Float
var weiFloat big.Float
var wei big.Int
gweiFloat.SetString(strconv.FormatFloat(gwei, 'f', -1, 64))
weiFloat.Mul(&gweiFloat, big.NewFloat(WeiPerGwei))
weiFloat.Int(&wei)
return &wei
}
// Convert milliEth to wei
func MilliEthToWei(milliEth float64) *big.Int {
var milliEthFloat big.Float
var weiFloat big.Float
var wei big.Int
milliEthFloat.SetString(strconv.FormatFloat(milliEth, 'f', -1, 64))
weiFloat.Mul(&milliEthFloat, big.NewFloat(WeiPerMilliEth))
weiFloat.Int(&wei)
return &wei
}
// Converts float amount to big.Int considering a token's decimals
func EthToWeiWithDecimals(amountRaw float64, decimals uint8) *big.Int {
var ethFloat big.Float
var weiFloat big.Float
var wei big.Int
ethFloat.SetString(strconv.FormatFloat(amountRaw, 'f', -1, 64))
weiFloat.Mul(ðFloat, big.NewFloat(math.Pow(10, float64(decimals))))
weiFloat.Int(&wei)
return &wei
}
// Converts big.Int to float64 considering a token's decimals
func WeiToEthWithDecimals(amount *big.Int, decimals uint8) float64 {
if amount == nil {
return 0
}
var weiFloat big.Float
var eth big.Float
weiFloat.SetInt(amount)
eth.Quo(&weiFloat, big.NewFloat(math.Pow(10, float64(decimals))))
eth64, _ := eth.Float64()
return eth64
}