github.com/0chain/gosdk@v1.17.11/core/tokenrate/coingecko.go (about)

     1  package tokenrate
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"errors"
     7  	"fmt"
     8  	"net/http"
     9  	"strconv"
    10  
    11  	"github.com/0chain/gosdk/core/resty"
    12  )
    13  
    14  type coingeckoQuoteQuery struct {
    15  }
    16  
    17  func (qq *coingeckoQuoteQuery) getUSD(ctx context.Context, symbol string) (float64, error) {
    18  
    19  	var result coingeckoResponse
    20  
    21  	r := resty.New()
    22  	r.DoGet(ctx, "https://zcnprices.zus.network/market").
    23  		Then(func(req *http.Request, resp *http.Response, respBody []byte, cf context.CancelFunc, err error) error {
    24  
    25  			if err != nil {
    26  				return err
    27  			}
    28  
    29  			if resp.StatusCode != http.StatusOK {
    30  				return errors.New("market API: " + strconv.Itoa(resp.StatusCode) + resp.Status)
    31  			}
    32  
    33  			err = json.Unmarshal(respBody, &result)
    34  			if err != nil {
    35  				return err
    36  			}
    37  			result.Raw = string(respBody)
    38  
    39  			return nil
    40  
    41  		})
    42  
    43  	errs := r.Wait()
    44  	if len(errs) > 0 {
    45  		return 0, errs[0]
    46  	}
    47  
    48  	var rate float64
    49  
    50  	h, ok := result.MarketData.High24h["usd"]
    51  	if ok {
    52  		l, ok := result.MarketData.Low24h["usd"]
    53  		if ok {
    54  			rate = (h + l) / 2
    55  			if rate > 0 {
    56  				return rate, nil
    57  			}
    58  		}
    59  	}
    60  
    61  	rate, ok = result.MarketData.CurrentPrice["usd"]
    62  
    63  	if ok {
    64  		if rate > 0 {
    65  			return rate, nil
    66  		}
    67  
    68  		return 0, fmt.Errorf("market API: invalid response %s", result.Raw)
    69  	}
    70  
    71  	return 0, fmt.Errorf("market API: %s price is not provided on internal https://zcnprices.zus.network/market api", symbol)
    72  }
    73  
    74  type coingeckoResponse struct {
    75  	MarketData coingeckoMarketData `json:"market_data"`
    76  	Raw        string              `json:"-"`
    77  }
    78  
    79  type coingeckoMarketData struct {
    80  	CurrentPrice map[string]float64 `json:"current_price"`
    81  	High24h      map[string]float64 `json:"high_24h"`
    82  	Low24h       map[string]float64 `json:"low_24h"`
    83  }