/
client.go
280 lines (235 loc) · 10.1 KB
/
client.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package eth
import (
"context"
"math/big"
"strings"
"time"
"github.com/smartcontractkit/chainlink/core/assets"
"github.com/smartcontractkit/chainlink/core/logger"
"github.com/smartcontractkit/chainlink/core/utils"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/rpc"
"github.com/pkg/errors"
)
//go:generate mockery --name Client --output mocks/ --case=underscore
//go:generate mockery --name Subscription --output ../../internal/mocks/ --case=underscore
// Client is the interface used to interact with an ethereum node.
type Client interface {
Dial(ctx context.Context) error
Close()
ChainID() *big.Int
GetERC20Balance(address common.Address, contractAddress common.Address) (*big.Int, error)
GetLINKBalance(linkAddress common.Address, address common.Address) (*assets.Link, error)
GetEthBalance(ctx context.Context, account common.Address, blockNumber *big.Int) (*assets.Eth, error)
// Wrapped RPC methods
Call(result interface{}, method string, args ...interface{}) error
CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error
BatchCallContext(ctx context.Context, b []rpc.BatchElem) error
// HeadByNumber is a reimplemented version of HeaderByNumber due to a
// difference in how block header hashes are calculated by Parity nodes
// running on Kovan. We have to return our own wrapper type to capture the
// correct hash from the RPC response.
HeadByNumber(ctx context.Context, n *big.Int) (*Head, error)
SubscribeNewHead(ctx context.Context, ch chan<- *Head) (ethereum.Subscription, error)
// Wrapped Geth client methods
SendTransaction(ctx context.Context, tx *types.Transaction) error
PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error)
TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error)
BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error)
FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error)
SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error)
EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error)
SuggestGasPrice(ctx context.Context) (*big.Int, error)
CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error)
CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error)
// bind.ContractBackend methods
HeaderByNumber(context.Context, *big.Int) (*types.Header, error)
SuggestGasTipCap(ctx context.Context) (*big.Int, error)
}
// This interface only exists so that we can generate a mock for it. It is
// identical to `ethereum.Subscription`.
type Subscription interface {
Err() <-chan error
Unsubscribe()
}
// DefaultQueryCtx returns a context with a sensible sanity limit timeout for
// queries to the eth node
func DefaultQueryCtx(ctxs ...context.Context) (ctx context.Context, cancel context.CancelFunc) {
if len(ctxs) > 0 {
ctx = ctxs[0]
} else {
ctx = context.Background()
}
return context.WithTimeout(ctx, 15*time.Second)
}
// client represents an abstract client that manages connections to
// multiple nodes for a single chain id
type client struct {
logger logger.Logger
pool *Pool
}
var _ Client = (*client)(nil)
// NewClientWithNodes instantiates a client from a list of nodes
// Currently only supports one primary
func NewClientWithNodes(logger logger.Logger, primaryNodes []Node, sendOnlyNodes []SendOnlyNode, chainID *big.Int) (*client, error) {
pool := NewPool(logger, primaryNodes, sendOnlyNodes, chainID)
return &client{
logger: logger,
pool: pool,
}, nil
}
// Dial opens websocket connections if necessary and sanity-checks that the
// node's remote chain ID matches the local one
func (client *client) Dial(ctx context.Context) error {
if err := client.pool.Dial(ctx); err != nil {
return errors.Wrap(err, "failed to dial pool")
}
return nil
}
func (client *client) Close() {
client.pool.Close()
}
// CallArgs represents the data used to call the balance method of a contract.
// "To" is the address of the ERC contract. "Data" is the message sent
// to the contract.
type CallArgs struct {
To common.Address `json:"to"`
Data hexutil.Bytes `json:"data"`
}
// GetERC20Balance returns the balance of the given address for the token contract address.
func (client *client) GetERC20Balance(address common.Address, contractAddress common.Address) (*big.Int, error) {
result := ""
numLinkBigInt := new(big.Int)
functionSelector := HexToFunctionSelector("0x70a08231") // balanceOf(address)
data := utils.ConcatBytes(functionSelector.Bytes(), common.LeftPadBytes(address.Bytes(), utils.EVMWordByteLen))
args := CallArgs{
To: contractAddress,
Data: data,
}
err := client.Call(&result, "eth_call", args, "latest")
if err != nil {
return numLinkBigInt, err
}
numLinkBigInt.SetString(result, 0)
return numLinkBigInt, nil
}
// GetLINKBalance returns the balance of LINK at the given address
func (client *client) GetLINKBalance(linkAddress common.Address, address common.Address) (*assets.Link, error) {
balance, err := client.GetERC20Balance(address, linkAddress)
if err != nil {
return assets.NewLinkFromJuels(0), err
}
return (*assets.Link)(balance), nil
}
func (client *client) GetEthBalance(ctx context.Context, account common.Address, blockNumber *big.Int) (*assets.Eth, error) {
balance, err := client.BalanceAt(ctx, account, blockNumber)
if err != nil {
return assets.NewEth(0), err
}
return (*assets.Eth)(balance), nil
}
// We wrap the GethClient's `TransactionReceipt` method so that we can ignore the error that arises
// when we're talking to a Parity node that has no receipt yet.
func (client *client) TransactionReceipt(ctx context.Context, txHash common.Hash) (receipt *types.Receipt, err error) {
receipt, err = client.pool.TransactionReceipt(ctx, txHash)
if err != nil && strings.Contains(err.Error(), "missing required field") {
return nil, ethereum.NotFound
}
return
}
func (client *client) ChainID() *big.Int {
return client.pool.chainID
}
func (client *client) HeaderByNumber(ctx context.Context, n *big.Int) (*types.Header, error) {
return client.pool.HeaderByNumber(ctx, n)
}
// SendTransaction also uses the sendonly HTTP RPC URLs if set
func (client *client) SendTransaction(ctx context.Context, tx *types.Transaction) error {
return client.pool.SendTransaction(ctx, tx)
}
func (client *client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
return client.pool.PendingNonceAt(ctx, account)
}
func (client *client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) {
return client.pool.NonceAt(ctx, account, blockNumber)
}
func (client *client) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) {
return client.pool.PendingCodeAt(ctx, account)
}
func (client *client) EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error) {
return client.pool.EstimateGas(ctx, call)
}
func (client *client) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
return client.pool.SuggestGasPrice(ctx)
}
func (client *client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
return client.pool.CallContract(ctx, msg, blockNumber)
}
func (client *client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) {
return client.pool.CodeAt(ctx, account, blockNumber)
}
func (client *client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
return client.pool.BlockByNumber(ctx, number)
}
func (client *client) HeadByNumber(ctx context.Context, number *big.Int) (head *Head, err error) {
hex := ToBlockNumArg(number)
err = client.pool.CallContext(ctx, &head, "eth_getBlockByNumber", hex, false)
if err != nil {
return nil, err
}
if head == nil {
err = ethereum.NotFound
return
}
head.EVMChainID = utils.NewBig(client.ChainID())
return
}
func ToBlockNumArg(number *big.Int) string {
if number == nil {
return "latest"
}
return hexutil.EncodeBig(number)
}
func (client *client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) {
return client.pool.BalanceAt(ctx, account, blockNumber)
}
func (client *client) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) {
return client.pool.FilterLogs(ctx, q)
}
func (client *client) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
client.logger.Debugw("eth.Client#SubscribeFilterLogs(...)",
"q", q,
)
return client.pool.SubscribeFilterLogs(ctx, q, ch)
}
func (client *client) SubscribeNewHead(ctx context.Context, ch chan<- *Head) (ethereum.Subscription, error) {
csf := newChainIDSubForwarder(client.ChainID(), ch)
err := csf.start(client.pool.EthSubscribe(ctx, csf.srcCh, "newHeads"))
if err != nil {
return nil, err
}
return csf, nil
}
func (client *client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (ethereum.Subscription, error) {
return client.pool.EthSubscribe(ctx, channel, args...)
}
func (client *client) Call(result interface{}, method string, args ...interface{}) error {
ctx, cancel := DefaultQueryCtx()
defer cancel()
return client.pool.CallContext(ctx, result, method, args...)
}
func (client *client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error {
return client.pool.CallContext(ctx, result, method, args...)
}
func (client *client) BatchCallContext(ctx context.Context, b []rpc.BatchElem) error {
return client.pool.BatchCallContext(ctx, b)
}
func (client *client) SuggestGasTipCap(ctx context.Context) (tipCap *big.Int, err error) {
return client.pool.SuggestGasTipCap(ctx)
}