From af3ceec223fe1e51db8b6aed1a80ce1425fa83b4 Mon Sep 17 00:00:00 2001 From: abs3nt Date: Tue, 28 Feb 2023 18:37:33 -0800 Subject: [PATCH] crypto --- cmd/crypto.go | 49 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/cmd/crypto.go b/cmd/crypto.go index 1f23cd7..6416ec8 100644 --- a/cmd/crypto.go +++ b/cmd/crypto.go @@ -12,10 +12,16 @@ import ( "github.com/spf13/cobra" ) -type Tokens []struct { - ID string `json:"id"` - Symbol string `json:"symbol"` - Name string `json:"name"` +type Search struct { + Coins []struct { + ID string `json:"id"` + Name string `json:"name"` + APISymbol string `json:"api_symbol"` + Symbol string `json:"symbol"` + MarketCapRank int `json:"market_cap_rank"` + Thumb string `json:"thumb"` + Large string `json:"large"` + } `json:"coins"` } type Price map[string]USD @@ -26,8 +32,7 @@ type USD struct { var ( price_url = "https://api.coingecko.com/api/v3/simple/price?" - vs_url = "https://api.coingecko.com/api/v3/simple/supported_vs_currencies" - tokens_url = "https://api.coingecko.com/api/v3/coins/list" + search_url = "https://api.coingecko.com/api/v3/search?query=" ) var amount float64 @@ -37,6 +42,13 @@ var cryptoCmd = &cobra.Command{ Use: "crypto", Short: "get price of token", Long: `get price of token`, + Args: cobra.MatchAll(cobra.RangeArgs(1, 2), cobra.OnlyValidArgs), + ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if len(args) >= 2 { + return nil, cobra.ShellCompDirectiveNoFileComp + } + return getTokens(toComplete), cobra.ShellCompDirectiveNoFileComp + }, RunE: func(cmd *cobra.Command, args []string) error { price, err := usdPrice(args[0]) if err != nil { @@ -55,6 +67,31 @@ var cryptoCmd = &cobra.Command{ }, } +func getTokens(in string) []string { + if in == "" { + return []string{"ethereum", "bitcoin", "tether", "binancecoin", "usd-coin", "ripple", "cardano", "dogecoin", "matic-network"} + } + resp, err := http.Get(search_url + in) + if err != nil { + return []string{err.Error()} + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return []string{err.Error()} + } + var tokens Search + err = json.Unmarshal(body, &tokens) + if err != nil { + return []string{err.Error()} + } + out := []string{} + for _, token := range tokens.Coins { + out = append(out, token.ID) + } + return out +} + func usdPrice(token string) (float64, error) { resp, err := http.Get(price_url + fmt.Sprintf("ids=%s&vs_currencies=usd", token)) if err != nil {