forked from gagliardetto/solana-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client-with-ratelimit2.go
66 lines (56 loc) · 1.44 KB
/
client-with-ratelimit2.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
package rpc
import (
"context"
"io"
"net/http"
"github.com/gagliardetto/solana-go/rpc/jsonrpc"
"golang.org/x/time/rate"
)
var _ JSONRPCClient = &clientWithLimiter{}
type clientWithLimiter struct {
rpcClient jsonrpc.RPCClient
limiter *rate.Limiter
}
// NewWithLimiter creates a new rate-limitted Solana RPC client.
// Example: NewWithLimiter(URL, rate.Every(time.Second), 1)
func NewWithLimiter(
rpcEndpoint string,
every rate.Limit, // time frame
b int, // number of requests per time frame
) JSONRPCClient {
opts := &jsonrpc.RPCClientOpts{
HTTPClient: newHTTP(),
}
rpcClient := jsonrpc.NewClientWithOpts(rpcEndpoint, opts)
rater := rate.NewLimiter(every, b)
return &clientWithLimiter{
rpcClient: rpcClient,
limiter: rater,
}
}
func (wr *clientWithLimiter) CallForInto(ctx context.Context, out interface{}, method string, params []interface{}) error {
err := wr.limiter.Wait(ctx)
if err != nil {
return err
}
return wr.rpcClient.CallForInto(ctx, &out, method, params)
}
func (wr *clientWithLimiter) CallWithCallback(
ctx context.Context,
method string,
params []interface{},
callback func(*http.Request, *http.Response) error,
) error {
err := wr.limiter.Wait(ctx)
if err != nil {
return err
}
return wr.rpcClient.CallWithCallback(ctx, method, params, callback)
}
// Close closes clientWithLimiter.
func (cl *clientWithLimiter) Close() error {
if c, ok := cl.rpcClient.(io.Closer); ok {
return c.Close()
}
return nil
}