-
Notifications
You must be signed in to change notification settings - Fork 0
/
tx.go
411 lines (335 loc) · 12.6 KB
/
tx.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package cli
import (
"bufio"
"fmt"
"os"
"strings"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/auth/client/utils"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/dev10/fantom-asset-management/x/assetmanagement/rand"
"github.com/prometheus/common/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/dev10/fantom-asset-management/x/assetmanagement/internal/types"
)
func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command {
txRootCmd := &cobra.Command{
Use: "token",
Short: "Asset Management transaction sub-commands",
DisableFlagParsing: false,
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
txRootCmd.AddCommand(client.PostCommands(
GetCmdIssueToken(cdc),
GetCmdMintCoins(cdc),
GetCmdBurnCoins(cdc),
GetCmdFreezeCoins(cdc),
GetCmdUnfreezeCoins(cdc),
)...)
return txRootCmd
}
func flagError2String(name string, err error) string {
return fmt.Sprintf("unable to find '%s' flag: %v", name, err)
}
func fetchStringFlag(cmd *cobra.Command, flagName string) string {
flag, err := cmd.Flags().GetString(flagName)
if err != nil {
panic(flagError2String(flagName, err))
}
return flag
}
func fetchInt64Flag(cmd *cobra.Command, flagName string) int64 {
flag, err := cmd.Flags().GetInt64(flagName)
if err != nil {
panic(flagError2String(flagName, err))
}
return flag
}
func fetchBoolFlag(cmd *cobra.Command, flagName string) bool {
flag, err := cmd.Flags().GetBool(flagName)
if err != nil {
panic(flagError2String(flagName, err))
}
return flag
}
func setupRequiredFlag(cmd *cobra.Command, name string) {
err := cmd.MarkFlagRequired(name)
if err != nil {
panic(fmt.Sprintf("failed to setup '%s' flag: %s", name, err))
}
}
func setupBoolFlag(cmd *cobra.Command, name string, shorthand string, value bool, usage string, required bool) {
cmd.Flags().BoolP(name, shorthand, value, usage)
if required {
setupRequiredFlag(cmd, name)
}
}
func setupStringFlag(cmd *cobra.Command, name string, shorthand string, value string, usage string, required bool) {
cmd.Flags().StringP(name, shorthand, value, usage)
if required {
setupRequiredFlag(cmd, name)
}
}
func setupInt64Flag(cmd *cobra.Command, name string, shorthand string, value int64, usage string, required bool) {
cmd.Flags().Int64P(name, shorthand, value, usage)
if required {
setupRequiredFlag(cmd, name)
}
}
func getAccountAddress(cliCtx client.CLIContext) sdk.AccAddress {
from := cliCtx.GetFromName()
address := cliCtx.GetFromAddress()
fmt.Printf("token account: %s / %v", from, address)
return address
}
// GetCmdIssueToken is the CLI command for sending a IssueToken transaction
func GetCmdIssueToken(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: `issue --token-name [name] --total-supply [amount]
--symbol [ABC] --mintable --from [account]`,
Short: "create a new asset",
// Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
cliCtx.BroadcastMode = flags.BroadcastBlock // wait in order to query later
txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))
address := getAccountAddress(cliCtx)
name := fetchStringFlag(cmd, "token-name")
originalSymbol := fetchStringFlag(cmd, "symbol")
symbol := strings.ToLower(rand.GenerateNewSymbol(originalSymbol))
totalSupply := fetchInt64Flag(cmd, "total-supply")
mintable := fetchBoolFlag(cmd, "mintable")
log.Debugf("token is mintable? %t", mintable)
msg := types.NewMsgIssueToken(address, name, symbol, originalSymbol, totalSupply, mintable)
err := msg.ValidateBasic()
if err != nil {
return err
}
response, result := GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
printIssuedSymbol(response, cliCtx)
return result
},
}
setupBoolFlag(cmd, "mintable", "", false, "is the new token mintable", false)
setupStringFlag(cmd, "token-name", "", "", "the name of the new token", true)
setupInt64Flag(cmd, "total-supply", "", -1,
"what is the total supply for the new token", true)
setupStringFlag(cmd, "symbol", "", "",
"what is the shorthand symbol, eg ABC, for the new token", true)
return cmd
}
func printIssuedSymbol(response *sdk.TxResponse, cliCtx context.CLIContext) {
if response != nil {
txHash := response.TxHash
tmTags := []string{fmt.Sprintf("tx.hash='%s'", txHash)}
txs, err := utils.QueryTxsByEvents(cliCtx, tmTags, 1, 1)
if err != nil {
log.Errorf("Failed to find new transaction for hash: %s because: %s", txHash, err)
} else if txs != nil {
if txs.Count == 0 || len(txs.Txs[0].Logs) == 0 {
log.Errorf("Failed to find new transaction for hash: %s", txHash)
} else {
log.Debugf("Found new transaction: %s", txs.Txs)
logResponse := txs.Txs[0].Logs[0]
if logResponse.Success == false {
log.Errorf("Transaction failed: %v", logResponse)
} else {
newSymbol := logResponse.Log
log.Infof("Symbol issued: %s", newSymbol)
}
}
}
} else {
log.Errorf("No response")
}
}
// GetCmdMintCoins is the CLI command for sending a MintCoins transaction
func GetCmdMintCoins(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: `mint --amount [amount] --symbol [ABC-123]`,
Short: "mint more coins for the specified token",
// Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))
// if err := cliCtx.EnsureAccountExists(); err != nil {
// return err
// }
address, symbol, amount := getCommonParameters(cliCtx, cmd)
msg := types.NewMsgMintCoins(amount, symbol, address)
err := msg.ValidateBasic()
if err != nil {
return err
}
// return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, msgs)
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
},
}
setupInt64Flag(cmd, "amount", "", -1,
"what is the total amount of coins to mint for the given token", true)
setupStringFlag(cmd, "symbol", "", "",
"what is the shorthand symbol, eg ABC-123, for the existing token", true)
return cmd
}
func getCommonParameters(cliCtx client.CLIContext, cmd *cobra.Command) (sdk.AccAddress, string, int64) {
// find given account
address := getAccountAddress(cliCtx)
symbol := fetchStringFlag(cmd, "symbol")
amount := fetchInt64Flag(cmd, "amount")
return address, symbol, amount
}
// GetCmdBurnCoins is the CLI command for sending a BurnCoins transaction
func GetCmdBurnCoins(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: `burn --amount [amount] --symbol [ABC-123] --from [account]`,
Short: "destroy the given amount of token/coins, reducing the total supply",
// Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))
address, symbol, amount := getCommonParameters(cliCtx, cmd)
msg := types.NewMsgBurnCoins(amount, symbol, address)
err := msg.ValidateBasic()
if err != nil {
return err
}
// return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, msgs)
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
},
}
setupInt64Flag(cmd, "amount", "", -1,
"what is the total amount of coins to burn for the given token", true)
setupStringFlag(cmd, "symbol", "", "",
"what is the shorthand symbol, eg ABC-123, for the existing token", true)
return cmd
}
// GetCmdFreezeCoins is the CLI command for sending a FreezeCoins transaction
func GetCmdFreezeCoins(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: `freeze --amount [amount] --symbol [ABC-123] --from [account]`,
Short: "move specified amount of token/coins into frozen status, preventing their sale",
// Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))
address, symbol, amount := getCommonParameters(cliCtx, cmd)
msg := types.NewMsgFreezeCoins(amount, symbol, address)
err := msg.ValidateBasic()
if err != nil {
return err
}
// return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, msgs)
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
},
}
setupInt64Flag(cmd, "amount", "", -1,
"what is the total amount of coins to freeze for the given token", true)
setupStringFlag(cmd, "symbol", "", "",
"what is the shorthand symbol, eg ABC-123, for the existing token", true)
return cmd
}
// GetCmdUnfreezeCoins is the CLI command for sending a FreezeCoins transaction
func GetCmdUnfreezeCoins(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: `unfreeze --amount [amount] --symbol [ABC-123] --from [account]`,
Short: "move specified amount of token into frozen status, preventing their sale",
// Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
txBldr := auth.NewTxBuilderFromCLI().WithTxEncoder(utils.GetTxEncoder(cdc))
address, symbol, amount := getCommonParameters(cliCtx, cmd)
msg := types.NewMsgUnfreezeCoins(amount, symbol, address)
err := msg.ValidateBasic()
if err != nil {
return err
}
// return utils.CompleteAndBroadcastTxCLI(txBldr, cliCtx, msgs)
return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
},
}
setupInt64Flag(cmd, "amount", "", -1,
"what is the total amount of coins to unfreeze for the given token", true)
setupStringFlag(cmd, "symbol", "", "",
"what is the shorthand symbol, eg ABC-123, for the existing token", true)
return cmd
}
// GenerateOrBroadcastMsgs creates a StdTx given a series of messages. If
// the provided context has generate-only enabled, the tx will only be printed
// to STDOUT in a fully offline manner. Otherwise, the tx will be signed and
// broadcast.
func GenerateOrBroadcastMsgs(cliCtx context.CLIContext, txBldr authtypes.TxBuilder, msgs []sdk.Msg) (*sdk.TxResponse, error) {
if cliCtx.GenerateOnly {
return nil, utils.PrintUnsignedStdTx(txBldr, cliCtx, msgs)
}
return CompleteAndBroadcastTxCLI(txBldr, cliCtx, msgs)
}
// CompleteAndBroadcastTxCLI implements a utility function that facilitates
// sending a series of messages in a signed transaction given a TxBuilder and a
// QueryContext. It ensures that the account exists, has a proper number and
// sequence set. In addition, it builds and signs a transaction with the
// supplied messages. Finally, it broadcasts the signed transaction to a node
// and returns the response and/or error
func CompleteAndBroadcastTxCLI(txBldr authtypes.TxBuilder, cliCtx context.CLIContext, msgs []sdk.Msg) (*sdk.TxResponse, error) {
txBldr, err := utils.PrepareTxBuilder(txBldr, cliCtx)
if err != nil {
return nil, err
}
fromName := cliCtx.GetFromName()
if txBldr.SimulateAndExecute() || cliCtx.Simulate {
txBldr, err = utils.EnrichWithGas(txBldr, cliCtx, msgs)
if err != nil {
return nil, err
}
gasEst := utils.GasEstimateResponse{GasEstimate: txBldr.Gas()}
_, _ = fmt.Fprintf(os.Stderr, "%s\n", gasEst.String())
}
if cliCtx.Simulate {
return nil, nil
}
if !cliCtx.SkipConfirm {
stdSignMsg, err := txBldr.BuildSignMsg(msgs)
if err != nil {
return nil, err
}
var json []byte
if viper.GetBool(flags.FlagIndentResponse) {
json, err = cliCtx.Codec.MarshalJSONIndent(stdSignMsg, "", " ")
if err != nil {
panic(err)
}
} else {
json = cliCtx.Codec.MustMarshalJSON(stdSignMsg)
}
_, _ = fmt.Fprintf(os.Stderr, "%s\n\n", json)
buf := bufio.NewReader(os.Stdin)
ok, err := input.GetConfirmation("confirm transaction before signing and broadcasting", buf)
if err != nil || !ok {
_, _ = fmt.Fprintf(os.Stderr, "%s\n", "cancelled transaction")
return nil, err
}
}
passphrase, err := keys.GetPassphrase(fromName)
if err != nil {
return nil, err
}
// build and sign the transaction
txBytes, err := txBldr.BuildAndSign(fromName, passphrase, msgs)
if err != nil {
return nil, err
}
// broadcast to a Tendermint node
res, err := cliCtx.BroadcastTx(txBytes)
if err != nil {
return nil, err
}
return &res, cliCtx.PrintOutput(res)
}