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

     1  // Copyright (c) 2022 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  	"math/big"
    11  
    12  	"github.com/pkg/errors"
    13  	"github.com/spf13/cobra"
    14  
    15  	ioAddress "github.com/iotexproject/iotex-address/address"
    16  	"github.com/iotexproject/iotex-core/ioctl"
    17  	"github.com/iotexproject/iotex-core/ioctl/config"
    18  	"github.com/iotexproject/iotex-core/ioctl/util"
    19  )
    20  
    21  // Multi-language support
    22  var (
    23  	_balanceCmdUses = map[config.Language]string{
    24  		config.English: "balance [ALIAS|ADDRESS]",
    25  		config.Chinese: "balance [别名|地址]",
    26  	}
    27  	_balanceCmdShorts = map[config.Language]string{
    28  		config.English: "Get balance of an account",
    29  		config.Chinese: "查询账号余额",
    30  	}
    31  )
    32  
    33  // NewAccountBalance represents the account balance command
    34  func NewAccountBalance(client ioctl.Client) *cobra.Command {
    35  	use, _ := client.SelectTranslation(_balanceCmdUses)
    36  	short, _ := client.SelectTranslation(_balanceCmdShorts)
    37  
    38  	return &cobra.Command{
    39  		Use:   use,
    40  		Short: short,
    41  		Args:  cobra.RangeArgs(0, 1),
    42  		RunE: func(cmd *cobra.Command, args []string) error {
    43  			cmd.SilenceUsage = true
    44  			addr := ""
    45  			if len(args) == 1 {
    46  				addr = args[0]
    47  			}
    48  			if addr != ioAddress.StakingBucketPoolAddr && addr != ioAddress.RewardingPoolAddr {
    49  				var err error
    50  				addr, err = client.AddressWithDefaultIfNotExist(addr)
    51  				if err != nil {
    52  					return errors.Wrap(err, "failed to get address")
    53  				}
    54  			}
    55  
    56  			accountMeta, err := Meta(client, addr)
    57  			if err != nil {
    58  				return errors.Wrap(err, "failed to get account meta")
    59  			}
    60  			balance, ok := new(big.Int).SetString(accountMeta.Balance, 10)
    61  			if !ok {
    62  				return errors.Wrap(err, "failed to convert account balance")
    63  			}
    64  			cmd.Println(fmt.Sprintf("%s: %s IOTX", addr, util.RauToString(balance, util.IotxDecimalNum)))
    65  			return nil
    66  		},
    67  	}
    68  }