This repository has been archived by the owner on May 9, 2024. It is now read-only.
/
util.go
74 lines (65 loc) 路 2.05 KB
/
util.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
69
70
71
72
73
74
package calls
import (
"errors"
"math"
gomath "math"
"math/big"
"strings"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
func GetSolidityFunctionSig(in []byte) [4]byte {
var res [4]byte
hash := crypto.Keccak256Hash(in)
copy(res[:], hash[:])
return res
}
func SliceTo32Bytes(in []byte) [32]byte {
var res [32]byte
copy(res[:], in)
return res
}
// ToCallArg is the function that converts ethereum.CallMsg into more abstract map
// This is done for matter of making EVMClient more abstract since some go-ethereum forks uses different messages types
func ToCallArg(msg ethereum.CallMsg) map[string]interface{} {
arg := map[string]interface{}{
"from": msg.From,
"to": msg.To,
}
if len(msg.Data) > 0 {
arg["data"] = hexutil.Bytes(msg.Data)
}
if msg.Value != nil {
arg["value"] = (*hexutil.Big)(msg.Value)
}
if msg.Gas != 0 {
arg["gas"] = hexutil.Uint64(msg.Gas)
}
if msg.GasPrice != nil {
arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
}
return arg
}
// UserAmountToWei converts decimal user friendly representation of token amount to 'Wei' representation with provided amount of decimal places
// eg UserAmountToWei(1, 5) => 100000
func UserAmountToWei(amount string, decimal *big.Int) (*big.Int, error) {
amountFloat, ok := big.NewFloat(0).SetString(amount)
if !ok {
return nil, errors.New("wrong amount format")
}
ethValueFloat := new(big.Float).Mul(amountFloat, big.NewFloat(math.Pow10(int(decimal.Int64()))))
ethValueFloatString := strings.Split(ethValueFloat.Text('f', int(decimal.Int64())), ".")
i, ok := big.NewInt(0).SetString(ethValueFloatString[0], 10)
if !ok {
return nil, errors.New(ethValueFloat.Text('f', int(decimal.Int64())))
}
return i, nil
}
func WeiAmountToUser(amount *big.Int, decimals *big.Int) (*big.Float, error) {
amountFloat, ok := big.NewFloat(0).SetString(amount.String())
if !ok {
return nil, errors.New("wrong amount format")
}
return new(big.Float).Quo(amountFloat, big.NewFloat(gomath.Pow10(int(decimals.Int64())))), nil
}