converter/cmd/crypto.go
2023-02-28 18:37:33 -08:00

117 lines
2.6 KiB
Go

/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/spf13/cobra"
)
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
type USD struct {
Usd float64
}
var (
price_url = "https://api.coingecko.com/api/v3/simple/price?"
search_url = "https://api.coingecko.com/api/v3/search?query="
)
var amount float64
// cryptoCmd represents the crypto command
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 {
return err
}
price = price * amount
price2 := float64(1)
if len(args) >= 2 {
price2, err = usdPrice(args[1])
if err != nil {
return err
}
}
fmt.Println(price / price2)
return nil
},
}
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 {
return 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}
var price Price
err = json.Unmarshal(body, &price)
if err != nil {
return 0, err
}
return price[token].Usd, nil
}
func init() {
rootCmd.AddCommand(cryptoCmd)
cryptoCmd.PersistentFlags().Float64VarP(&amount, "amount", "a", 1, "amount of the given token")
}