-
-
Notifications
You must be signed in to change notification settings - Fork 108
/
client.go
208 lines (180 loc) · 5.33 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
/*
* Copyright (c) 2018 LI Zhennan
*
* Use of this work is governed by a MIT License.
* You may find a license copy in project root.
*/
package etherscan
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"time"
)
// Client etherscan API client
// Clients are safe for concurrent use by multiple goroutines.
type Client struct {
coon *http.Client
key string
baseURL string
// Verbose when true, talks a lot
Verbose bool
// BeforeRequest runs before every client request, in the same goroutine.
// May be used in rate limit.
// Request will be aborted, if BeforeRequest returns non-nil err.
BeforeRequest func(module, action string, param map[string]interface{}) error
// AfterRequest runs after every client request, even when there is an error.
AfterRequest func(module, action string, param map[string]interface{}, outcome interface{}, requestErr error)
}
// New initialize a new etherscan API client
// please use pre-defined network value
func New(network Network, APIKey string) *Client {
return NewCustomized(Customization{
Timeout: 30 * time.Second,
Key: APIKey,
BaseURL: fmt.Sprintf(`https://%s.etherscan.io/api?`, network.SubDomain()),
})
}
// Customization is used in NewCustomized()
type Customization struct {
// Timeout for API call
Timeout time.Duration
// API key applied from Etherscan
Key string
// Base URL like `https://api.etherscan.io/api?`
BaseURL string
// When true, talks a lot
Verbose bool
// HTTP Client to be used. Specifying this value will ignore the Timeout value set
// Set your own timeout.
Client *http.Client
// BeforeRequest runs before every client request, in the same goroutine.
// May be used in rate limit.
// Request will be aborted, if BeforeRequest returns non-nil err.
BeforeRequest func(module, action string, param map[string]interface{}) error
// AfterRequest runs after every client request, even when there is an error.
AfterRequest func(module, action string, param map[string]interface{}, outcome interface{}, requestErr error)
}
// NewCustomized initialize a customized API client,
// useful when calling against etherscan-family API like BscScan.
func NewCustomized(config Customization) *Client {
var httpClient *http.Client
if config.Client != nil {
httpClient = config.Client
} else {
httpClient = &http.Client{
Timeout: config.Timeout,
}
}
return &Client{
coon: httpClient,
key: config.Key,
baseURL: config.BaseURL,
Verbose: config.Verbose,
BeforeRequest: config.BeforeRequest,
AfterRequest: config.AfterRequest,
}
}
// call does almost all the dirty work.
func (c *Client) call(module, action string, param map[string]interface{}, outcome interface{}) (err error) {
// fire hooks if in need
if c.BeforeRequest != nil {
err = c.BeforeRequest(module, action, param)
if err != nil {
err = wrapErr(err, "beforeRequest")
return
}
}
if c.AfterRequest != nil {
defer c.AfterRequest(module, action, param, outcome, err)
}
// recover if there shall be an panic
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("[ouch! panic recovered] please report this with what you did and what you expected, panic detail: %v", r)
}
}()
req, err := http.NewRequest(http.MethodGet, c.craftURL(module, action, param), http.NoBody)
if err != nil {
err = wrapErr(err, "http.NewRequest")
return
}
req.Header.Set("User-Agent", "etherscan-api(Go)")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
if c.Verbose {
var reqDump []byte
reqDump, err = httputil.DumpRequestOut(req, false)
if err != nil {
err = wrapErr(err, "verbose mode req dump failed")
return
}
fmt.Printf("\n%s\n", reqDump)
defer func() {
if err != nil {
fmt.Printf("[Error] %v\n", err)
}
}()
}
res, err := c.coon.Do(req)
if err != nil {
err = wrapErr(err, "sending request")
return
}
defer res.Body.Close()
if c.Verbose {
var resDump []byte
resDump, err = httputil.DumpResponse(res, true)
if err != nil {
err = wrapErr(err, "verbose mode res dump failed")
return
}
fmt.Printf("%s\n", resDump)
}
var content bytes.Buffer
if _, err = io.Copy(&content, res.Body); err != nil {
err = wrapErr(err, "reading response")
return
}
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("response status %v %s, response body: %s", res.StatusCode, res.Status, content.String())
return
}
var envelope Envelope
err = json.Unmarshal(content.Bytes(), &envelope)
if err != nil {
err = wrapErr(err, "json unmarshal envelope")
return
}
if envelope.Status != 1 {
err = fmt.Errorf("etherscan server: %s", envelope.Message)
return
}
// workaround for missing tokenDecimal for some tokentx calls
if action == "tokentx" {
err = json.Unmarshal(bytes.Replace(envelope.Result, []byte(`"tokenDecimal":""`), []byte(`"tokenDecimal":"0"`), -1), outcome)
} else {
err = json.Unmarshal(envelope.Result, outcome)
}
if err != nil {
err = wrapErr(err, "json unmarshal outcome")
return
}
return
}
// craftURL returns desired URL via param provided
func (c *Client) craftURL(module, action string, param map[string]interface{}) (URL string) {
q := url.Values{
"module": []string{module},
"action": []string{action},
"apikey": []string{c.key},
}
for k, v := range param {
q[k] = extractValue(v)
}
URL = c.baseURL + q.Encode()
return
}