status-go/services/wallet/thirdparty/infura/client.go

108 lines
2.3 KiB
Go
Raw Normal View History

package infura
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
2023-04-18 14:33:59 +00:00
walletCommon "github.com/status-im/status-go/services/wallet/common"
"github.com/status-im/status-go/services/wallet/thirdparty"
)
const baseURL = "https://nft.api.infura.io"
const InfuraID = "infura"
type Client struct {
2023-07-05 09:33:48 +00:00
thirdparty.CollectibleContractOwnershipProvider
client *http.Client
apiKey string
apiKeySecret string
IsConnected bool
IsConnectedLock sync.RWMutex
}
func NewClient(apiKey string, apiKeySecret string) *Client {
return &Client{
client: &http.Client{Timeout: time.Minute},
apiKey: apiKey,
}
}
func (o *Client) doQuery(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(o.apiKey, o.apiKeySecret)
resp, err := o.client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
func (o *Client) ID() string {
return InfuraID
}
func (o *Client) IsChainSupported(chainID walletCommon.ChainID) bool {
switch uint64(chainID) {
case walletCommon.EthereumMainnet, walletCommon.ArbitrumMainnet:
case walletCommon.EthereumGoerli, walletCommon.EthereumSepolia:
return true
}
return false
}
func (o *Client) FetchCollectibleOwnersByContractAddress(chainID walletCommon.ChainID, contractAddress common.Address) (*thirdparty.CollectibleContractOwnership, error) {
cursor := ""
2023-07-05 09:33:48 +00:00
ownersMap := make(map[common.Address][]CollectibleOwner)
for {
url := fmt.Sprintf("%s/networks/%d/nfts/%s/owners", baseURL, chainID, contractAddress.String())
if cursor != "" {
url = url + "?cursor=" + cursor
}
resp, err := o.doQuery(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
2023-07-05 09:33:48 +00:00
var infuraOwnership CollectibleContractOwnership
err = json.Unmarshal(body, &infuraOwnership)
if err != nil {
return nil, err
}
for _, infuraOwner := range infuraOwnership.Owners {
ownersMap[infuraOwner.OwnerAddress] = append(ownersMap[infuraOwner.OwnerAddress], infuraOwner)
}
cursor = infuraOwnership.Cursor
if cursor == "" {
break
}
}
return infuraOwnershipToCommon(contractAddress, ownersMap)
}