github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/account/accountnonce.go (about)

     1  // Copyright (c) 2019 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package account
     7  
     8  import (
     9  	"fmt"
    10  
    11  	"github.com/spf13/cobra"
    12  
    13  	"github.com/iotexproject/iotex-core/ioctl/config"
    14  	"github.com/iotexproject/iotex-core/ioctl/output"
    15  	"github.com/iotexproject/iotex-core/ioctl/util"
    16  )
    17  
    18  // Multi-language support
    19  var (
    20  	_nonceCmdShorts = map[config.Language]string{
    21  		config.English: "Get nonce of an account",
    22  		config.Chinese: "获取账户的nonce值",
    23  	}
    24  	_nonceCmdUses = map[config.Language]string{
    25  		config.English: "nonce [ALIAS|ADDRESS]",
    26  		config.Chinese: "nonce [别名|地址]",
    27  	}
    28  )
    29  
    30  // _accountNonceCmd represents the account nonce command
    31  var _accountNonceCmd = &cobra.Command{
    32  	Use:   config.TranslateInLang(_nonceCmdUses, config.UILanguage),
    33  	Short: config.TranslateInLang(_nonceCmdShorts, config.UILanguage),
    34  	Args:  cobra.RangeArgs(0, 1),
    35  	RunE: func(cmd *cobra.Command, args []string) error {
    36  		cmd.SilenceUsage = true
    37  		arg := ""
    38  		if len(args) == 1 {
    39  			arg = args[0]
    40  		}
    41  		err := nonce(arg)
    42  		return output.PrintError(err)
    43  	},
    44  }
    45  
    46  type nonceMessage struct {
    47  	Address      string `json:"address"`
    48  	PendingNonce int    `json:"pendingNonce"`
    49  }
    50  
    51  // nonce gets pending nonce of an IoTeX blockchain address
    52  func nonce(arg string) error {
    53  	addr, err := util.GetAddress(arg)
    54  	if err != nil {
    55  		return output.NewError(output.AddressError, "failed to get address", err)
    56  	}
    57  	accountMeta, err := GetAccountMeta(addr)
    58  	if err != nil {
    59  		return output.NewError(0, "", err)
    60  	}
    61  	message := nonceMessage{
    62  		Address:      addr,
    63  		PendingNonce: int(accountMeta.PendingNonce),
    64  	}
    65  	fmt.Println(message.String())
    66  	return nil
    67  }
    68  
    69  func (m *nonceMessage) String() string {
    70  	if output.Format == "" {
    71  		return fmt.Sprintf("%s:\nPending Nonce: %d",
    72  			m.Address, m.PendingNonce)
    73  	}
    74  	return output.FormatString(output.Result, m)
    75  }