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

     1  package tokenrate
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  )
     7  
     8  var ErrNoAvailableQuoteQuery = errors.New("token: no available quote query service")
     9  var quotes []quoteQuery
    10  
    11  func init() {
    12  
    13  	//priority: uniswap > bancor > coingecko > coinmarketcap
    14  	quotes = []quoteQuery{
    15  		&coingeckoQuoteQuery{},
    16  		&bancorQuoteQuery{},
    17  		&uniswapQuoteQuery{},
    18  		createCoinmarketcapQuoteQuery(),
    19  		//more query services
    20  	}
    21  
    22  }
    23  
    24  func GetUSD(ctx context.Context, symbol string) (float64, error) {
    25  	var err error
    26  
    27  	ctx, cancel := context.WithCancel(ctx)
    28  	defer func() {
    29  		cancel()
    30  	}()
    31  
    32  	for _, q := range quotes {
    33  		val, err := q.getUSD(ctx, symbol)
    34  
    35  		if err != nil {
    36  			continue
    37  		}
    38  
    39  		if val > 0 {
    40  			return val, nil
    41  		}
    42  	}
    43  
    44  	// All conversion APIs failed
    45  	if err != nil {
    46  		return 0, err
    47  	}
    48  
    49  	return 0, ErrNoAvailableQuoteQuery
    50  }
    51  
    52  type quoteQuery interface {
    53  	getUSD(ctx context.Context, symbol string) (float64, error)
    54  }