github.com/iotexproject/iotex-core@v1.14.1-rc1/ioctl/cmd/contract/contractinvokefunction.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/flag" 16 "github.com/iotexproject/iotex-core/ioctl/output" 17 "github.com/iotexproject/iotex-core/ioctl/util" 18 ) 19 20 // Multi-language support 21 var ( 22 _invokeFunctionCmdUses = map[config.Language]string{ 23 config.English: "function (CONTRACT_ADDRESS|ALIAS) ABI_PATH FUNCTION_NAME [AMOUNT_IOTX] " + 24 "[--with-arguments INVOKE_INPUT]", 25 config.Chinese: "function (合约地址|别名) ABI文件路径 函数名 [IOTX数量] [--with-arguments 调用输入]", 26 } 27 _invokeFunctionCmdShorts = map[config.Language]string{ 28 config.English: "invoke smart contract on IoTeX blockchain with function name", 29 config.Chinese: "invoke 通过 函数名方式 调用IoTeX区块链上的智能合约", 30 } 31 ) 32 33 // _contractInvokeFunctionCmd represents the contract invoke function command 34 var _contractInvokeFunctionCmd = &cobra.Command{ 35 Use: config.TranslateInLang(_invokeFunctionCmdUses, config.UILanguage), 36 Short: config.TranslateInLang(_invokeFunctionCmdShorts, config.UILanguage), 37 Args: util.CheckArgs(3, 4), 38 RunE: func(cmd *cobra.Command, args []string) error { 39 cmd.SilenceUsage = true 40 err := contractInvokeFunction(args) 41 return output.PrintError(err) 42 }, 43 } 44 45 func contractInvokeFunction(args []string) error { 46 contract, err := util.Address(args[0]) 47 if err != nil { 48 return output.NewError(output.AddressError, "failed to get contract address", err) 49 } 50 51 abi, err := readAbiFile(args[1]) 52 if err != nil { 53 return output.NewError(output.ReadFileError, "failed to read abi file "+args[1], err) 54 } 55 56 methodName := args[2] 57 58 amount := big.NewInt(0) 59 if len(args) == 4 { 60 amount, err = util.StringToRau(args[3], util.IotxDecimalNum) 61 if err != nil { 62 return output.NewError(output.ConvertError, "invalid amount", err) 63 } 64 } 65 66 bytecode, err := packArguments(abi, methodName, flag.WithArgumentsFlag.Value().(string)) 67 if err != nil { 68 return output.NewError(output.ConvertError, "failed to pack given arguments", err) 69 } 70 71 return action.Execute(contract, amount, bytecode) 72 }