-
Notifications
You must be signed in to change notification settings - Fork 71
/
balance.go
60 lines (49 loc) · 1.29 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
package cmd
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/ardanlabs/blockchain/foundation/blockchain/database"
"github.com/ethereum/go-ethereum/crypto"
"github.com/spf13/cobra"
)
type balance struct {
Account string `json:"account"`
Balance uint `json:"balance"`
}
type balances struct {
LastestBlock string `json:"lastest_block"`
Uncommitted int `json:"uncommitted"`
Balances []balance `json:"balances"`
}
var balanceCmd = &cobra.Command{
Use: "balance",
Short: "Print your balance.",
Run: balanceRun,
}
func init() {
rootCmd.AddCommand(balanceCmd)
balanceCmd.Flags().StringVarP(&url, "url", "u", "http://localhost:8080", "Url of the node.")
}
func balanceRun(cmd *cobra.Command, args []string) {
privateKey, err := crypto.LoadECDSA(getPrivateKeyPath())
if err != nil {
log.Fatal(err)
}
accountID := database.PublicKeyToAccountID(privateKey.PublicKey)
fmt.Println("For Account:", accountID)
resp, err := http.Get(fmt.Sprintf("%s/v1/accounts/list/%s", url, accountID))
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var balances balances
if err := decoder.Decode(&balances); err != nil {
log.Fatal(err)
}
if len(balances.Balances) > 0 {
fmt.Println(balances.Balances[0].Balance)
}
}