github.com/diadata-org/diadata@v1.4.593/pkg/dia/helpers/bifrost-helper/client.go (about)

     1  package bifrosthelper
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net/http"
     8  	"strconv"
     9  	"strings"
    10  	"sync"
    11  	"time"
    12  	"unicode/utf8"
    13  
    14  	"github.com/diadata-org/diadata/pkg/dia"
    15  	"github.com/diadata-org/diadata/pkg/utils"
    16  	"github.com/sirupsen/logrus"
    17  )
    18  
    19  const (
    20  	AssetAddressURI = "AssetRegistry:Assets"
    21  	Blockchain      = "Bifrost"
    22  	ExchangeName    = "Bifrost"
    23  	GetAssetsPath   = "assets"
    24  )
    25  
    26  type BifrostClient struct {
    27  	logger            *logrus.Entry
    28  	sleepBetweenCalls time.Duration
    29  	debug             bool
    30  }
    31  
    32  func NewBifrostClient(logger *logrus.Entry, sleepBetweenCalls time.Duration, isDebug bool) *BifrostClient {
    33  	return &BifrostClient{
    34  		logger:            logger,
    35  		sleepBetweenCalls: sleepBetweenCalls,
    36  		debug:             isDebug,
    37  	}
    38  }
    39  func (c *BifrostClient) waiting() {
    40  	time.Sleep(c.sleepBetweenCalls)
    41  }
    42  func (c *BifrostClient) GetAssetAllAssets() ([]BifrostAssetMetadata, error) {
    43  	var wg sync.WaitGroup
    44  	wg.Add(1)
    45  
    46  	apiURL := utils.Getenv(strings.ToUpper(ExchangeName)+"_API_URL", "http://localhost:3000/bifrost/v1")
    47  	getAllAssetsURI := fmt.Sprintf("%s/%s", apiURL, GetAssetsPath)
    48  	c.logger.Infof("Getting assets from: %s", getAllAssetsURI)
    49  	var assets []BifrostAssetMetadata
    50  	var err error
    51  	go func() {
    52  		defer wg.Done()
    53  		response, err := http.Get(getAllAssetsURI)
    54  		if err != nil {
    55  			c.logger.WithError(err).Error("Failed to get assets")
    56  			return
    57  		}
    58  		defer response.Body.Close()
    59  		if response.StatusCode != http.StatusOK {
    60  			c.logger.Errorf("Failed to get assets, status code: %d", response.StatusCode)
    61  			err = fmt.Errorf("failed to get assets, status code: %d", response.StatusCode)
    62  			return
    63  		}
    64  		if json.NewDecoder(response.Body).Decode(&assets) != nil {
    65  			c.logger.Error("Failed to decode assets")
    66  			err = fmt.Errorf("failed to decode assets")
    67  		}
    68  	}()
    69  	wg.Wait()
    70  	if err != nil {
    71  		return nil, err
    72  	}
    73  	return assets, nil
    74  }
    75  func (c *BifrostClient) GetAllPoolAssets() ([]BifrostPoolMetadata, error) {
    76  
    77  	var wg sync.WaitGroup
    78  	wg.Add(1)
    79  
    80  	apiURL := utils.Getenv(strings.ToUpper(ExchangeName)+"_API_URL", "http://localhost:3000/bifrost/v1")
    81  	getAllPoolAssetsURI := fmt.Sprintf("%s/%s", apiURL, "pools")
    82  	c.logger.Infof("Getting pool assets from: %s", getAllPoolAssetsURI)
    83  	var pools []BifrostPoolMetadata
    84  	var err error
    85  	go func() {
    86  		defer wg.Done()
    87  		response, err := http.Get(getAllPoolAssetsURI)
    88  		if err != nil {
    89  			c.logger.WithError(err).Error("Failed to get token pools")
    90  			return
    91  		}
    92  		defer response.Body.Close()
    93  		c.logger.Infof("Response: %d", response.Body)
    94  		if response.StatusCode != http.StatusOK {
    95  			c.logger.Errorf("Failed to get token pools, status code: %d", response.StatusCode)
    96  			err = fmt.Errorf("failed to get token pools, status code: %d", response.StatusCode)
    97  			return
    98  		}
    99  		if json.NewDecoder(response.Body).Decode(&pools) != nil {
   100  			c.logger.Error("Failed to decode token pools")
   101  			err = fmt.Errorf("failed to decode token pools")
   102  		}
   103  	}()
   104  	wg.Wait()
   105  	if err != nil {
   106  		return nil, err
   107  	}
   108  	return pools, nil
   109  }
   110  func (c *BifrostClient) ScrapAssets() ([]*dia.Asset, error) {
   111  	bifrostAssets, err := c.GetAssetAllAssets()
   112  	if err != nil {
   113  		c.logger.WithError(err).Error("Failed to get assets")
   114  		return nil, err
   115  	}
   116  	diaAssets := c.parseAssets(bifrostAssets)
   117  	c.logger.Infof("Scraped (%d) assets.", len(diaAssets))
   118  	return diaAssets, nil
   119  }
   120  func (c *BifrostClient) parseAsset(bifrostAsset BifrostAssetMetadata) *dia.Asset {
   121  	decimals, err := strconv.ParseUint(bifrostAsset.Decimals, 10, 8)
   122  	if err != nil {
   123  		c.logger.WithError(err).Errorf("Failed to parse decimals: %s", bifrostAsset.Decimals)
   124  		return nil
   125  	}
   126  	return &dia.Asset{
   127  		Name:       bifrostAsset.Name,
   128  		Symbol:     bifrostAsset.Symbol,
   129  		Decimals:   uint8(decimals),
   130  		Blockchain: Blockchain,
   131  		Address:    strings.ToLower(bifrostAsset.AssetKey),
   132  	}
   133  }
   134  func (c *BifrostClient) parseAssets(bifrostAssets []BifrostAssetMetadata) []*dia.Asset {
   135  	diaAssets := make([]*dia.Asset, 0, len(bifrostAssets))
   136  	for _, asset := range bifrostAssets {
   137  		diaAssets = append(diaAssets, c.parseAsset(asset))
   138  	}
   139  	return diaAssets
   140  }
   141  func (c *BifrostClient) sanitizeToUTF8(data []byte) string {
   142  	var buf bytes.Buffer
   143  	for len(data) > 0 {
   144  		r, size := utf8.DecodeRune(data)
   145  		if r == utf8.RuneError && size == 1 {
   146  			data = data[size:]
   147  			continue
   148  		}
   149  		if r == 0 {
   150  			data = data[size:]
   151  			continue
   152  		}
   153  		buf.WriteRune(r)
   154  		data = data[size:]
   155  	}
   156  	return buf.String()
   157  }