-
Notifications
You must be signed in to change notification settings - Fork 248
/
opensea.go
235 lines (199 loc) · 5.96 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
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
package wallet
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/log"
)
const AssetLimit = 50
const CollectionLimit = 300
var OpenseaClientInstances = make(map[uint64]*OpenseaClient)
var BaseURLs = map[uint64]string{
1: "https://api.opensea.io/api/v1",
4: "https://rinkeby-api.opensea.io/api/v1",
5: "https://testnets-api.opensea.io/api/v1",
}
type TraitValue string
func (st *TraitValue) UnmarshalJSON(b []byte) error {
var item interface{}
if err := json.Unmarshal(b, &item); err != nil {
return err
}
switch v := item.(type) {
case float64:
*st = TraitValue(strconv.FormatFloat(v, 'f', 2, 64))
case int:
*st = TraitValue(strconv.Itoa(v))
case string:
*st = TraitValue(v)
}
return nil
}
type OpenseaAssetContainer struct {
Assets []OpenseaAsset `json:"assets"`
}
type OpenseaAssetCollection struct {
Name string `json:"name"`
}
type OpenseaContract struct {
Address string `json:"address"`
}
type OpenseaTrait struct {
TraitType string `json:"trait_type"`
Value TraitValue `json:"value"`
DisplayType string `json:"display_type"`
MaxValue string `json:"max_value"`
}
type OpenseaPaymentToken struct {
ID int `json:"id"`
Symbol string `json:"symbol"`
Address string `json:"address"`
ImageURL string `json:"image_url"`
Name string `json:"name"`
Decimals int `json:"decimals"`
EthPrice string `json:"eth_price"`
UsdPrice string `json:"usd_price"`
}
type OpenseaLastSale struct {
PaymentToken OpenseaPaymentToken `json:"payment_token"`
}
type OpenseaSellOrder struct {
CurrentPrice string `json:"current_price"`
}
type OpenseaAsset struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Permalink string `json:"permalink"`
ImageThumbnailURL string `json:"image_thumbnail_url"`
ImageURL string `json:"image_url"`
Contract OpenseaContract `json:"asset_contract"`
Collection OpenseaAssetCollection `json:"collection"`
Traits []OpenseaTrait `json:"traits"`
LastSale OpenseaLastSale `json:"last_sale"`
SellOrders []OpenseaSellOrder `json:"sell_orders"`
BackgroundColor string `json:"background_color"`
}
type OpenseaCollectionTrait struct {
Min float64 `json:"min"`
Max float64 `json:"max"`
}
type OpenseaCollection struct {
Name string `json:"name"`
Slug string `json:"slug"`
ImageURL string `json:"image_url"`
OwnedAssetCount int `json:"owned_asset_count"`
Traits map[string]OpenseaCollectionTrait `json:"traits"`
}
type OpenseaClient struct {
client *http.Client
url string
apiKey string
IsConnected bool
IsConnectedLock sync.RWMutex
}
// new opensea client.
func newOpenseaClient(chainID uint64, apiKey string) (*OpenseaClient, error) {
if client, ok := OpenseaClientInstances[chainID]; ok {
if client.apiKey == apiKey {
return client, nil
}
}
client := &http.Client{
Timeout: time.Second * 5,
}
if url, ok := BaseURLs[chainID]; ok {
openseaClient := &OpenseaClient{client: client, url: url, apiKey: apiKey, IsConnected: true}
OpenseaClientInstances[chainID] = openseaClient
return openseaClient, nil
}
return nil, errors.New("ChainID not supported")
}
func (o *OpenseaClient) fetchAllCollectionsByOwner(owner common.Address) ([]OpenseaCollection, error) {
offset := 0
var collections []OpenseaCollection
o.IsConnectedLock.Lock()
defer o.IsConnectedLock.Unlock()
for {
url := fmt.Sprintf("%s/collections?asset_owner=%s&offset=%d&limit=%d", o.url, owner, offset, CollectionLimit)
body, err := o.doOpenseaRequest(url)
if err != nil {
o.IsConnected = false
return nil, err
}
var tmp []OpenseaCollection
err = json.Unmarshal(body, &tmp)
if err != nil {
o.IsConnected = false
return nil, err
}
collections = append(collections, tmp...)
if len(tmp) < CollectionLimit {
break
}
}
o.IsConnected = true
return collections, nil
}
func (o *OpenseaClient) fetchAllAssetsByOwnerAndCollection(owner common.Address, collectionSlug string, limit int) ([]OpenseaAsset, error) {
offset := 0
var assets []OpenseaAsset
o.IsConnectedLock.Lock()
defer o.IsConnectedLock.Unlock()
for {
url := fmt.Sprintf("%s/assets?owner=%s&collection=%s&offset=%d&limit=%d", o.url, owner, collectionSlug, offset, AssetLimit)
body, err := o.doOpenseaRequest(url)
if err != nil {
o.IsConnected = false
return nil, err
}
container := OpenseaAssetContainer{}
err = json.Unmarshal(body, &container)
if err != nil {
o.IsConnected = false
return nil, err
}
for _, asset := range container.Assets {
for i := range asset.Traits {
asset.Traits[i].TraitType = strings.Replace(asset.Traits[i].TraitType, "_", " ", 1)
asset.Traits[i].Value = TraitValue(strings.Title(string(asset.Traits[i].Value)))
}
assets = append(assets, asset)
}
if len(container.Assets) < AssetLimit {
break
}
if len(assets) >= limit {
break
}
}
o.IsConnected = true
return assets, nil
}
func (o *OpenseaClient) doOpenseaRequest(url string) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:96.0) Gecko/20100101 Firefox/96.0")
req.Header.Set("X-API-KEY", o.apiKey)
resp, err := o.client.Do(req)
if err != nil {
return nil, err
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Error("failed to close opensea request body", "err", err)
}
}()
body, err := ioutil.ReadAll(resp.Body)
return body, err
}