/
balance.go
82 lines (68 loc) · 2.15 KB
/
balance.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package ensquery
import (
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"os"
"strconv"
)
// These contain data to be returned by the Etherscan API
type ethBalance struct {
Status string `json:"status"`
Message string `json:"message"`
Result string `json:"result"`
}
type ethConv struct {
Ethbtc string `json:"ethbtc"`
Ethbtc_timestap string `json:"ethbtc_timestamp"`
Ethusd string `json:"ethusd"`
Ethusd_timestamp string `json:"ethusd_timestamp"`
}
type ethVal struct {
Status string `json:"status"`
Message string `json:"message"`
Result ethConv `json:"result"`
}
/*
We use the Etherscan API to return the balance of an address in ETH and USD.
The Ethplorer API is of interest (among other tools) in the future as support
for ERC-20 tokens is under consideration.
*/
func GetEthBalance(address string) (string, string) {
apiKey := os.Getenv("ETHERSCAN_API_KEY")
balanceUrl := fmt.Sprintf("https://api.etherscan.io/api?module=account&action=balance&address=%s&tag=latest&apikey=%s", address, apiKey)
ethUsdUrl := fmt.Sprintf("https://api.etherscan.io/api?module=stats&action=ethprice&apikey=%s", apiKey)
balanceStruct := ethBalance{}
convStruct := ethVal{}
balResp, err := http.Get(balanceUrl)
CheckErr(err)
balBody, err := ioutil.ReadAll(balResp.Body)
CheckErr(err)
err = json.Unmarshal(balBody, &balanceStruct)
CheckErr(err)
balanceMessage := balanceStruct.Message
if balanceMessage != "OK" {
panic(fmt.Sprintf("Unexpected response: balanceStruct.Message == %s", balanceMessage))
}
convResp, err := http.Get(ethUsdUrl)
CheckErr(err)
convBody, err := ioutil.ReadAll(convResp.Body)
CheckErr(err)
err = json.Unmarshal(convBody, &convStruct)
CheckErr(err)
convMessage := convStruct.Message
if convMessage != "OK" {
panic(fmt.Sprintf("Unexpected response: convStruct.Message == %s", convMessage))
}
balance, err := strconv.ParseFloat(balanceStruct.Result, 64)
CheckErr(err)
ethFloat := balance / math.Pow(10, 18)
ethUsd, err := strconv.ParseFloat(convStruct.Result.Ethusd, 64)
CheckErr(err)
usdFloat := ethFloat * ethUsd
eth := fmt.Sprintf("%f", ethFloat)
usd := fmt.Sprintf("%f", usdFloat)
return eth, usd
}