github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/contract/contractinvokebytecode.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 contract
     7  
     8  import (
     9  	"math/big"
    10  
    11  	"github.com/spf13/cobra"
    12  
    13  	"github.com/iotexproject/iotex-core/ioctl/cmd/action"
    14  	"github.com/iotexproject/iotex-core/ioctl/config"
    15  	"github.com/iotexproject/iotex-core/ioctl/output"
    16  	"github.com/iotexproject/iotex-core/ioctl/util"
    17  )
    18  
    19  // Multi-language support
    20  var (
    21  	_invokeBytecodeCmdUses = map[config.Language]string{
    22  		config.English: "bytecode (CONTRACT_ADDRESS|ALIAS) PACKED_ARGUMENTS [AMOUNT_IOTX]",
    23  		config.Chinese: "bytecode (合约地址|别名) 已打包参数 [IOTX数量]",
    24  	}
    25  	_invokeBytecodeCmdShorts = map[config.Language]string{
    26  		config.English: "invoke smart contract on IoTex blockchain with packed arguments",
    27  		config.Chinese: "invoke 通过 已打包参数方式 调用IoTex区块链上的智能合约",
    28  	}
    29  )
    30  
    31  // _contractInvokeBytecodeCmd represents the contract invoke bytecode command
    32  var _contractInvokeBytecodeCmd = &cobra.Command{
    33  	Use:   config.TranslateInLang(_invokeBytecodeCmdUses, config.UILanguage),
    34  	Short: config.TranslateInLang(_invokeBytecodeCmdShorts, config.UILanguage),
    35  	Args:  cobra.RangeArgs(2, 3),
    36  	RunE: func(cmd *cobra.Command, args []string) error {
    37  		cmd.SilenceUsage = true
    38  		err := contractInvokeBytecode(args)
    39  		return output.PrintError(err)
    40  	},
    41  }
    42  
    43  func contractInvokeBytecode(args []string) error {
    44  	contract, err := util.Address(args[0])
    45  	if err != nil {
    46  		return output.NewError(output.AddressError, "failed to get contract address", err)
    47  	}
    48  
    49  	bytecode, err := decodeBytecode(args[1])
    50  	if err != nil {
    51  		return output.NewError(output.ConvertError, "invalid bytecode", err)
    52  	}
    53  
    54  	amount := big.NewInt(0)
    55  	if len(args) == 3 {
    56  		amount, err = util.StringToRau(args[2], util.IotxDecimalNum)
    57  		if err != nil {
    58  			return output.NewError(output.ConvertError, "invalid amount", err)
    59  		}
    60  	}
    61  
    62  	return action.Execute(contract, amount, bytecode)
    63  }