Skip to content

Commit

Permalink
cleaned up error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
jubeless committed Nov 27, 2020
1 parent b893a1c commit 026969c
Show file tree
Hide file tree
Showing 20 changed files with 162 additions and 109 deletions.
1 change: 1 addition & 0 deletions .envrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export SLNC_GLOBAL_INSECURE_VAULT_PASSPHRASE=secure
3 changes: 0 additions & 3 deletions cmd/slnc/cmd/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,6 @@ func getClient() *rpc.Client {
}
api.SetHeader(headerArray[0], headerArray[1])
}

api.Debug = viper.GetBool("global-debug")

return api
}

Expand Down
7 changes: 4 additions & 3 deletions cmd/slnc/cmd/get_account.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@ var getAccountCmd = &cobra.Command{
}

acct := resp.Value

data, err := json.MarshalIndent(acct, "", " ")
errorCheck("json marshal", err)
var data []byte
if data, err = json.MarshalIndent(acct, "", " "); err != nil {
return fmt.Errorf("unable to marshall account information: %w", err)
}

fmt.Println(string(data))

Expand Down
3 changes: 1 addition & 2 deletions cmd/slnc/cmd/get_balance.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package cmd

import (
"context"
"errors"
"fmt"

"github.com/spf13/cobra"
Expand All @@ -36,7 +35,7 @@ var getBalanceCmd = &cobra.Command{
}

if resp.Value == 0 {
errorCheck("not found", errors.New("account not found"))
return fmt.Errorf("account not found")
}

fmt.Println(resp.Value, "lamports")
Expand Down
18 changes: 5 additions & 13 deletions cmd/slnc/cmd/get_confirmed_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ var getConfirmedBlockCmd = &cobra.Command{
Use: "confirmed-block {block_num}",
Short: "Retrieve a confirmed block, with all of its transactions",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, args []string) (err error) {
client := getClient()
ctx := context.Background()

slot, err := strconv.ParseInt(args[0], 10, 64)
errorCheck("parsing slot number in first argument", err)
var slot int64
if slot, err = strconv.ParseInt(args[0], 10, 64); err != nil {
return fmt.Errorf("unable to parse provided slot number %q: %w", args[0], err)
}

resp, err := client.GetConfirmedBlock(ctx, uint64(slot), "")
if err != nil {
Expand All @@ -42,16 +44,6 @@ var getConfirmedBlockCmd = &cobra.Command{
cnt, _ := json.MarshalIndent(resp, "", " ")
fmt.Println(string(cnt))

// for idx, trx := range resp.Transactions {
// unpacked, err := solana.TransactionFromData(trx.Transaction)
// if err != nil {
// return err
// }

// cnt, _ := json.MarshalIndent(unpacked, "", " ")
// fmt.Println(idx, string(cnt))
// }

return nil
},
}
Expand Down
3 changes: 1 addition & 2 deletions cmd/slnc/cmd/get_program_accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ package cmd
import (
"context"
"encoding/json"
"errors"
"fmt"

"github.com/dfuse-io/solana-go"
Expand All @@ -39,7 +38,7 @@ var getProgramAccountsCmd = &cobra.Command{
}

if resp == nil {
errorCheck("not found", errors.New("program account not found"))
return fmt.Errorf("program account not found")
}

for _, keyedAcct := range resp {
Expand Down
6 changes: 2 additions & 4 deletions cmd/slnc/cmd/get_spl_token.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
package cmd

import (
"context"
"errors"
"fmt"
"log"
"os"
Expand All @@ -35,7 +33,7 @@ var getSPLTokenCmd = &cobra.Command{
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
client := getClient()
ctx := context.Background()
ctx := cmd.Context()

resp, err := client.GetProgramAccounts(
ctx,
Expand All @@ -53,7 +51,7 @@ var getSPLTokenCmd = &cobra.Command{
}

if resp == nil {
errorCheck("not found", errors.New("program account not found"))
return fmt.Errorf("program account not found")
}

for _, keyedAcct := range resp {
Expand Down
33 changes: 22 additions & 11 deletions cmd/slnc/cmd/get_transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,18 @@ var getTransactionsCmd = &cobra.Command{

address := args[0]
pubKey, err := solana.PublicKeyFromBase58(address)
errorCheck("public key", err)
if err != nil {
return fmt.Errorf("invalid account address %q: %w", address, err)
}

csList, err := client.GetConfirmedSignaturesForAddress2(ctx, pubKey, &rpc.GetConfirmedSignaturesForAddress2Opts{
Limit: 1,
Before: "",
Until: "",
})

errorCheck("getting confirm transaction:", err)
if err != nil {
return fmt.Errorf("unable to retrieve confirmed transaction signatures for account: %w", err)
}

for _, cs := range csList {
fmt.Println("-----------------------------------------------------------------------------------------------")
Expand All @@ -60,19 +63,22 @@ var getTransactionsCmd = &cobra.Command{
fmt.Println(cs.Memo)

ct, err := client.GetConfirmedTransaction(ctx, cs.Signature)
errorCheck("confirm transaction", err)
if err != nil {
return fmt.Errorf("unable to get confirmed transaction with signature %q: %w", cs.Signature, err)
}

if ct.Meta.Err != nil {
fmt.Println("ERROR:", ct.Meta.Err)
// for k, _ := range ct.Meta.Err
return fmt.Errorf("unable to get confirmed transaction with signature %q: %s", cs.Signature, ct.Meta.Err)
}

fmt.Print("\nInstructions:\n-------------\n\n")
for _, i := range ct.Transaction.Message.Instructions {

//Missing Initial account instruction ??????

id, err := ct.Transaction.ResolveProgramIDIndex(i.ProgramIDIndex)
errorCheck("resolving programID", err)
if err != nil {
return fmt.Errorf("unable to resolve program ID: %w", err)
}

decoder := solana.InstructionDecoderRegistry[id.String()]
if decoder == nil {
fmt.Println("raw instruction:")
Expand All @@ -88,9 +94,14 @@ var getTransactionsCmd = &cobra.Command{
}

decoded, err := decoder(ct.Transaction.AccountMetaList(), &i)
errorCheck("bin decode", err)
if err != nil {
return fmt.Errorf("unable to decode instruction: %w", err)
}

err = text.NewEncoder(os.Stdout).Encode(decoded, nil)
errorCheck("textEncoding", err)
if err != nil {
return fmt.Errorf("unable to text encoder instruction: %w", err)
}
}
text.EncoderColorCyan.Print("\n\nEnd of transaction\n\n")
}
Expand Down
17 changes: 3 additions & 14 deletions cmd/slnc/cmd/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
package cmd

import (
"fmt"
"os"
"strings"

Expand All @@ -32,19 +31,9 @@ func init() {
logging.Register("github.com/dfuse-io/solana-go/cmd/slnc/cmd", &zlog)
}

func SetupLogger(debug bool) {
fmt.Println("setting logger with debug:", debug)
if debug {
zlog, err := zap.NewDevelopment()
fmt.Println("setting logger1")
if err == nil {
fmt.Println("setting logger2")
logging.Set(zlog)
}
// Hijack standard Golang `log` and redirect it to our common logger
zap.RedirectStdLogAt(zlog, zap.DebugLevel)

}
func SetupLogger() {
commonLogger := createLogger("cli", 1, zap.FatalLevel)
logging.Set(commonLogger)

// Fine-grain customization
//
Expand Down
12 changes: 8 additions & 4 deletions cmd/slnc/cmd/request_airdrop.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,28 @@ import (

var requestCmd = &cobra.Command{
Use: "request-airdrop {address} {lamport}",
Short: "request lamport airdrop for an account",
Short: "Request lamport airdrop for an account",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {

client := getClient()

address, err := solana.PublicKeyFromBase58(args[0])
errorCheck("invalid token address", err)
if err != nil {
return fmt.Errorf("invalid account address %q: %w", args[0], err)
}

lamport, err := strconv.Atoi(args[1])
if err != nil {
return fmt.Errorf("invalid lamport value, expected a int value, got : %s", args[1])
}

airDrop, err := client.RequestAirdrop(context.Background(), &address, uint64(lamport), rpc.CommitmentMax)
errorCheck("air drop", err)
fmt.Println("air drop hash:", airDrop)
if err != nil {
return fmt.Errorf("airdrop request failed: %w", err)
}

fmt.Println("Air drop succeeded, transaction hash:", airDrop)
return nil
},
}
Expand Down
15 changes: 6 additions & 9 deletions cmd/slnc/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,27 +46,24 @@ func Execute() {

func init() {
cobra.OnInitialize(initConfig)

RootCmd.PersistentFlags().BoolP("debug", "", false, "Enables verbose API debug messages")
// Not implemnted
//RootCmd.PersistentFlags().BoolP("debug", "", false, "Enables verbose API debug messages")
RootCmd.PersistentFlags().StringP("vault-file", "", "./solana-vault.json", "Wallet file that contains encrypted key material")
RootCmd.PersistentFlags().StringP("rpc-url", "u", defaultRPCURL, "API endpoint of eos.io blockchain node")
RootCmd.PersistentFlags().StringSliceP("http-header", "H", []string{}, "HTTP header to add to JSON-RPC requests")
RootCmd.PersistentFlags().StringP("kms-gcp-keypath", "", "", "Path to the cryptoKeys within a keyRing on GCP")
// RootCmd.PersistentFlags().StringP("write-transaction", "", "", "Do not broadcast the transaction produced, but write it in json to the given filename instead.")
// RootCmd.PersistentFlags().StringP("offline-head-block", "", "", "Provide a recent block ID (long-form hex) for TaPoS. Use all --offline options to sign transactions offline.")
// RootCmd.PersistentFlags().StringP("offline-chain-id", "", "", "Chain ID to sign transaction with. Use all --offline- options to sign transactions offline.")
// RootCmd.PersistentFlags().StringSliceP("offline-sign-key", "", []string{}, "Public key to use to sign transaction. Must be in your vault or wallet. Use all --offline- options to sign transactions offline.")
// RootCmd.PersistentFlags().BoolP("skip-sign", "", false, "Do not sign the transaction. Use with --write-transaction.")

SetupLogger(viper.GetBool("global-debug"))
RootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
SetupLogger()
return nil
}
}

func initConfig() {
viper.SetEnvPrefix("SLNC")
viper.AutomaticEnv()
replacer := strings.NewReplacer("-", "_")
viper.SetEnvKeyReplacer(replacer)

recurseViperCommands(RootCmd, nil)
}

Expand Down
9 changes: 7 additions & 2 deletions cmd/slnc/cmd/token_registry_get.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ var tokenRegistryGetCmd = &cobra.Command{

address := args[0]
pubKey, err := solana.PublicKeyFromBase58(address)
errorCheck("public key", err)
if err != nil {
return fmt.Errorf("invalid mint address %q: %w", address, err)
}

t, err := tokenregistry.GetTokenRegistryEntry(cmd.Context(), client, pubKey)
if err != nil {
Expand All @@ -47,7 +49,10 @@ var tokenRegistryGetCmd = &cobra.Command{
}

err = text.NewEncoder(os.Stdout).Encode(t, nil)
errorCheck("textEncoding", err)
if err != nil {
return fmt.Errorf("unable to text encode token registry entry: %w", err)
}

return nil
},
}
Expand Down
Loading

0 comments on commit 026969c

Please sign in to comment.