/
invoke.go
102 lines (78 loc) · 2.26 KB
/
invoke.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
Copyright State Street Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package chaincode
import (
"errors"
"fmt"
"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
"github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry"
"github.com/spf13/cobra"
"github.com/hyperledger/fabric-cli/cmd/commands/common"
"github.com/hyperledger/fabric-cli/pkg/environment"
)
// NewChaincodeInvokeCommand creates a new "fabric chaincode invoke" command
func NewChaincodeInvokeCommand(settings *environment.Settings) *cobra.Command {
c := InvokeCommand{}
c.Settings = settings
cmd := &cobra.Command{
Use: "invoke <chaincode-name>",
Short: "Invoke a chaincode",
Long: "Invoke a chaincode with chaincode-name args function",
Args: c.ParseArgs(),
PreRunE: func(_ *cobra.Command, _ []string) error {
if err := c.Complete(); err != nil {
return err
}
if err := c.Validate(); err != nil {
return err
}
return nil
},
RunE: func(_ *cobra.Command, _ []string) error {
return c.Run()
},
}
c.AddArg(&c.ChaincodeName)
flags := cmd.Flags()
flags.StringVar(&c.ChaincodeFcn, "fcn", "", "set the invoke function")
flags.StringArrayVar(&c.ChaincodeArgs, "args", []string{}, "set the invoke arguments")
flags.BoolVar(&c.IsInit, "is-init", false, "indicates whether or not this invocation is meant to initialize the chaincode")
cmd.SetOutput(c.Settings.Streams.Out)
return cmd
}
// InvokeCommand implements the chaincode invoke command
type InvokeCommand struct {
BaseCommand
ChaincodeName string
ChaincodeFcn string
ChaincodeArgs []string
IsInit bool
}
// Validate checks the required parameters for run
func (c *InvokeCommand) Validate() error {
if len(c.ChaincodeName) == 0 {
return errors.New("chaincode name not specified")
}
return nil
}
// Run executes the command
func (c *InvokeCommand) Run() error {
fcn := c.ChaincodeFcn
if c.IsInit {
fcn = "Init"
}
req := channel.Request{
ChaincodeID: c.ChaincodeName,
Fcn: fcn,
Args: common.AsByteArgs(c.ChaincodeArgs),
IsInit: c.IsInit,
}
resp, err := c.Channel.Execute(req, channel.WithRetry(retry.DefaultChannelOpts))
if err != nil {
return err
}
fmt.Fprintln(c.Settings.Streams.Out, string(resp.Payload))
return nil
}