github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/account/accountethaddr.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/ethereum/go-ethereum/common" 12 "github.com/iotexproject/iotex-address/address" 13 "github.com/spf13/cobra" 14 15 "github.com/iotexproject/iotex-core/ioctl/config" 16 "github.com/iotexproject/iotex-core/ioctl/output" 17 "github.com/iotexproject/iotex-core/ioctl/util" 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 // _accountEthaddrCmd represents the account ethaddr command 34 var _accountEthaddrCmd = &cobra.Command{ 35 Use: config.TranslateInLang(_ethaddrCmdUses, config.UILanguage), 36 Short: config.TranslateInLang(_ethaddrCmdShorts, config.UILanguage), 37 Args: cobra.ExactArgs(1), 38 RunE: func(cmd *cobra.Command, args []string) error { 39 cmd.SilenceUsage = true 40 err := accountEthaddr(args[0]) 41 return output.PrintError(err) 42 }, 43 } 44 45 type ethaddrMessage struct { 46 IOAddr string `json:"ioAddr"` 47 EthAddr string `json:"ethAddr"` 48 } 49 50 func accountEthaddr(arg string) error { 51 var ethAddress common.Address 52 ioAddr, err := util.Address(arg) 53 if err != nil { 54 if ok := common.IsHexAddress(arg); !ok { 55 return output.NewError(output.AddressError, "", err) 56 } 57 ethAddress = common.HexToAddress(arg) 58 ioAddress, err := address.FromBytes(ethAddress.Bytes()) 59 if err != nil { 60 return output.NewError(output.AddressError, "failed to form IoTeX address from ETH address", nil) 61 } 62 ioAddr = ioAddress.String() 63 } else { 64 ethAddress, err = addrutil.IoAddrToEvmAddr(ioAddr) 65 if err != nil { 66 return output.NewError(output.AddressError, "", err) 67 } 68 } 69 message := ethaddrMessage{IOAddr: ioAddr, EthAddr: ethAddress.String()} 70 fmt.Println(message.String()) 71 return nil 72 } 73 74 func (m *ethaddrMessage) String() string { 75 if output.Format == "" { 76 return fmt.Sprintf("%s - %s", m.IOAddr, m.EthAddr) 77 } 78 return output.FormatString(output.Result, m) 79 }