-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathopensea.go
119 lines (103 loc) · 2.57 KB
/
opensea.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
package opensea
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math/big"
"net"
"net/http"
"time"
)
var (
mainnetAPI = "https://api.opensea.io"
rinkebyAPI = "https://rinkeby-api.opensea.io"
)
type Opensea struct {
API string
APIKey string
}
type errorResponse struct {
Success bool `json:"success"`
}
func (e errorResponse) Error() string {
return "Not success"
}
func NewOpensea(apiKey string) (*Opensea, error) {
o := &Opensea{
API: mainnetAPI,
APIKey: apiKey,
}
return o, nil
}
func NewOpenseaRinkeby(apiKey string) (*Opensea, error) {
o := &Opensea{
API: rinkebyAPI,
APIKey: apiKey,
}
return o, nil
}
func (o Opensea) GetSingleAsset(assetContractAddress string, tokenID *big.Int) (*Asset, error) {
ctx := context.TODO()
return o.GetSingleAssetWithContext(ctx, assetContractAddress, tokenID)
}
func (o Opensea) GetSingleAssetWithContext(ctx context.Context, assetContractAddress string, tokenID *big.Int) (*Asset, error) {
path := fmt.Sprintf("/api/v1/asset/%s/%s", assetContractAddress, tokenID.String())
b, err := o.getPath(ctx, path)
if err != nil {
return nil, err
}
ret := new(Asset)
return ret, json.Unmarshal(b, ret)
}
func (o Opensea) getPath(ctx context.Context, path string) ([]byte, error) {
return o.getURL(ctx, o.API+path)
}
func (o Opensea) getURL(ctx context.Context, url string) ([]byte, error) {
client := httpClient()
// fmt.Println(url)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
req.Header.Add("X-API-KEY", o.APIKey)
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
e := new(errorResponse)
err = json.Unmarshal(body, e)
if err != nil {
return nil, err
}
if !e.Success {
return nil, e
}
return nil, fmt.Errorf("Backend returns status %d msg: %s", resp.StatusCode, string(body))
}
return body, nil
}
func httpClient() *http.Client {
client := new(http.Client)
var transport http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DisableKeepAlives: false,
DisableCompression: false,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 300 * time.Second,
DualStack: true,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
client.Transport = transport
return client
}