github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/crypto/keys/client/add_ledger.go (about)

     1  package client
     2  
     3  import (
     4  	"context"
     5  	"flag"
     6  	"fmt"
     7  
     8  	"github.com/gnolang/gno/tm2/pkg/commands"
     9  	"github.com/gnolang/gno/tm2/pkg/crypto"
    10  	"github.com/gnolang/gno/tm2/pkg/crypto/keys"
    11  )
    12  
    13  // NewAddLedgerCmd creates a gnokey add ledger command
    14  func NewAddLedgerCmd(cfg *AddCfg, io commands.IO) *commands.Command {
    15  	return commands.NewCommand(
    16  		commands.Metadata{
    17  			Name:       "ledger",
    18  			ShortUsage: "add ledger [flags] <key-name>",
    19  			ShortHelp:  "adds a Ledger key reference to the keybase",
    20  		},
    21  		commands.NewEmptyConfig(),
    22  		func(_ context.Context, args []string) error {
    23  			return execAddLedger(cfg, args, io)
    24  		},
    25  	)
    26  }
    27  
    28  func execAddLedger(cfg *AddCfg, args []string, io commands.IO) error {
    29  	// Validate a key name was provided
    30  	if len(args) != 1 {
    31  		return flag.ErrHelp
    32  	}
    33  
    34  	name := args[0]
    35  
    36  	// Read the keybase from the home directory
    37  	kb, err := keys.NewKeyBaseFromDir(cfg.RootCfg.Home)
    38  	if err != nil {
    39  		return fmt.Errorf("unable to read keybase, %w", err)
    40  	}
    41  
    42  	// Check if the key exists
    43  	exists, err := kb.HasByName(name)
    44  	if err != nil {
    45  		return fmt.Errorf("unable to fetch key, %w", err)
    46  	}
    47  
    48  	// Get overwrite confirmation, if any
    49  	if exists {
    50  		overwrite, err := io.GetConfirmation(fmt.Sprintf("Override the existing name %s", name))
    51  		if err != nil {
    52  			return fmt.Errorf("unable to get confirmation, %w", err)
    53  		}
    54  
    55  		if !overwrite {
    56  			return errOverwriteAborted
    57  		}
    58  	}
    59  
    60  	// Create the ledger reference
    61  	info, err := kb.CreateLedger(
    62  		name,
    63  		keys.Secp256k1,
    64  		crypto.Bech32AddrPrefix,
    65  		uint32(cfg.Account),
    66  		uint32(cfg.Index),
    67  	)
    68  	if err != nil {
    69  		return fmt.Errorf("unable to create Ledger reference in keybase, %w", err)
    70  	}
    71  
    72  	// Print the information
    73  	printCreate(info, false, "", io)
    74  
    75  	return nil
    76  }