-
Notifications
You must be signed in to change notification settings - Fork 0
/
balancecmd.go
71 lines (62 loc) · 1.99 KB
/
balancecmd.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
package main
import (
"fmt"
"math"
"math/big"
"github.com/kruspy/erc20-token-cli/cmd/utils"
token "github.com/kruspy/erc20-token-cli/contracts"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/urfave/cli/v2"
)
var (
balanceCommand = &cli.Command{
Action: tokenBalance,
Name: "balance",
Usage: "Check the balance of an ERC20 token for a given wallet address",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "token",
Usage: "Token contract address",
Required: true,
},
&cli.StringFlag{
Name: "wallet",
Usage: "Wallet address",
Required: true,
},
&cli.StringFlag{
Name: "ethclient",
Value: "http://127.0.0.1:8545",
Usage: "Ethereum client to connect",
},
},
Description: `
Retrieves the token balance of an address. Both the address of the token contract
and the address of the wallet are required flags.
An optional flag can be passed to specify the network where the query is going
to take place.
`,
}
)
func tokenBalance(ctx *cli.Context) error {
tokenAddress := common.HexToAddress(ctx.String("token"))
// Get an intance of the contract to interact with it
instance, err := token.NewToken(tokenAddress, utils.Client(ctx.String("ethclient")))
if err != nil {
utils.Fatalf(err.Error())
}
walletAddress := common.HexToAddress(ctx.String("wallet"))
// Send a query to the chain using the contract instance
minimalRepBalance, err := instance.BalanceOf(&bind.CallOpts{}, walletAddress)
if err != nil {
utils.Fatalf(err.Error())
}
fbal := new(big.Float)
fbal.SetString(minimalRepBalance.String())
// Divide the minimal representation of the amount by the number of decimals to obtain a classic representation,
// i.e. 12550120 -> 12.550120
balance := new(big.Float).Quo(fbal, big.NewFloat(math.Pow10(int(utils.TokenDecimals(instance)))))
fmt.Printf("Wallet address: %v\nCurrent balance: %v%v\n", ctx.String("wallet"), balance, utils.TokenSymbol(instance))
return nil
}