Skip to content

Commit ec4fc08

Browse files
committed
feat(add load balance logic): add load balance logic
add load balance logic
1 parent 29eb3e2 commit ec4fc08

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,23 @@ ganache-cli
5757

5858
```yaml
5959
ETH_JSON_RPC_URL=http://localhost:8545
60+
```
61+
62+
## add lookup balance logic
63+
64+
```golang
65+
// find specific address balance
66+
addr := config.AppConfig.EthAddress
67+
address := common.HexToAddress(addr)
68+
69+
balance, err := client.BalanceAt(context.Background(), address, nil)
70+
if err != nil {
71+
log.Fatalf("Error to get the balance:%v", err)
72+
}
73+
fmt.Println("The balance:", balance)
74+
// 1 ether = 10^18 wei
75+
fBalance := new(big.Float)
76+
fBalance.SetString(balance.String())
77+
balanceEther := new(big.Float).Quo(fBalance, big.NewFloat(math.Pow10(18)))
78+
fmt.Println("address:", config.AppConfig.EthAddress, "has", balanceEther, "ether")
6079
```

internal/config/config.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88

99
type Config struct {
1010
EthJsonRpcURL string `mapstructure:"ETH_JSON_RPC_URL"`
11+
EthAddress string `mapstructure:"ETH_ADDRESS"`
1112
}
1213

1314
var AppConfig *Config
@@ -19,6 +20,7 @@ func init() {
1920
v.SetConfigType("env")
2021
v.AutomaticEnv()
2122
failOnError(v.BindEnv("ETH_JSON_RPC_URL"), "fail on Bind ETH_JSON_RPC_URL")
23+
failOnError(v.BindEnv("ETH_ADDRESS"), "fail on Bind ETH_ADDRESS")
2224
err := v.ReadInConfig()
2325
if err != nil {
2426
log.Println("load from environment variable")

learn/go-client.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import (
44
"context"
55
"fmt"
66
"log"
7+
"math"
8+
"math/big"
79

10+
"github.com/ethereum/go-ethereum/common"
811
"github.com/ethereum/go-ethereum/ethclient"
912
"github.com/leetcode-golang-classroom/golang-ethereum-sample/internal/config"
1013
)
@@ -21,5 +24,20 @@ func main() {
2124
log.Fatalf("Error to get a block: %v", err)
2225
}
2326
// get latest block number
24-
fmt.Println(block.Number())
27+
fmt.Println("The block number:", block.Number())
28+
29+
// find specific address balance
30+
addr := config.AppConfig.EthAddress
31+
address := common.HexToAddress(addr)
32+
33+
balance, err := client.BalanceAt(context.Background(), address, nil)
34+
if err != nil {
35+
log.Fatalf("Error to get the balance:%v", err)
36+
}
37+
fmt.Println("The balance:", balance)
38+
// 1 ether = 10^18 wei
39+
fBalance := new(big.Float)
40+
fBalance.SetString(balance.String())
41+
balanceEther := new(big.Float).Quo(fBalance, big.NewFloat(math.Pow10(18)))
42+
fmt.Println("address:", config.AppConfig.EthAddress, "has", balanceEther, "ether")
2543
}

0 commit comments

Comments
 (0)