-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathethconv.go
56 lines (51 loc) · 1.18 KB
/
ethconv.go
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
package ethconv
import (
"fmt"
"math/big"
)
// FromWei convert from wei to a unit
func FromWei(amount *big.Int, unit string) (*big.Float, error) {
result := new(big.Float)
result.SetInt(amount)
if unit == Wei {
return result, nil
}
value, err := GetUnitValue(unit)
if err != nil {
return nil, err
}
return result.Quo(result, new(big.Float).SetInt(value)), nil
}
// ToWei convert a unit to wei
func ToWei(amount *big.Float, unit string) (*big.Int, error) {
if unit == Wei {
return bigFloatToBigInt(amount), nil
}
value, err := GetUnitValue(unit)
if err != nil {
return nil, err
}
amount.Mul(amount, new(big.Float).SetInt(value))
result := new(big.Int)
amount.Int(result)
return result, nil
}
// GetUnitValue from units map
func GetUnitValue(unit string) (*big.Int, error) {
value, ok := units[unit]
if !ok {
return nil, fmt.Errorf("unit %s is not supported", unit)
}
result := new(big.Int)
result.SetString(value, 10)
return result, nil
}
// bigFloatToBigInt conversion
func bigFloatToBigInt(value *big.Float) *big.Int {
per := new(big.Float)
per.SetInt(big.NewInt(1000000000000000000))
value.Mul(value, per)
result := new(big.Int)
value.Int(result)
return result
}