github.com/0chain/gosdk@v1.17.11/core/tokenrate/uniswap.go (about) 1 package tokenrate 2 3 import ( 4 "context" 5 "errors" 6 "strconv" 7 "strings" 8 9 "github.com/0chain/gosdk/core/resty" 10 "github.com/machinebox/graphql" 11 ) 12 13 type V2Pair struct { 14 ID string 15 VolumeToken0 string 16 VolumeToken1 string 17 Token0Price string 18 Token1Price string 19 Token0 V2Token 20 Token1 V2Token 21 } 22 23 type V2Token struct { 24 ID string 25 Symbol string 26 } 27 28 type Query struct { 29 ZCN V2Pair 30 USDC V2Pair 31 } 32 33 type uniswapQuoteQuery struct { 34 } 35 36 func (qq *uniswapQuoteQuery) getUSD(ctx context.Context, symbol string) (float64, error) { 37 38 hql := graphql.NewClient("https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2") 39 40 // make a request 41 req := graphql.NewRequest(` 42 { 43 zcn: pair(id:"0xa6890ac41e3a99a427bef68398bf06119fb5e211"){ 44 token0 { 45 id 46 symbol 47 totalSupply 48 } 49 token1 { 50 id 51 symbol 52 totalSupply 53 } 54 token0Price 55 token1Price 56 volumeToken0 57 volumeToken1 58 } 59 60 usdc: pair(id:"0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc"){ 61 token0 { 62 id 63 symbol 64 totalSupply 65 } 66 token1 { 67 id 68 symbol 69 totalSupply 70 } 71 token0Price 72 token1Price 73 volumeToken0 74 volumeToken1 75 } 76 } 77 `) 78 79 for k, v := range resty.DefaultHeader { 80 req.Header.Add(k, v) 81 } 82 83 // run it and capture the response 84 q := &Query{} 85 if err := hql.Run(ctx, req, q); err != nil { 86 return 0, err 87 } 88 89 switch strings.ToUpper(symbol) { 90 case "ZCN": 91 ethPerZCN, _ := strconv.ParseFloat(q.ZCN.Token1Price, 64) 92 usdcPerETH, _ := strconv.ParseFloat(q.USDC.Token0Price, 64) 93 return ethPerZCN * usdcPerETH, nil 94 case "ETH": 95 usdcPerETH, _ := strconv.ParseFloat(q.USDC.Token0Price, 64) 96 return usdcPerETH, nil 97 } 98 99 return 0, errors.New("uniswap: quote [" + symbol + "] is unimplemented yet") 100 }