status-go/services/wallet/collectibles/collectibles.go

358 lines
11 KiB
Go
Raw Normal View History

package collectibles
import (
"context"
"fmt"
"math/big"
"strings"
2023-03-30 21:01:28 +00:00
"sync"
"time"
"github.com/afex/hystrix-go/hystrix"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
2023-03-20 13:02:09 +00:00
"github.com/ethereum/go-ethereum/event"
"github.com/status-im/status-go/contracts/collectibles"
"github.com/status-im/status-go/rpc"
"github.com/status-im/status-go/services/wallet/bigint"
"github.com/status-im/status-go/services/wallet/thirdparty"
"github.com/status-im/status-go/services/wallet/thirdparty/opensea"
)
const requestTimeout = 5 * time.Second
const hystrixContractOwnershipClientName = "contractOwnershipClient"
const maxNFTDescriptionLength = 1024
// ERC721 does not support function "TokenURI" if call
// returns error starting with one of these strings
var noTokenURIErrorPrefixes = []string{
"execution reverted",
"abi: attempting to unmarshall",
}
type Manager struct {
rpcClient *rpc.Client
2023-07-05 09:33:48 +00:00
mainContractOwnershipProvider thirdparty.CollectibleContractOwnershipProvider
fallbackContractOwnershipProvider thirdparty.CollectibleContractOwnershipProvider
metadataProvider thirdparty.CollectibleMetadataProvider
opensea *opensea.Client
nftCache map[uint64]map[string]opensea.Asset
nftCacheLock sync.RWMutex
}
2023-07-05 09:33:48 +00:00
func NewManager(rpcClient *rpc.Client, mainContractOwnershipProvider thirdparty.CollectibleContractOwnershipProvider, fallbackContractOwnershipProvider thirdparty.CollectibleContractOwnershipProvider, openseaAPIKey string, walletFeed *event.Feed) *Manager {
hystrix.ConfigureCommand(hystrixContractOwnershipClientName, hystrix.CommandConfig{
Timeout: 10000,
MaxConcurrentRequests: 100,
SleepWindow: 300000,
ErrorPercentThreshold: 25,
})
return &Manager{
rpcClient: rpcClient,
mainContractOwnershipProvider: mainContractOwnershipProvider,
fallbackContractOwnershipProvider: fallbackContractOwnershipProvider,
opensea: opensea.NewClient(openseaAPIKey, walletFeed),
nftCache: make(map[uint64]map[string]opensea.Asset),
}
}
func makeContractOwnershipCall(main func() (any, error), fallback func() (any, error)) (any, error) {
resultChan := make(chan any, 1)
errChan := hystrix.Go(hystrixContractOwnershipClientName, func() error {
res, err := main()
if err != nil {
return err
}
resultChan <- res
return nil
}, func(err error) error {
if fallback == nil {
return err
}
res, err := fallback()
if err != nil {
return err
}
resultChan <- res
return nil
})
select {
case result := <-resultChan:
return result, nil
case err := <-errChan:
return nil, err
}
}
// Used to break circular dependency, call once as soon as possible after initialization
2023-07-05 09:33:48 +00:00
func (o *Manager) SetMetadataProvider(metadataProvider thirdparty.CollectibleMetadataProvider) {
o.metadataProvider = metadataProvider
}
func (o *Manager) FetchAllCollectionsByOwner(chainID uint64, owner common.Address) ([]opensea.OwnedCollection, error) {
return o.opensea.FetchAllCollectionsByOwner(chainID, owner)
}
func (o *Manager) FetchAllAssetsByOwnerAndCollection(chainID uint64, owner common.Address, collectionSlug string, cursor string, limit int) (*opensea.AssetContainer, error) {
assetContainer, err := o.opensea.FetchAllAssetsByOwnerAndCollection(chainID, owner, collectionSlug, cursor, limit)
if err != nil {
return nil, err
}
err = o.processAssets(chainID, assetContainer.Assets)
if err != nil {
return nil, err
}
return assetContainer, nil
}
// Need to combine different providers to support all needed ChainIDs
func (o *Manager) FetchBalancesByOwnerAndContractAddress(chainID uint64, ownerAddress common.Address, contractAddresses []common.Address) (thirdparty.TokenBalancesPerContractAddress, error) {
ret := make(thirdparty.TokenBalancesPerContractAddress)
for _, contractAddress := range contractAddresses {
ret[contractAddress] = make([]thirdparty.TokenBalance, 0)
}
// Try with more direct endpoint first (OpenSea)
assetsContainer, err := o.FetchAllAssetsByOwnerAndContractAddress(chainID, ownerAddress, contractAddresses, "", 0)
if err == opensea.ErrChainIDNotSupported {
// Use contract ownership providers
for _, contractAddress := range contractAddresses {
2023-07-05 09:33:48 +00:00
ownership, err := o.FetchCollectibleOwnersByContractAddress(chainID, contractAddress)
if err != nil {
return nil, err
}
for _, nftOwner := range ownership.Owners {
if nftOwner.OwnerAddress == ownerAddress {
ret[contractAddress] = nftOwner.TokenBalances
break
}
}
}
} else if err == nil {
// OpenSea could provide
for _, asset := range assetsContainer.Assets {
contractAddress := common.HexToAddress(asset.Contract.Address)
balance := thirdparty.TokenBalance{
TokenID: asset.TokenID,
Balance: &bigint.BigInt{Int: big.NewInt(1)},
}
ret[contractAddress] = append(ret[contractAddress], balance)
}
} else {
// OpenSea could have provided, but returned error
return nil, err
}
return ret, nil
}
func (o *Manager) FetchAllAssetsByOwnerAndContractAddress(chainID uint64, owner common.Address, contractAddresses []common.Address, cursor string, limit int) (*opensea.AssetContainer, error) {
assetContainer, err := o.opensea.FetchAllAssetsByOwnerAndContractAddress(chainID, owner, contractAddresses, cursor, limit)
if err != nil {
return nil, err
}
err = o.processAssets(chainID, assetContainer.Assets)
if err != nil {
return nil, err
}
return assetContainer, nil
}
func (o *Manager) FetchAllAssetsByOwner(chainID uint64, owner common.Address, cursor string, limit int) (*opensea.AssetContainer, error) {
assetContainer, err := o.opensea.FetchAllAssetsByOwner(chainID, owner, cursor, limit)
if err != nil {
return nil, err
}
err = o.processAssets(chainID, assetContainer.Assets)
if err != nil {
return nil, err
}
return assetContainer, nil
}
2023-07-05 09:33:48 +00:00
func (o *Manager) FetchAssetsByNFTUniqueID(chainID uint64, uniqueIDs []thirdparty.CollectibleUniqueID, limit int) (*opensea.AssetContainer, error) {
2023-03-30 21:01:28 +00:00
assetContainer := new(opensea.AssetContainer)
2023-03-30 21:01:28 +00:00
idsToFetch := o.getIDsNotInCache(chainID, uniqueIDs)
if len(idsToFetch) > 0 {
fetchedAssetContainer, err := o.opensea.FetchAssetsByNFTUniqueID(chainID, idsToFetch, limit)
2023-03-30 21:01:28 +00:00
if err != nil {
return nil, err
}
err = o.processAssets(chainID, fetchedAssetContainer.Assets)
if err != nil {
return nil, err
}
assetContainer.NextCursor = fetchedAssetContainer.NextCursor
assetContainer.PreviousCursor = fetchedAssetContainer.PreviousCursor
}
2023-03-30 21:01:28 +00:00
assetContainer.Assets = o.getCachedAssets(chainID, uniqueIDs)
return assetContainer, nil
}
2023-07-05 09:33:48 +00:00
func (o *Manager) FetchCollectibleOwnersByContractAddress(chainID uint64, contractAddress common.Address) (*thirdparty.CollectibleContractOwnership, error) {
mainFunc := func() (any, error) {
2023-07-05 09:33:48 +00:00
return o.mainContractOwnershipProvider.FetchCollectibleOwnersByContractAddress(chainID, contractAddress)
}
var fallbackFunc func() (any, error) = nil
if o.fallbackContractOwnershipProvider != nil && o.fallbackContractOwnershipProvider.IsChainSupported(chainID) {
fallbackFunc = func() (any, error) {
2023-07-05 09:33:48 +00:00
return o.fallbackContractOwnershipProvider.FetchCollectibleOwnersByContractAddress(chainID, contractAddress)
}
}
owners, err := makeContractOwnershipCall(mainFunc, fallbackFunc)
if err != nil {
return nil, err
}
2023-07-05 09:33:48 +00:00
return owners.(*thirdparty.CollectibleContractOwnership), nil
}
func isMetadataEmpty(asset opensea.Asset) bool {
return asset.Name == "" &&
asset.Description == "" &&
asset.ImageURL == "" &&
asset.TokenURI == ""
}
2023-07-05 09:33:48 +00:00
func (o *Manager) fetchTokenURI(chainID uint64, id thirdparty.CollectibleUniqueID) (string, error) {
backend, err := o.rpcClient.EthClient(chainID)
if err != nil {
return "", err
}
caller, err := collectibles.NewCollectiblesCaller(id.ContractAddress, backend)
if err != nil {
return "", err
}
timeoutContext, timeoutCancel := context.WithTimeout(context.Background(), requestTimeout)
defer timeoutCancel()
tokenURI, err := caller.TokenURI(&bind.CallOpts{
Context: timeoutContext,
}, id.TokenID.Int)
if err != nil {
for _, errorPrefix := range noTokenURIErrorPrefixes {
if strings.HasPrefix(err.Error(), errorPrefix) {
// Contract doesn't support "TokenURI" method
return "", nil
}
}
return "", err
}
return tokenURI, err
}
func (o *Manager) processAssets(chainID uint64, assets []opensea.Asset) error {
2023-03-30 21:01:28 +00:00
o.nftCacheLock.Lock()
defer o.nftCacheLock.Unlock()
if _, ok := o.nftCache[chainID]; !ok {
o.nftCache[chainID] = make(map[string]opensea.Asset)
}
for idx, asset := range assets {
2023-07-05 09:33:48 +00:00
id := thirdparty.CollectibleUniqueID{
2023-03-30 21:01:28 +00:00
ContractAddress: common.HexToAddress(asset.Contract.Address),
TokenID: asset.TokenID,
}
2023-03-30 21:01:28 +00:00
if isMetadataEmpty(asset) {
if o.metadataProvider == nil {
2023-07-05 09:33:48 +00:00
return fmt.Errorf("CollectibleMetadataProvider not available")
}
tokenURI, err := o.fetchTokenURI(chainID, id)
if err != nil {
return err
}
assets[idx].TokenURI = tokenURI
2023-07-05 09:33:48 +00:00
canProvide, err := o.metadataProvider.CanProvideCollectibleMetadata(chainID, id, tokenURI)
if err != nil {
return err
}
if canProvide {
2023-07-05 09:33:48 +00:00
metadata, err := o.metadataProvider.FetchCollectibleMetadata(chainID, id, tokenURI)
if err != nil {
return err
}
if metadata != nil {
assets[idx].Name = metadata.Name
assets[idx].Description = metadata.Description
assets[idx].Collection.ImageURL = metadata.CollectionImageURL
assets[idx].ImageURL = metadata.ImageURL
}
}
}
2023-03-30 21:01:28 +00:00
// The NFT description field could be arbitrarily large, causing memory management issues upstream.
// Trim it to a reasonable length here.
if len(assets[idx].Description) > maxNFTDescriptionLength {
assets[idx].Description = assets[idx].Description[:maxNFTDescriptionLength]
}
2023-03-30 21:01:28 +00:00
o.nftCache[chainID][id.HashKey()] = assets[idx]
}
return nil
}
2023-03-30 21:01:28 +00:00
2023-07-05 09:33:48 +00:00
func (o *Manager) getIDsNotInCache(chainID uint64, uniqueIDs []thirdparty.CollectibleUniqueID) []thirdparty.CollectibleUniqueID {
2023-03-30 21:01:28 +00:00
o.nftCacheLock.RLock()
defer o.nftCacheLock.RUnlock()
2023-07-05 09:33:48 +00:00
idsToFetch := make([]thirdparty.CollectibleUniqueID, 0, len(uniqueIDs))
2023-03-30 21:01:28 +00:00
if _, ok := o.nftCache[chainID]; !ok {
idsToFetch = uniqueIDs
} else {
for _, id := range uniqueIDs {
if _, ok := o.nftCache[chainID][id.HashKey()]; !ok {
idsToFetch = append(idsToFetch, id)
}
}
}
return idsToFetch
}
2023-07-05 09:33:48 +00:00
func (o *Manager) getCachedAssets(chainID uint64, uniqueIDs []thirdparty.CollectibleUniqueID) []opensea.Asset {
2023-03-30 21:01:28 +00:00
o.nftCacheLock.RLock()
defer o.nftCacheLock.RUnlock()
assets := make([]opensea.Asset, 0, len(uniqueIDs))
if _, ok := o.nftCache[chainID]; ok {
for _, id := range uniqueIDs {
if asset, ok := o.nftCache[chainID][id.HashKey()]; ok {
assets = append(assets, asset)
}
}
}
return assets
}