-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
265 lines (224 loc) · 6.71 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
package coinbasev3
import (
"encoding/json"
"errors"
"fmt"
"github.com/imroc/req/v3"
"net/url"
"strings"
"time"
)
var (
ErrFailedToUnmarshal = fmt.Errorf("failed to unmarshal response")
)
type HttpClient interface {
Get(url string) (*req.Response, error)
Post(url string, data []byte) (*req.Response, error)
GetClient() *req.Client
}
type ApiClient struct {
apiKey string
secretKey string
client *req.Client
httpClient HttpClient
baseUrlV3 string
baseUrlV2 string
baseExchangeUrl string
}
// NewApiClient creates a new Coinbase API client. The API key and secret key are used to sign requests. The default timeout is 10 seconds. The default retry count is 3. The default retry backoff interval is 1 second to 5 seconds.
func NewApiClient(apiKey, secretKey string, clients ...HttpClient) *ApiClient {
if clients != nil && len(clients) > 0 {
ac := &ApiClient{
apiKey: apiKey,
secretKey: secretKey,
client: newClient(apiKey, secretKey),
httpClient: clients[0],
}
ac.setBaseUrls()
return ac
}
client := newClient(apiKey, secretKey)
ac := &ApiClient{
apiKey: apiKey,
secretKey: secretKey,
client: client,
httpClient: &ReqClient{client: client},
}
ac.setBaseUrls()
return ac
}
func newClient(apiKey, secretKey string) *req.Client {
client := req.C().
SetTimeout(time.Second * 10).
SetUserAgent("GoCoinbaseV3/1.0.0")
// TODO: figure out how to do this where we can use PathParam, QueryParam, etc.
client.OnBeforeRequest(func(client *req.Client, req *req.Request) error {
// create a secret key from: `timestamp + method + requestPath + body`
path := ""
if req.RawURL != "" {
u, err := url.Parse(req.RawURL)
if err != nil {
return err
}
path = u.Path
} else {
return fmt.Errorf("no path found")
}
sig := fmt.Sprintf("%d%s%s%s", time.Now().Unix(), req.Method, path, req.Body)
signedSig := string(SignHmacSha256(sig, secretKey))
client.Headers.Set("CB-ACCESS-KEY", apiKey)
client.Headers.Set("CB-ACCESS-SIGN", signedSig)
client.Headers.Set("CB-ACCESS-TIMESTAMP", fmt.Sprintf("%d", time.Now().Unix()))
return nil
})
return client
}
func (c *ApiClient) get(url string, out interface{}) ([]byte, error) {
resp, err := c.httpClient.Get(url)
if err != nil {
return resp.Bytes(), err
}
if !resp.IsSuccessState() {
return resp.Bytes(), ErrFailedToUnmarshal
}
err = resp.Unmarshal(&out)
if err != nil {
return resp.Bytes(), err
}
return resp.Bytes(), nil
}
func (c *ApiClient) post(url string, data []byte, out interface{}) ([]byte, error) {
resp, err := c.httpClient.Post(url, data)
if err != nil {
return resp.Bytes(), err
}
if !resp.IsSuccessState() {
return resp.Bytes(), ErrFailedToUnmarshal
}
err = resp.Unmarshal(&out)
if err != nil {
return resp.Bytes(), err
}
return resp.Bytes(), nil
}
func (c *ApiClient) setBaseUrls() {
c.baseUrlV3 = "https://api.coinbase.com/api/v3"
c.baseUrlV2 = "https://api.coinbase.com/api/v2"
c.baseExchangeUrl = "https://api.exchange.coinbase.com"
}
// SetSandboxUrls sets the base URLs to the sandbox environment. Note: The sandbox for Advanced Trading is not yet available. This method will be revisited when the sandbox is available.
func (c *ApiClient) SetSandboxUrls() {
c.baseUrlV3 = "https://api-public.sandbox.pro.coinbase.com"
c.baseUrlV2 = "https://api-public.sandbox.pro.coinbase.com"
c.baseExchangeUrl = "https://api-public.sandbox.exchange.coinbase.com"
}
// SetBaseUrlV3 sets the base URL for the Coinbase Advanced Trading API.
func (c *ApiClient) SetBaseUrlV3(url string) {
c.baseUrlV3 = url
}
func (c *ApiClient) makeV3Url(path string) string {
if strings.HasPrefix(path, "/") {
path = strings.TrimPrefix(path, "/")
}
return fmt.Sprintf("%s/%s", c.baseUrlV3, path)
}
// SetBaseUrlV2 sets the base URL for the Sign In With Coinbase APIs.
func (c *ApiClient) SetBaseUrlV2(url string) {
c.baseUrlV2 = url
}
func (c *ApiClient) makeV2Url(path string) string {
if strings.HasPrefix(path, "/") {
path = strings.TrimPrefix(path, "/")
}
return fmt.Sprintf("%s/%s", c.baseUrlV2, path)
}
// SetBaseExchangeUrl sets the base URL for the Coinbase Exchange API.
func (c *ApiClient) SetBaseExchangeUrl(url string) {
c.baseExchangeUrl = url
}
func (c *ApiClient) makeExchangeUrl(path string) string {
if strings.HasPrefix(path, "/") {
path = strings.TrimPrefix(path, "/")
}
return fmt.Sprintf("%s/%s", c.baseExchangeUrl, path)
}
// ReqClient is a wrapper around the req.Client to satisfy the HttpClient interface.
type ReqClient struct {
client *req.Client
}
// GetClient returns the underlying req.Client.
func (c *ReqClient) GetClient() *req.Client {
return c.client
}
// Get makes a GET request to the given URL.
func (c *ReqClient) Get(url string) (*req.Response, error) {
resp, err := c.client.R().Get(url)
if err != nil {
return nil, err
}
return resp, nil
}
// Post makes a POST request to the given URL.
func (c *ReqClient) Post(url string, data []byte) (*req.Response, error) {
resp, err := c.client.R().SetBody(data).Post(url)
if err != nil {
return nil, err
}
return resp, nil
}
type ResponseError struct {
Message string `json:"message"`
CoinbaseError CoinbaseError `json:"coinbase_error"`
}
// Implement the Error() method for MyCustomError.
// This method makes MyCustomError satisfy the error interface.
func (e ResponseError) Error() string {
return e.Message
}
func newResponseError(res []byte) error {
resErr := newCoinbaseError(res)
return ResponseError{
Message: resErr.Message,
CoinbaseError: resErr.CoinbaseError,
}
}
type CoinbaseError struct {
Error string `json:"error"`
Code string `json:"code"`
Message string `json:"message"`
ErrorDetails string `json:"error_details"`
Details ErrorDetails `json:"details"`
}
func newCoinbaseError(res []byte) ResponseError {
var errRes CoinbaseError
err := json.Unmarshal(res, &errRes)
if err != nil {
return ResponseError{
Message: err.Error(),
CoinbaseError: errRes,
}
}
return ResponseError{
Message: errRes.Message,
CoinbaseError: errRes,
}
}
type ErrorDetail struct {
TypeUrl string `json:"type_url"`
Value string `json:"value"`
}
type ErrorDetails []ErrorDetail
// UnmarshalJSON implements the json.Unmarshaler interface. Required because Coinbase returns an array of error details or a single error detail object.
func (ed *ErrorDetails) UnmarshalJSON(data []byte) error {
var details []ErrorDetail
if err := json.Unmarshal(data, &details); err == nil {
*ed = details
return nil
}
var detail ErrorDetail
if err := json.Unmarshal(data, &detail); err == nil {
*ed = ErrorDetails{detail}
return nil
}
return errors.New("error details should be an array or a single object")
}