-
Notifications
You must be signed in to change notification settings - Fork 32
/
client.go
220 lines (193 loc) · 5.55 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
/*
Package w3 is your toolbelt for integrating with Ethereum in Go. Closely linked
to [go-ethereum], it provides an ergonomic wrapper for working with RPC, ABI's,
and the EVM.
[go-ethereum]: https://github.com/ethereum/go-ethereum
*/
package w3
import (
"context"
"fmt"
"reflect"
"strings"
"github.com/ethereum/go-ethereum/rpc"
"github.com/lmittmann/w3/w3types"
"golang.org/x/time/rate"
)
// Client represents a connection to an RPC endpoint.
type Client struct {
client *rpc.Client
// rate limiter
rl *rate.Limiter
rlCostFunc func(methods []string) (cost int)
}
// NewClient returns a new Client given an rpc.Client client.
func NewClient(client *rpc.Client, opts ...Option) *Client {
c := &Client{
client: client,
}
for _, opt := range opts {
if opt == nil {
continue
}
opt(c)
}
return c
}
// Dial returns a new Client connected to the URL rawurl. An error is returned
// if the connection establishment fails.
//
// The supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a
// file name with no URL scheme, a local IPC socket connection is established.
func Dial(rawurl string, opts ...Option) (*Client, error) {
client, err := rpc.Dial(rawurl)
if err != nil {
return nil, err
}
return NewClient(client, opts...), nil
}
// MustDial is like [Dial] but panics if the connection establishment fails.
func MustDial(rawurl string, opts ...Option) *Client {
client, err := Dial(rawurl, opts...)
if err != nil {
panic(fmt.Sprintf("w3: %s", err))
}
return client
}
// Close the RPC connection and cancel all in-flight requests.
//
// Close implements the [io.Closer] interface.
func (c *Client) Close() error {
c.client.Close()
return nil
}
// CallCtx creates the final RPC request, sends it, and handles the RPC
// response.
//
// An error is returned if RPC request creation, networking, or RPC response
// handling fails.
func (c *Client) CallCtx(ctx context.Context, calls ...w3types.RPCCaller) error {
// no requests = nothing to do
if len(calls) <= 0 {
return nil
}
// create requests
batchElems := make([]rpc.BatchElem, len(calls))
var err error
for i, req := range calls {
batchElems[i], err = req.CreateRequest()
if err != nil {
return err
}
}
// invoke rate limiter
if err := c.rateLimit(ctx, batchElems); err != nil {
return err
}
// do requests
if len(batchElems) > 1 {
// batch requests if >1 request
err = c.client.BatchCallContext(ctx, batchElems)
if err != nil {
return err
}
} else {
// non-batch requests if 1 request
batchElem := batchElems[0]
err = c.client.CallContext(ctx, batchElem.Result, batchElem.Method, batchElem.Args...)
if err != nil {
switch reflect.TypeOf(err).String() {
case "*rpc.jsonError":
batchElems[0].Error = err
default:
return err
}
}
}
// handle responses
var callErrs CallErrors
for i, req := range calls {
err = req.HandleResponse(batchElems[i])
if err != nil {
if callErrs == nil {
callErrs = make(CallErrors, len(calls))
}
callErrs[i] = err
}
}
if len(callErrs) > 0 {
return callErrs
}
return nil
}
// Call is like [Client.CallCtx] with ctx equal to context.Background().
func (c *Client) Call(calls ...w3types.RPCCaller) error {
return c.CallCtx(context.Background(), calls...)
}
// SubscribeCtx creates a new subscription and returns a [rpc.ClientSubscription].
func (c *Client) SubscribeCtx(ctx context.Context, s w3types.RPCSubscriber) (*rpc.ClientSubscription, error) {
namespace, ch, params, err := s.CreateRequest()
if err != nil {
return nil, err
}
return c.client.Subscribe(ctx, namespace, ch, params...)
}
// Subscribe is like [Client.SubscribeCtx] with ctx equal to context.Background().
func (c *Client) Subscribe(s w3types.RPCSubscriber) (*rpc.ClientSubscription, error) {
return c.SubscribeCtx(context.Background(), s)
}
func (c *Client) rateLimit(ctx context.Context, batchElems []rpc.BatchElem) error {
if c.rl == nil {
return nil
}
if c.rlCostFunc == nil {
// limit requests
return c.rl.Wait(ctx)
}
// limit requests based on Compute Units (CUs)
methods := make([]string, len(batchElems))
for i, batchElem := range batchElems {
methods[i] = batchElem.Method
}
cost := c.rlCostFunc(methods)
return c.rl.WaitN(ctx, cost)
}
// CallErrors is an error type that contains the errors of multiple calls. The
// length of the error slice is equal to the number of calls. Each error at a
// given index corresponds to the call at the same index. An error is nil if the
// corresponding call was successful.
type CallErrors []error
func (e CallErrors) Error() string {
if len(e) == 1 && e[0] != nil {
return fmt.Sprintf("w3: call failed: %s", e[0])
}
var errors []string
for i, err := range e {
if err == nil {
continue
}
errors = append(errors, fmt.Sprintf("call[%d]: %s", i, err))
}
var plr string
if len(errors) > 1 {
plr = "s"
}
return fmt.Sprintf("w3: %d call%s failed:\n%s", len(errors), plr, strings.Join(errors, "\n"))
}
func (e CallErrors) Is(target error) bool {
_, ok := target.(CallErrors)
return ok
}
// An Option configures a Client.
type Option func(*Client)
// WithRateLimiter sets the rate limiter for the client. Set the optional argument
// costFunc to nil to limit the number of requests. Supply a costFunc to limit
// the the number of requests based on individual RPC calls for advanced rate
// limiting by e.g. Compute Units (CUs). Note that only if len(methods) > 1, the
// calls are sent in a batch request.
func WithRateLimiter(rl *rate.Limiter, costFunc func(methods []string) (cost int)) Option {
return func(c *Client) {
c.rl = rl
c.rlCostFunc = costFunc
}
}