-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.go
More file actions
112 lines (101 loc) · 2.33 KB
/
Copy pathmodule.go
File metadata and controls
112 lines (101 loc) · 2.33 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package ethgo
import (
"encoding/hex"
"fmt"
"github.com/umbracle/ethgo"
"github.com/umbracle/ethgo/wallet"
"go.k6.io/k6/js/modules"
"math/big"
)
type Module struct{}
// Ensure the module is loaded
func init() {
m := &Module{}
modules.Register("k6/x/ethgo", m)
}
// JS: ethgo.signLegacyTx({nonce, gasPrice, gas, to, value, data, chainId}, privKeyHex) → hex string
func (m *Module) SignLegacyTx(tx map[string]interface{}, privKeyHex string) (string, error) {
t := ðgo.Transaction{
Type: ethgo.TransactionLegacy,
}
// Required fields
if v, ok := tx["nonce"]; ok {
t.Nonce = uint64(intFromIface(v))
}
if v, ok := tx["gasPrice"]; ok {
t.GasPrice = uint64(intFromIface(v))
}
if v, ok := tx["gas"]; ok {
t.Gas = uint64(intFromIface(v))
}
if v, ok := tx["to"]; ok {
addr := ethgo.HexToAddress(v.(string))
t.To = &addr
}
if v, ok := tx["value"]; ok {
t.Value = big.NewInt(intFromIface(v))
}
if v, ok := tx["data"]; ok {
dataHex := v.(string)
if len(dataHex) > 2 && dataHex[:2] == "0x" {
dataHex = dataHex[2:]
}
d, _ := hex.DecodeString(dataHex)
t.Input = d
}
if v, ok := tx["chainId"]; ok {
t.ChainID = big.NewInt(intFromIface(v))
}
pk, err := hex.DecodeString(privKeyHex)
if err != nil {
return "", err
}
key, err := wallet.NewWalletFromPrivKey(pk)
signer := wallet.NewEIP155Signer(t.ChainID.Uint64())
signed, err := signer.SignTx(t, key)
if err != nil {
return "", err
}
raw, err := signed.MarshalRLPTo(nil)
if err != nil {
return "", err
}
return "0x" + hex.EncodeToString(raw), nil
}
// JS: ethgo.hexToAddress(str) → "0x.."
func (m *Module) HexToAddress(addr string) string {
return ethgo.HexToAddress(addr).String()
}
func intFromIface(v interface{}) int64 {
switch vv := v.(type) {
case float64:
return int64(vv)
case int64:
return vv
case int32:
return int64(vv)
case uint64:
return int64(vv)
case uint32:
return int64(vv)
case int:
return int64(vv)
case *big.Int:
return vv.Int64()
case big.Int:
return vv.Int64()
default:
panic(fmt.Sprintf("unexpected type for int field: %T", v))
}
}
func (m *Module) PrivateKeyToAddress(privateKeyHex string) (string, error) {
pk, err := hex.DecodeString(privateKeyHex)
if err != nil {
return "", err
}
key, err := wallet.NewWalletFromPrivKey(pk)
if err != nil {
return "", err
}
return key.Address().String(), nil
}