forked from distribworks/xk6-ethereum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontract.go
88 lines (73 loc) · 2.13 KB
/
contract.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package ethereum
import (
"fmt"
"math/big"
"github.com/umbracle/ethgo"
"github.com/umbracle/ethgo/abi"
"github.com/umbracle/ethgo/contract"
)
// Contract exposes a contract
type Contract struct {
Contract *contract.Contract
Client *Client
SignerAddress string
}
type TxnOpts struct {
Value uint64
GasPrice uint64
GasLimit uint64
Nonce uint64
}
// Call executes a call on the contract
func (c *Contract) Call(method string, args ...interface{}) (map[string]interface{}, error) {
return c.Contract.Call(method, ethgo.Latest, args...)
}
// Txn executes a transactions on the contract and waits for it to be mined
// TODO maybe use promise
func (c *Contract) Txn(method string, opts TxnOpts, args ...interface{}) (string, error) {
txn, err := c.Contract.Txn(method, args...)
if err != nil {
return "", fmt.Errorf("failed to create contract transaction: %w", err)
}
gasPrice, err := c.Client.GasPrice()
if err != nil {
return "", fmt.Errorf("failed to get gas price: %w", err)
}
blockNumber, err := c.Client.BlockNumber()
if err != nil {
return "", fmt.Errorf("failed to get block number: %w", err)
}
block, err := c.Client.GetBlockByNumber(ethgo.BlockNumber(blockNumber), false)
if err != nil {
return "", fmt.Errorf("failed to get block: %w", err)
}
txo := contract.TxnOpts{
Value: big.NewInt(int64(opts.Value)),
GasPrice: gasPrice,
GasLimit: block.GasLimit,
Nonce: opts.Nonce,
}
txn.WithOpts(&txo)
err = txn.Do()
if err != nil {
return "", fmt.Errorf("failed to send contract transaction: %w, Tx: %+v", err, txo)
}
return txn.Hash().String(), nil
}
func (c *Contract) GetAddress() string {
return c.SignerAddress
}
func (c *Contract) FillInput(abiString string, method string, args ...interface{}) ([]byte, error) {
var input []byte
contractABI, err := abi.NewABI(abiString)
if err != nil {
return nil, fmt.Errorf("failed to parse abi: %v", err)
}
abiMethod := contractABI.GetMethod(method)
data, err := abi.Encode(args, abiMethod.Inputs)
if err != nil {
return nil, fmt.Errorf("failed to encode arguments: %v", err)
}
input = append(abiMethod.ID(), data...)
return input, nil
}