github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/newcmd/account/accountethaddr.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  
    11  	"github.com/ethereum/go-ethereum/common"
    12  	"github.com/iotexproject/iotex-address/address"
    13  	"github.com/pkg/errors"
    14  	"github.com/spf13/cobra"
    15  
    16  	"github.com/iotexproject/iotex-core/ioctl"
    17  	"github.com/iotexproject/iotex-core/ioctl/config"
    18  	"github.com/iotexproject/iotex-core/pkg/util/addrutil"
    19  )
    20  
    21  // Multi-language support
    22  var (
    23  	_ethaddrCmdShorts = map[config.Language]string{
    24  		config.English: "Translate address between IOTX and ETH",
    25  		config.Chinese: "在IOTX和ETH间转换地址",
    26  	}
    27  	_ethaddrCmdUses = map[config.Language]string{
    28  		config.English: "ethaddr (ALIAS|IOTEX_ADDRESS|ETH_ADDRESS)",
    29  		config.Chinese: "ethaddr (别名|IOTEX_地址|ETH_地址)",
    30  	}
    31  )
    32  
    33  // NewAccountEthAddr represents the account ethaddr command
    34  func NewAccountEthAddr(client ioctl.Client) *cobra.Command {
    35  	use, _ := client.SelectTranslation(_ethaddrCmdUses)
    36  	short, _ := client.SelectTranslation(_ethaddrCmdShorts)
    37  
    38  	return &cobra.Command{
    39  		Use:   use,
    40  		Short: short,
    41  		Args:  cobra.ExactArgs(1),
    42  		RunE: func(cmd *cobra.Command, args []string) error {
    43  			cmd.SilenceUsage = true
    44  			var ethAddress common.Address
    45  			ioAddr, err := client.Address(args[0])
    46  			if err != nil {
    47  				if ok := common.IsHexAddress(args[0]); !ok {
    48  					return errors.Wrap(err, "the input address is invalid")
    49  				}
    50  				ethAddress = common.HexToAddress(args[0])
    51  				var ioAddress address.Address
    52  				ioAddress, err = address.FromBytes(ethAddress.Bytes())
    53  				if err != nil {
    54  					return errors.Wrap(err, "failed to convert ETH address to IoTeX address")
    55  				}
    56  				ioAddr = ioAddress.String()
    57  			} else {
    58  				ethAddress, err = addrutil.IoAddrToEvmAddr(ioAddr)
    59  				if err != nil {
    60  					return err
    61  				}
    62  			}
    63  			cmd.Println(fmt.Sprintf("%s - %s", ioAddr, ethAddress.String()))
    64  			return nil
    65  		},
    66  	}
    67  }