-
Notifications
You must be signed in to change notification settings - Fork 4
/
cmd.go
338 lines (271 loc) · 8.54 KB
/
cmd.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package main
import (
"fmt"
"log"
"os"
"strconv"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/dymensionxyz/eibc-client/cmd/version"
"github.com/dymensionxyz/eibc-client/store"
utils "github.com/dymensionxyz/eibc-client/utils/viper"
)
var rootCmd = &cobra.Command{
Use: "eibc-client",
Short: "eIBC Order client for Dymension Hub",
Long: `Order client for Dymension Hub that scans for demand orders and fulfills them.`,
Run: func(cmd *cobra.Command, args []string) {
// If no arguments are provided, print usage information
if len(args) == 0 {
if err := cmd.Usage(); err != nil {
log.Fatalf("Error printing usage: %v", err)
}
}
},
}
var initCmd = &cobra.Command{
Use: "init",
Short: "Initialize the order client",
Long: `Initialize the order client by generating a config file with default values.`,
Run: func(cmd *cobra.Command, args []string) {
config := Config{}
if err := viper.Unmarshal(&config); err != nil {
log.Fatalf("failed to unmarshal config: %v", err)
}
// if home dir doesn't exist, create it
if _, err := os.Stat(config.HomeDir); os.IsNotExist(err) {
if err := os.MkdirAll(config.HomeDir, 0o755); err != nil {
log.Fatalf("failed to create home directory: %v", err)
}
}
if err := viper.WriteConfigAs(cfgFile); err != nil {
log.Fatalf("failed to write config file: %v", err)
}
fmt.Printf("Config file created: %s\n", cfgFile)
fmt.Println()
fmt.Println("Edit the config file to set the correct values for your environment.")
},
}
var startCmd = &cobra.Command{
Use: "start",
Short: "Start the order client",
Long: `Start the order client that scans for demand orders and fulfills them.`,
Run: func(cmd *cobra.Command, args []string) {
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
config := Config{}
if err := viper.Unmarshal(&config); err != nil {
log.Fatalf("failed to unmarshal config: %v", err)
}
log.Printf("using config file: %+v", viper.ConfigFileUsed())
oc, err := newOrderClient(cmd.Context(), config)
if err != nil {
log.Fatalf("failed to create order client: %v", err)
}
if config.Bots.NumberOfBots == 0 {
log.Println("no bots to start")
return
}
if err := oc.start(cmd.Context()); err != nil {
log.Fatalf("failed to start order client: %v", err)
}
},
}
var balancesCmd = &cobra.Command{
Use: "funds",
Short: "Get account funds",
Long: `Get account balances and pending rewards for the configured whale account and the bot accounts.`,
Run: func(cmd *cobra.Command, args []string) {
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
config := Config{}
if err := viper.Unmarshal(&config); err != nil {
log.Fatalf("failed to unmarshal config: %v", err)
}
config.SkipRefund = true
oc, err := newOrderClient(cmd.Context(), config)
if err != nil {
log.Fatalf("failed to create order client: %v", err)
}
defer oc.orderTracker.store.Close()
if err := oc.whale.accountSvc.refreshBalances(cmd.Context()); err != nil {
log.Fatalf("failed to refresh whale account balances: %v", err)
}
longestAmountStr := 0
for _, bal := range oc.whale.accountSvc.balances {
amtStr := formatAmount(bal.Amount.String())
if len(amtStr) > longestAmountStr {
longestAmountStr = len(amtStr)
}
}
fmt.Println()
fmt.Println("Bots Funds:")
bots, err := oc.orderTracker.store.GetBots(cmd.Context(), store.OnlyWithFunds())
if err != nil {
log.Fatalf("failed to get bots from db: %v", err)
}
for _, b := range bots {
balances, err := sdk.ParseCoinsNormalized(strings.Join(b.Balances, ","))
if err != nil {
log.Fatalf("failed to parse balance: %v", err)
}
pendingRewards, err := sdk.ParseCoinsNormalized(strings.Join(b.PendingRewards, ","))
if err != nil {
log.Fatalf("failed to parse pending rewards: %v", err)
}
for _, bal := range balances {
if len(bal.Amount.String()) > longestAmountStr {
longestAmountStr = len(bal.Amount.String())
}
}
for _, pr := range pendingRewards {
if len(pr.Amount.String()) > longestAmountStr {
longestAmountStr = len(pr.Amount.String())
}
}
}
maxDen := 68
dividerItem := ""
dividerFunds := ""
for i := 0; i < longestAmountStr+maxDen+3; i++ {
dividerItem += "="
dividerFunds += "-"
}
totalBalances := sdk.NewCoins(oc.whale.accountSvc.balances...)
totalPendingRewards := sdk.NewCoins()
i := 0
for _, b := range bots {
i++
balances, err := sdk.ParseCoinsNormalized(strings.Join(b.Balances, ","))
if err != nil {
log.Fatalf("failed to parse balance: %v", err)
}
pendingRewards, err := sdk.ParseCoinsNormalized(strings.Join(b.PendingRewards, ","))
if err != nil {
log.Fatalf("failed to parse pending rewards: %v", err)
}
totalBalances = totalBalances.Add(balances...)
totalPendingRewards = totalPendingRewards.Add(pendingRewards...)
if !balances.IsZero() {
accPref := fmt.Sprintf("%d. | '%s': ", i, b.Name)
printAccountSlot(b.Address, accPref, dividerItem)
fmt.Println("Balances:")
printBalances(balances, longestAmountStr, maxDen)
fmt.Println()
}
if !pendingRewards.IsZero() {
fmt.Println("Pending Rewards:")
fmt.Println(dividerFunds)
printBalances(pendingRewards, longestAmountStr, maxDen)
}
}
fmt.Println()
fmt.Println("Whale Balances:")
if !oc.whale.accountSvc.balances.IsZero() {
accPref := fmt.Sprintf("Whale | '%s': ", oc.whale.accountSvc.accountName)
printAccountSlot(
oc.whale.accountSvc.account.GetAddress().String(),
accPref,
dividerItem,
)
printBalances(oc.whale.accountSvc.balances, longestAmountStr, maxDen)
fmt.Println()
}
fmt.Println()
fmt.Println("Total:")
fmt.Println(dividerItem)
fmt.Println("Balances:")
printBalances(totalBalances, longestAmountStr, maxDen)
fmt.Println(dividerFunds)
fmt.Println("Pending Rewards:")
printBalances(totalPendingRewards, longestAmountStr, maxDen)
},
}
var scaleCmd = &cobra.Command{
Use: "scale [count]",
Short: "scale bot count",
Long: `scale the number of bot accounts that fulfill the eibc orders`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
newBotCount, err := strconv.Atoi(args[0])
if err != nil {
return
}
home, err := homedir.Dir()
if err != nil {
log.Fatalf("failed to get home directory: %v", err)
}
defaultHomeDir := home + "/.eibc-client"
cfgFile = defaultHomeDir + "/config.yaml"
viper.SetConfigFile(cfgFile)
err = viper.ReadInConfig()
if err != nil {
return
}
err = utils.UpdateViperConfig("bots.number_of_bots", newBotCount, viper.ConfigFileUsed())
if err != nil {
return
}
fmt.Printf(
"bot count successfully scaled to %d, please restart the eibc process if it's running\n",
newBotCount,
)
},
}
func printAccountSlot(address string, accPref, dividerItem string) {
dividerAcc := ""
fmt.Printf("%s", dividerItem)
accLine := fmt.Sprintf("\n %s%s |", accPref, address)
for i := 0; i < len(accLine)-1; i++ {
dividerAcc += "-"
}
fmt.Printf("%s\n", accLine)
fmt.Printf("%s\n", dividerAcc)
}
func printBalances(balances sdk.Coins, maxBal, maxDen int) {
dividerBal, dividerDen := "", ""
for i := 0; i < maxBal; i++ {
dividerBal += "-"
}
for i := 0; i < maxDen; i++ {
dividerDen += "-"
}
fmt.Printf("%*s | Denom\n", maxBal, "Amount")
fmt.Printf("%*s | %s\n", maxBal, dividerBal, dividerDen)
for _, bl := range balances {
amtStr := bl.Amount.String()
if bl.Denom == "adym" {
amtStr = formatAmount(bl.Amount.String())
bl.Denom = "dym"
}
fmt.Printf("%*s | %-s\n", maxBal, amtStr, bl.Denom)
}
}
func formatAmount(numStr string) string {
if len(numStr) <= 18 {
return "0," + strings.Repeat("0", 18-len(numStr)) + numStr
}
return numStr[:len(numStr)-18] + "," + numStr[len(numStr)-18:]
}
var cfgFile string
func init() {
rootCmd.CompletionOptions.DisableDefaultCmd = true
rootCmd.AddCommand(initCmd)
rootCmd.AddCommand(startCmd)
rootCmd.AddCommand(scaleCmd)
balancesCmd.Flags().BoolP("all", "a", false, "Filter by fulfillment status")
rootCmd.AddCommand(balancesCmd)
rootCmd.AddCommand(version.Cmd())
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}