-
Notifications
You must be signed in to change notification settings - Fork 1
/
wei.go
68 lines (54 loc) · 1.71 KB
/
wei.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
57
58
59
60
61
62
63
64
65
66
67
68
// Copyright gotools (https://github.com/zerjioang/gotools)
// SPDX-License-Identifier: GNU GPL v3
package eth
import (
"math/big"
"github.com/zerjioang/gotools/lib/decimal"
"github.com/zerjioang/gotools/util/str"
"github.com/zerjioang/gotools/lib/eth/fixtures"
"github.com/zerjioang/gotools/lib/eth/fixtures/crypto"
)
// ToDecimal wei to decimals
func ToDecimal(ivalue interface{}, decimals int) decimal.Decimal {
value := new(big.Int)
switch v := ivalue.(type) {
case string:
value.SetString(v, 10)
case *big.Int:
value = v
}
mul := decimal.NewFromFloat(float64(10)).Pow(decimal.NewFromFloat(float64(decimals)))
num, _ := decimal.NewFromString(value.String())
result := num.Div(mul)
return result
}
// ToWei decimals to wei
func ToWei(iamount interface{}, decimals int) *big.Int {
amount := decimal.NewFromFloat(0)
switch v := iamount.(type) {
case string:
amount, _ = decimal.NewFromString(v)
case float64:
amount = decimal.NewFromFloat(v)
case int64:
amount = decimal.NewFromFloat(float64(v))
case decimal.Decimal:
amount = v
case *decimal.Decimal:
amount = *v
}
mul := decimal.NewFromFloat(float64(10)).Pow(decimal.NewFromFloat(float64(decimals)))
result := amount.Mul(mul)
wei := new(big.Int)
wei.SetString(result.String(), 10)
return wei
}
// CalcGasCost calculate gas cost given gas limit (units) and gas price (wei)
func CalcGasCost(gasLimit uint64, gasPrice *big.Int) *big.Int {
gasLimitBig := big.NewInt(int64(gasLimit))
return gasLimitBig.Mul(gasLimitBig, gasPrice)
}
// LogTopicHash generates the log topic hash given the event function declaration signature
func LogTopicHash(functionSignature string) fixtures.Hash {
return crypto.Keccak256Hash(str.UnsafeBytes(functionSignature))
}