-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathethereum.go
221 lines (181 loc) · 6.77 KB
/
ethereum.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Package ethereum higher level Go API's for writing applications and smart
// contracts on the Ethereum blockchain.
package ethereum
import (
"context"
"crypto/ecdsa"
"fmt"
"math/big"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
)
// Set of networks supported by the smart package.
const (
NetworkHTTPLocalhost = "http://localhost:8545"
NetworkLocalhost = "zarf/ethereum/geth.ipc"
NetworkGoerli = "https://rpc.ankr.com/eth_goerli"
)
// =============================================================================
// Backend represents behavior for interacting with an ethereum node.
type Backend interface {
bind.ContractBackend
bind.DeployBackend
TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, bool, error)
TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
BalanceAt(ctx context.Context, contract common.Address, blockNumber *big.Int) (*big.Int, error)
Network() string
ChainID() *big.Int
}
// Client provides an API for working with smart contracts.
type Client struct {
Backend
address common.Address
privateKey *ecdsa.PrivateKey
}
// NewClient provides an API for accessing an Ethereum node to perform blockchain
// related operations. It required the private key you want to use for this
// instance when accessing the node.
func NewClient(backend Backend, privateKey *ecdsa.PrivateKey) (*Client, error) {
clt := Client{
Backend: backend,
address: crypto.PubkeyToAddress(privateKey.PublicKey),
privateKey: privateKey,
}
return &clt, nil
}
// =============================================================================
// Address returns the current address calculated from the private key.
func (clt *Client) Address() common.Address {
return clt.address
}
// Network returns the network information for the connected network.
func (clt *Client) Network() string {
return clt.Backend.Network()
}
// ChainID returns the chain information for the connected network.
func (clt *Client) ChainID() int {
return int(clt.Backend.ChainID().Int64())
}
// PrivateKey returns the private key being used.
func (clt *Client) PrivateKey() *ecdsa.PrivateKey {
return clt.privateKey
}
// =============================================================================
// NewCallOpts constructs a new CallOpts which is used to call contract methods
// that does not require a transaction.
func (clt *Client) NewCallOpts(ctx context.Context) (*bind.CallOpts, error) {
call := bind.CallOpts{
Pending: true,
From: clt.address,
Context: ctx,
}
return &call, nil
}
// NewTransactOpts constructs a new TransactOpts which is the collection of
// authorization data required to create a valid Ethereum transaction. If the
// gasLimit is set to 0, an estimate will be made for the amount of gas needed.
// If the gasPrice is set to 0, then the connected geth service is consulted
// for the suggested gas price.
func (clt *Client) NewTransactOpts(ctx context.Context, gasLimit uint64, gasPrice *big.Int, valueGWei *big.Float) (*bind.TransactOpts, error) {
nonce, err := clt.PendingNonceAt(ctx, clt.address)
if err != nil {
return nil, fmt.Errorf("retrieving next nonce: %w", err)
}
if gasPrice == nil || gasPrice.Cmp(big.NewInt(0)) == 0 {
gasPrice, err = clt.SuggestGasPrice(ctx)
if err != nil {
return nil, fmt.Errorf("retrieving suggested gas price: %w", err)
}
}
tranOpts, err := bind.NewKeyedTransactorWithChainID(clt.privateKey, clt.Backend.ChainID())
if err != nil {
return nil, fmt.Errorf("keying transaction: %w", err)
}
// This will convert the GWei value to Wei.
gwe2Wei := big.NewInt(0)
big.NewFloat(0).SetPrec(1024).Mul(valueGWei, big.NewFloat(1e9)).Int(gwe2Wei)
tranOpts.Nonce = big.NewInt(0).SetUint64(nonce)
tranOpts.Value = gwe2Wei
tranOpts.GasLimit = gasLimit // The maximum amount of Gas you are willing to pay for.
tranOpts.GasPrice = gasPrice // What you will agree to pay per unit of gas.
return tranOpts, nil
}
// WaitMined will wait for the transaction to be minded and return a receipt.
func (clt *Client) WaitMined(ctx context.Context, tx *types.Transaction) (*types.Receipt, error) {
receipt, err := bind.WaitMined(ctx, clt.Backend, tx)
if err != nil {
return nil, fmt.Errorf("waiting for tx to be mined: %w", err)
}
if receipt.Status == 0 {
if err := clt.extractError(ctx, tx); err != nil {
return nil, fmt.Errorf("extracting tx error: %w", err)
}
}
return receipt, nil
}
// SendTransaction sends a transaction to the specified address for the
// specified amount. The function will wait for the transaction to be mined
// based on the timeout value specified in the context.
func (clt *Client) SendTransaction(ctx context.Context, address common.Address, value *big.Int, gasLimit uint64) error {
nonce, err := clt.PendingNonceAt(ctx, clt.address)
if err != nil {
return fmt.Errorf("retrieving next nonce: %w", err)
}
gasPrice, err := clt.SuggestGasPrice(ctx)
if err != nil {
return fmt.Errorf("retrieving suggested gas price: %w", err)
}
tx := types.NewTx(&types.LegacyTx{
Nonce: nonce,
GasPrice: gasPrice,
Gas: gasLimit,
To: &address,
Value: value,
Data: nil,
})
signedTx, err := types.SignTx(tx, types.LatestSignerForChainID(clt.Backend.ChainID()), clt.privateKey)
if err != nil {
return fmt.Errorf("signing transaction: %w", err)
}
if err := clt.Backend.SendTransaction(ctx, signedTx); err != nil {
return fmt.Errorf("signing transaction: %w", err)
}
if _, err := clt.WaitMined(ctx, signedTx); err != nil {
return fmt.Errorf("timedout waiting: %w", err)
}
return nil
}
// =============================================================================
// Balance retrieves the current balance for the client account.
func (clt *Client) Balance(ctx context.Context) (wei *big.Int, err error) {
return clt.BalanceAt(ctx, clt.address, nil)
}
// BaseFee calculates the base fee from the block for this receipt.
func (clt *Client) BaseFee(receipt *types.Receipt) (wei *big.Int) {
client, isClient := clt.Backend.(*DialedBackend)
if !isClient {
return big.NewInt(0)
}
block, err := client.BlockByNumber(context.Background(), receipt.BlockNumber)
if err != nil {
return big.NewInt(0)
}
return block.BaseFee()
}
// =============================================================================
// extractError checks the failed transaction for the error message.
func (clt *Client) extractError(ctx context.Context, tx *types.Transaction) error {
msg := ethereum.CallMsg{
From: clt.address,
To: tx.To(),
Gas: tx.Gas(),
GasPrice: tx.GasPrice(),
Value: tx.Value(),
Data: tx.Data(),
}
_, err := clt.CallContract(ctx, msg, nil)
return err
}