Skip to content

Commit 3dca5a5

Browse files
committed
refactor: standardize error handling and improve code readability in wasp-cli commands
1 parent 7831b0b commit 3dca5a5

File tree

21 files changed

+400
-264
lines changed

21 files changed

+400
-264
lines changed

tools/wasp-cli/chain/access-nodes.go

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package chain
66

77
import (
88
"context"
9+
"fmt"
910

1011
"github.com/spf13/cobra"
1112

@@ -29,7 +30,10 @@ func initPermissionlessAccessNodesCmd() *cobra.Command {
2930
if err != nil {
3031
return err
3132
}
32-
chain = defaultChainFallback(chain)
33+
chain, err = defaultChainFallback(chain)
34+
if err != nil {
35+
return err
36+
}
3337

3438
action := args[0]
3539
node, err = waspcmd.DefaultWaspNodeFallback(node)
@@ -39,31 +43,39 @@ func initPermissionlessAccessNodesCmd() *cobra.Command {
3943
ctx := context.Background()
4044
client := cliclients.WaspClientWithVersionCheck(ctx, node)
4145

42-
var executeActionFunc func(peer string)
46+
var executeActionFunc func(peer string) error
4347

4448
switch action {
4549
case "add":
46-
executeActionFunc = func(peer string) {
50+
executeActionFunc = func(peer string) error {
4751
_, err := client.ChainsAPI.
4852
AddAccessNode(ctx, peer).
4953
Execute() //nolint:bodyclose // false positive
50-
log.Check(err)
54+
if err != nil {
55+
return err
56+
}
5157
log.Printf("added %s as an access node\n", peer)
58+
return nil
5259
}
5360
case "remove":
54-
executeActionFunc = func(peer string) {
61+
executeActionFunc = func(peer string) error {
5562
_, err := client.ChainsAPI.
5663
RemoveAccessNode(ctx, peer).
5764
Execute() //nolint:bodyclose // false positive
58-
log.Check(err)
65+
if err != nil {
66+
return err
67+
}
5968
log.Printf("removed %s as an access node\n", peer)
69+
return nil
6070
}
6171
default:
62-
log.Fatalf("unknown action: %s", action)
72+
return fmt.Errorf("unknown action: %s", action)
6373
}
6474

6575
for _, peer := range peers {
66-
executeActionFunc(peer)
76+
if err := executeActionFunc(peer); err != nil {
77+
return err
78+
}
6779
}
6880
return nil
6981
},

tools/wasp-cli/chain/accounts.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,10 @@ func initAccountObjectsCmd() *cobra.Command {
8282
if err != nil {
8383
return err
8484
}
85-
chain = defaultChainFallback(chain)
85+
chain, err = defaultChainFallback(chain)
86+
if err != nil {
87+
return err
88+
}
8689
agentID := util.AgentIDFromArgs(args)
8790
ctx := context.Background()
8891
client := cliclients.WaspClientWithVersionCheck(ctx, node)
@@ -154,7 +157,10 @@ func initDepositCmd() *cobra.Command {
154157
if err != nil {
155158
return err
156159
}
157-
chain = defaultChainFallback(chain)
160+
chain, err = defaultChainFallback(chain)
161+
if err != nil {
162+
return err
163+
}
158164
chainID := config.GetChain(chain)
159165

160166
ctx, cancel := context.WithTimeout(context.Background(), time.Second*1000)

tools/wasp-cli/chain/activate.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ func initActivateCmd() *cobra.Command {
2727
if err != nil {
2828
return err
2929
}
30-
chainName = defaultChainFallback(chainName)
30+
chainName, err = defaultChainFallback(chainName)
31+
if err != nil {
32+
return err
33+
}
3134
chainID := config.GetChain(chainName)
3235
ctx := context.Background()
3336
activateChain(ctx, node, chainName, chainID)
@@ -75,9 +78,11 @@ func initDeactivateCmd() *cobra.Command {
7578
Short: "Deactivates the chain on selected nodes",
7679
Args: cobra.NoArgs,
7780
RunE: func(cmd *cobra.Command, args []string) error {
78-
chainName = defaultChainFallback(chainName)
79-
8081
var err error
82+
chainName, err = defaultChainFallback(chainName)
83+
if err != nil {
84+
return err
85+
}
8186
node, err = waspcmd.DefaultWaspNodeFallback(node)
8287
if err != nil {
8388
return err

tools/wasp-cli/chain/blocklog.go

Lines changed: 62 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,30 @@ func initBlockCmd() *cobra.Command {
3333
if err != nil {
3434
return err
3535
}
36-
chain = defaultChainFallback(chain)
36+
chain, err = defaultChainFallback(chain)
37+
if err != nil {
38+
return err
39+
}
3740
ctx := context.Background()
3841
client := cliclients.WaspClientWithVersionCheck(ctx, node)
3942

40-
bi := fetchBlockInfo(ctx, client, args)
43+
bi, err := fetchBlockInfo(ctx, client, args)
44+
if err != nil {
45+
return err
46+
}
4147
log.Printf("Block index: %d\n", bi.BlockIndex)
4248
log.Printf("Timestamp: %s\n", bi.Timestamp.UTC().Format(time.RFC3339))
4349
log.Printf("Total requests: %d\n", bi.TotalRequests)
4450
log.Printf("Successful requests: %d\n", bi.NumSuccessfulRequests)
4551
log.Printf("Off-ledger requests: %d\n", bi.NumOffLedgerRequests)
4652
log.Printf("\n")
47-
logRequestsInBlock(ctx, client, bi.BlockIndex)
53+
if err := logRequestsInBlock(ctx, client, bi.BlockIndex); err != nil {
54+
return err
55+
}
4856
log.Printf("\n")
49-
logEventsInBlock(ctx, client, bi.BlockIndex)
57+
if err := logEventsInBlock(ctx, client, bi.BlockIndex); err != nil {
58+
return err
59+
}
5060
return nil
5161
},
5262
}
@@ -55,76 +65,87 @@ func initBlockCmd() *cobra.Command {
5565
return cmd
5666
}
5767

58-
func fetchBlockInfo(ctx context.Context, client *apiclient.APIClient, args []string) *apiclient.BlockInfoResponse {
68+
func fetchBlockInfo(ctx context.Context, client *apiclient.APIClient, args []string) (*apiclient.BlockInfoResponse, error) {
5969
if len(args) == 0 {
6070
blockInfo, _, err := client.
6171
CorecontractsAPI.
6272
BlocklogGetLatestBlockInfo(ctx).
6373
Execute() //nolint:bodyclose // false positive
64-
65-
log.Check(err)
66-
return blockInfo
74+
if err != nil {
75+
return nil, err
76+
}
77+
return blockInfo, nil
6778
}
6879

6980
blockIndexStr := args[0]
7081
index, err := strconv.ParseUint(blockIndexStr, 10, 32)
71-
log.Check(err)
82+
if err != nil {
83+
return nil, fmt.Errorf("invalid block index '%s': %w", blockIndexStr, err)
84+
}
7285

7386
blockInfo, _, err := client.
7487
CorecontractsAPI.
7588
BlocklogGetBlockInfo(ctx, uint32(index)).
7689
Block(blockIndexStr).
7790
Execute() //nolint:bodyclose // false positive
78-
79-
log.Check(err)
80-
return blockInfo
91+
if err != nil {
92+
return nil, err
93+
}
94+
return blockInfo, nil
8195
}
8296

83-
func logRequestsInBlock(ctx context.Context, client *apiclient.APIClient, index uint32) {
97+
func logRequestsInBlock(ctx context.Context, client *apiclient.APIClient, index uint32) error {
8498
receipts, _, err := client.CorecontractsAPI.
8599
BlocklogGetRequestReceiptsOfBlock(ctx, index).
86100
Block(fmt.Sprintf("%d", index)).
87101
Execute() //nolint:bodyclose // false positive
88-
89-
log.Check(err)
102+
if err != nil {
103+
return err
104+
}
90105

91106
for i, receipt := range receipts {
92107
r := receipt
93108
util.LogReceipt(r, i)
94109
}
110+
return nil
95111
}
96112

97-
func logEventsInBlock(ctx context.Context, client *apiclient.APIClient, index uint32) {
113+
func logEventsInBlock(ctx context.Context, client *apiclient.APIClient, index uint32) error {
98114
events, _, err := client.CorecontractsAPI.
99115
BlocklogGetEventsOfBlock(ctx, index).
100116
Block(fmt.Sprintf("%d", index)).
101117
Execute() //nolint:bodyclose // false positive
102-
103-
log.Check(err)
118+
if err != nil {
119+
return err
120+
}
104121
logEvents(events)
122+
return nil
105123
}
106124

107125
func hexLenFromByteLen(length int) int {
108126
return (length * 2) + 2
109127
}
110128

111-
func reqIDFromString(s string) isc.RequestID {
129+
func reqIDFromString(s string) (isc.RequestID, error) {
112130
switch len(s) {
113131
case hexLenFromByteLen(iotago.AddressLen):
114132
// isc ReqID
115133
reqID, err := isc.RequestIDFromString(s)
116-
log.Check(err)
117-
return reqID
134+
if err != nil {
135+
return isc.RequestID{}, fmt.Errorf("invalid isc requestID: %w", err)
136+
}
137+
return reqID, nil
118138
case hexLenFromByteLen(common.HashLength):
119139
bytes, err := cryptolib.DecodeHex(s)
120-
log.Check(err)
140+
if err != nil {
141+
return isc.RequestID{}, fmt.Errorf("invalid evm tx hash: %w", err)
142+
}
121143
var txHash common.Hash
122144
copy(txHash[:], bytes)
123-
return isc.RequestIDFromEVMTxHash(txHash)
145+
return isc.RequestIDFromEVMTxHash(txHash), nil
124146
default:
125-
log.Fatalf("invalid requestID length: %d", len(s))
147+
return isc.RequestID{}, fmt.Errorf("invalid requestID length: %d", len(s))
126148
}
127-
panic("unreachable")
128149
}
129150

130151
func initRequestCmd() *cobra.Command {
@@ -140,11 +161,17 @@ func initRequestCmd() *cobra.Command {
140161
if err != nil {
141162
return err
142163
}
143-
chain = defaultChainFallback(chain)
164+
chain, err = defaultChainFallback(chain)
165+
if err != nil {
166+
return err
167+
}
144168
ctx := context.Background()
145169
client := cliclients.WaspClientWithVersionCheck(ctx, node)
146170

147-
reqID := reqIDFromString(args[0])
171+
reqID, err := reqIDFromString(args[0])
172+
if err != nil {
173+
return err
174+
}
148175

149176
// TODO add optional block param?
150177
receipt, _, err := client.ChainsAPI.
@@ -158,7 +185,9 @@ func initRequestCmd() *cobra.Command {
158185
util.LogReceipt(*receipt)
159186

160187
log.Printf("\n")
161-
logEventsInRequest(ctx, client, reqID)
188+
if err := logEventsInRequest(ctx, client, reqID); err != nil {
189+
return err
190+
}
162191
log.Printf("\n")
163192
return nil
164193
},
@@ -168,13 +197,15 @@ func initRequestCmd() *cobra.Command {
168197
return cmd
169198
}
170199

171-
func logEventsInRequest(ctx context.Context, client *apiclient.APIClient, reqID isc.RequestID) {
200+
func logEventsInRequest(ctx context.Context, client *apiclient.APIClient, reqID isc.RequestID) error {
172201
events, _, err := client.CorecontractsAPI.
173202
BlocklogGetEventsOfRequest(ctx, reqID.String()).
174203
Execute() //nolint:bodyclose // false positive
175-
176-
log.Check(err)
204+
if err != nil {
205+
return err
206+
}
177207
logEvents(events)
208+
return nil
178209
}
179210

180211
func logEvents(ret *apiclient.EventsResponse) {

tools/wasp-cli/chain/callview.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ func initCallViewCmd() *cobra.Command {
2727
if err != nil {
2828
return err
2929
}
30-
chain = defaultChainFallback(chain)
30+
chain, err = defaultChainFallback(chain)
31+
if err != nil {
32+
return err
33+
}
3134
ctx := context.Background()
3235
client := cliclients.WaspClientWithVersionCheck(ctx, node)
3336

tools/wasp-cli/chain/deploy.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,10 @@ func initDeployCmd() *cobra.Command {
206206
if err != nil {
207207
return err
208208
}
209-
chainName = defaultChainFallback(chainName)
209+
chainName, err = defaultChainFallback(chainName)
210+
if err != nil {
211+
return err
212+
}
210213
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
211214
defer cancel()
212215

tools/wasp-cli/chain/flag.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,38 @@
11
package chain
22

33
import (
4+
"fmt"
5+
46
"github.com/iotaledger/wasp/v2/tools/wasp-cli/cli/config"
5-
"github.com/iotaledger/wasp/v2/tools/wasp-cli/log"
67
"github.com/spf13/cobra"
78
)
89

910
func withChainFlag(cmd *cobra.Command, chainName *string) {
1011
cmd.Flags().StringVar(chainName, "chain", "", "target chain name")
1112
}
1213

13-
func defaultChainFallback(chainName string) string {
14+
func defaultChainFallback(chainName string) (string, error) {
1415
if chainName != "" {
15-
return chainName
16+
return chainName, nil
1617
}
1718
return getDefaultChain()
1819
}
1920

20-
func getDefaultChain() string {
21+
func getDefaultChain() (string, error) {
2122
chainSettings := map[string]interface{}{}
2223
chainsKey := config.Config.Cut("chains")
2324
if chainsKey != nil {
2425
chainSettings = chainsKey.All()
2526
}
2627
switch len(chainSettings) {
2728
case 0:
28-
log.Fatalf("no chains configured, you can add a new chain with `wasp-cli chain add <name> <chain id>`")
29+
return "", fmt.Errorf("no chains configured, you can add a new chain with `wasp-cli chain add <name> <chain id>`")
2930
case 1:
3031
for nodeName := range chainSettings {
31-
return nodeName
32+
return nodeName, nil
3233
}
3334
default:
34-
log.Fatalf("more than 1 chain in the configuration, you can specify the target chain with `--chain=<name>`")
35+
return "", fmt.Errorf("more than 1 chain in the configuration, you can specify the target chain with `--chain=<name>`")
3536
}
36-
panic("unreachable")
37+
return "", nil
3738
}

0 commit comments

Comments
 (0)