summaryrefslogtreecommitdiff
path: root/cmd/goal/application.go
blob: 49a2ce9c581e2149fa350b32352a8169a6b7a85f (plain)
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
// Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package main

import (
	"bytes"
	"crypto/sha512"
	"encoding/base32"
	"encoding/base64"
	"encoding/binary"
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/spf13/cobra"

	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/data/abi"
	"github.com/algorand/go-algorand/data/basics"
	"github.com/algorand/go-algorand/data/transactions"
	"github.com/algorand/go-algorand/data/transactions/logic"
	"github.com/algorand/go-algorand/libgoal"
	"github.com/algorand/go-algorand/protocol"
)

var (
	appIdx     uint64
	appCreator string

	approvalProgFile string
	clearProgFile    string

	method     string
	methodArgs []string

	approvalProgRawFile string
	clearProgRawFile    string

	extraPages uint32

	onCompletion string

	localSchemaUints      uint64
	localSchemaByteSlices uint64

	globalSchemaUints      uint64
	globalSchemaByteSlices uint64

	// Cobra only has a slice helper for uint, not uint64, so we'll parse
	// uint64s from strings for now. 4bn transactions and using a 32-bit
	// platform seems not so far-fetched?
	foreignApps    []string
	foreignAssets  []string
	appStrAccounts []string

	appArgs          []string
	appInputFilename string

	fetchLocal  bool
	fetchGlobal bool
	guessFormat bool
)

func init() {
	appCmd.AddCommand(createAppCmd)
	appCmd.AddCommand(deleteAppCmd)
	appCmd.AddCommand(updateAppCmd)
	appCmd.AddCommand(callAppCmd)
	appCmd.AddCommand(optInAppCmd)
	appCmd.AddCommand(closeOutAppCmd)
	appCmd.AddCommand(clearAppCmd)
	appCmd.AddCommand(readStateAppCmd)
	appCmd.AddCommand(infoAppCmd)
	appCmd.AddCommand(methodAppCmd)

	appCmd.PersistentFlags().StringVarP(&walletName, "wallet", "w", "", "Set the wallet to be used for the selected operation")
	appCmd.PersistentFlags().StringArrayVar(&appArgs, "app-arg", nil, "Args to encode for application transactions (all will be encoded to a byte slice). For ints, use the form 'int:1234'. For raw bytes, use the form 'b64:A=='. For printable strings, use the form 'str:hello'. For addresses, use the form 'addr:XYZ...'.")
	appCmd.PersistentFlags().StringSliceVar(&foreignApps, "foreign-app", nil, "Indexes of other apps whose global state is read in this transaction")
	appCmd.PersistentFlags().StringSliceVar(&foreignAssets, "foreign-asset", nil, "Indexes of assets whose parameters are read in this transaction")
	appCmd.PersistentFlags().StringSliceVar(&appStrAccounts, "app-account", nil, "Accounts that may be accessed from application logic")
	appCmd.PersistentFlags().StringVarP(&appInputFilename, "app-input", "i", "", "JSON file containing encoded arguments and inputs (mutually exclusive with app-arg-b64 and app-account)")

	appCmd.PersistentFlags().StringVar(&approvalProgFile, "approval-prog", "", "(Uncompiled) TEAL assembly program filename for approving/rejecting transactions")
	appCmd.PersistentFlags().StringVar(&clearProgFile, "clear-prog", "", "(Uncompiled) TEAL assembly program filename for updating application state when a user clears their local state")

	appCmd.PersistentFlags().StringVar(&approvalProgRawFile, "approval-prog-raw", "", "Compiled TEAL program filename for approving/rejecting transactions")
	appCmd.PersistentFlags().StringVar(&clearProgRawFile, "clear-prog-raw", "", "Compiled TEAL program filename for updating application state when a user clears their local state")

	createAppCmd.Flags().Uint64Var(&globalSchemaUints, "global-ints", 0, "Maximum number of integer values that may be stored in the global key/value store. Immutable.")
	createAppCmd.Flags().Uint64Var(&globalSchemaByteSlices, "global-byteslices", 0, "Maximum number of byte slices that may be stored in the global key/value store. Immutable.")
	createAppCmd.Flags().Uint64Var(&localSchemaUints, "local-ints", 0, "Maximum number of integer values that may be stored in local (per-account) key/value stores for this app. Immutable.")
	createAppCmd.Flags().Uint64Var(&localSchemaByteSlices, "local-byteslices", 0, "Maximum number of byte slices that may be stored in local (per-account) key/value stores for this app. Immutable.")
	createAppCmd.Flags().StringVar(&appCreator, "creator", "", "Account to create the application")
	createAppCmd.Flags().StringVar(&onCompletion, "on-completion", "NoOp", "OnCompletion action for application transaction")
	createAppCmd.Flags().Uint32Var(&extraPages, "extra-pages", 0, "Additional program space for supporting larger TEAL assembly program. A maximum of 3 extra pages is allowed. A page is 1024 bytes.")

	callAppCmd.Flags().StringVarP(&account, "from", "f", "", "Account to call app from")
	optInAppCmd.Flags().StringVarP(&account, "from", "f", "", "Account to opt in")
	closeOutAppCmd.Flags().StringVarP(&account, "from", "f", "", "Account to opt out")
	clearAppCmd.Flags().StringVarP(&account, "from", "f", "", "Account to clear app state for")
	deleteAppCmd.Flags().StringVarP(&account, "from", "f", "", "Account to send delete transaction from")
	readStateAppCmd.Flags().StringVarP(&account, "from", "f", "", "Account to fetch state from")
	updateAppCmd.Flags().StringVarP(&account, "from", "f", "", "Account to send update transaction from")
	methodAppCmd.Flags().StringVarP(&account, "from", "f", "", "Account to call method from")

	methodAppCmd.Flags().StringVar(&method, "method", "", "Method to be called")
	methodAppCmd.Flags().StringArrayVar(&methodArgs, "arg", nil, "Args to pass in for calling a method")
	methodAppCmd.Flags().StringVar(&onCompletion, "on-completion", "NoOp", "OnCompletion action for application transaction")

	// Can't use PersistentFlags on the root because for some reason marking
	// a root command as required with MarkPersistentFlagRequired isn't
	// working
	callAppCmd.Flags().Uint64Var(&appIdx, "app-id", 0, "Application ID")
	optInAppCmd.Flags().Uint64Var(&appIdx, "app-id", 0, "Application ID")
	closeOutAppCmd.Flags().Uint64Var(&appIdx, "app-id", 0, "Application ID")
	clearAppCmd.Flags().Uint64Var(&appIdx, "app-id", 0, "Application ID")
	deleteAppCmd.Flags().Uint64Var(&appIdx, "app-id", 0, "Application ID")
	readStateAppCmd.Flags().Uint64Var(&appIdx, "app-id", 0, "Application ID")
	updateAppCmd.Flags().Uint64Var(&appIdx, "app-id", 0, "Application ID")
	infoAppCmd.Flags().Uint64Var(&appIdx, "app-id", 0, "Application ID")
	methodAppCmd.Flags().Uint64Var(&appIdx, "app-id", 0, "Application ID")

	// Add common transaction flags to all txn-generating app commands
	addTxnFlags(createAppCmd)
	addTxnFlags(deleteAppCmd)
	addTxnFlags(updateAppCmd)
	addTxnFlags(callAppCmd)
	addTxnFlags(optInAppCmd)
	addTxnFlags(closeOutAppCmd)
	addTxnFlags(clearAppCmd)
	addTxnFlags(methodAppCmd)

	readStateAppCmd.Flags().BoolVar(&fetchLocal, "local", false, "Fetch account-specific state for this application. `--from` address is required when using this flag")
	readStateAppCmd.Flags().BoolVar(&fetchGlobal, "global", false, "Fetch global state for this application.")
	readStateAppCmd.Flags().BoolVar(&guessFormat, "guess-format", false, "Format application state using heuristics to guess data encoding.")

	createAppCmd.MarkFlagRequired("creator")
	createAppCmd.MarkFlagRequired("global-ints")
	createAppCmd.MarkFlagRequired("global-byteslices")
	createAppCmd.MarkFlagRequired("local-ints")
	createAppCmd.MarkFlagRequired("local-byteslices")

	optInAppCmd.MarkFlagRequired("app-id")
	optInAppCmd.MarkFlagRequired("from")

	callAppCmd.MarkFlagRequired("app-id")
	callAppCmd.MarkFlagRequired("from")

	closeOutAppCmd.MarkFlagRequired("app-id")
	closeOutAppCmd.MarkFlagRequired("from")

	clearAppCmd.MarkFlagRequired("app-id")
	clearAppCmd.MarkFlagRequired("from")

	deleteAppCmd.MarkFlagRequired("app-id")
	deleteAppCmd.MarkFlagRequired("from")

	updateAppCmd.MarkFlagRequired("app-id")
	updateAppCmd.MarkFlagRequired("from")

	readStateAppCmd.MarkFlagRequired("app-id")

	infoAppCmd.MarkFlagRequired("app-id")

	methodAppCmd.MarkFlagRequired("method")    // nolint:errcheck // follow previous required flag format
	methodAppCmd.MarkFlagRequired("app-id")    // nolint:errcheck
	methodAppCmd.MarkFlagRequired("from")      // nolint:errcheck
	methodAppCmd.Flags().MarkHidden("app-arg") // nolint:errcheck
}

type appCallArg struct {
	Encoding string `codec:"encoding"`
	Value    string `codec:"value"`
}

type appCallInputs struct {
	Accounts      []string     `codec:"accounts"`
	ForeignApps   []uint64     `codec:"foreignapps"`
	ForeignAssets []uint64     `codec:"foreignassets"`
	Args          []appCallArg `codec:"args"`
}

func stringsToUint64(strs []string) []uint64 {
	out := make([]uint64, len(strs))
	for i, idstr := range strs {
		parsed, err := strconv.ParseUint(idstr, 10, 64)
		if err != nil {
			reportErrorf("Could not parse foreign app id: %v", err)
		}
		out[i] = parsed
	}
	return out
}

func getForeignAssets() []uint64 {
	return stringsToUint64(foreignAssets)
}

func getForeignApps() []uint64 {
	return stringsToUint64(foreignApps)
}

func parseAppArg(arg appCallArg) (rawValue []byte, parseErr error) {
	switch arg.Encoding {
	case "str", "string":
		rawValue = []byte(arg.Value)
	case "int", "integer":
		num, err := strconv.ParseUint(arg.Value, 10, 64)
		if err != nil {
			parseErr = fmt.Errorf("Could not parse uint64 from string (%s): %v", arg.Value, err)
			return
		}
		ibytes := make([]byte, 8)
		binary.BigEndian.PutUint64(ibytes, num)
		rawValue = ibytes
	case "addr", "address":
		addr, err := basics.UnmarshalChecksumAddress(arg.Value)
		if err != nil {
			parseErr = fmt.Errorf("Could not unmarshal checksummed address from string (%s): %v", arg.Value, err)
			return
		}
		rawValue = addr[:]
	case "b32", "base32", "byte base32":
		data, err := base32.StdEncoding.DecodeString(arg.Value)
		if err != nil {
			parseErr = fmt.Errorf("Could not decode base32-encoded string (%s): %v", arg.Value, err)
			return
		}
		rawValue = data
	case "b64", "base64", "byte base64":
		data, err := base64.StdEncoding.DecodeString(arg.Value)
		if err != nil {
			parseErr = fmt.Errorf("Could not decode base64-encoded string (%s): %v", arg.Value, err)
			return
		}
		rawValue = data
	case "abi":
		typeAndValue := strings.SplitN(arg.Value, ":", 2)
		if len(typeAndValue) != 2 {
			parseErr = fmt.Errorf("Could not decode abi string (%s): should split abi-type and abi-value with colon", arg.Value)
			return
		}
		abiType, err := abi.TypeOf(typeAndValue[0])
		if err != nil {
			parseErr = fmt.Errorf("Could not decode abi type string (%s): %v", typeAndValue[0], err)
			return
		}
		value, err := abiType.UnmarshalFromJSON([]byte(typeAndValue[1]))
		if err != nil {
			parseErr = fmt.Errorf("Could not decode abi value string (%s):%v ", typeAndValue[1], err)
			return
		}
		return abiType.Encode(value)
	default:
		parseErr = fmt.Errorf("Unknown encoding: %s", arg.Encoding)
	}
	return
}

func parseAppInputs(inputs appCallInputs) (args [][]byte, accounts []string, foreignApps []uint64, foreignAssets []uint64) {
	accounts = inputs.Accounts
	foreignApps = inputs.ForeignApps
	foreignAssets = inputs.ForeignAssets
	args = make([][]byte, len(inputs.Args))
	for i, arg := range inputs.Args {
		rawValue, err := parseAppArg(arg)
		if err != nil {
			reportErrorf("Could not decode input at index %d: %v", i, err)
		}
		args[i] = rawValue
	}
	return
}

func processAppInputFile() (args [][]byte, accounts []string, foreignApps []uint64, foreignAssets []uint64) {
	var inputs appCallInputs
	f, err := os.Open(appInputFilename)
	if err != nil {
		reportErrorf("Could not open app input JSON file: %v", err)
	}

	dec := protocol.NewJSONDecoder(f)
	err = dec.Decode(&inputs)
	if err != nil {
		reportErrorf("Could not decode app input JSON file: %v", err)
	}

	return parseAppInputs(inputs)
}

// filterEmptyStrings filters out empty string parsed in by StringArrayVar
// this function is added to support abi argument parsing
// since parsing of `appArg` diverted from `StringSliceVar` to `StringArrayVar`
func filterEmptyStrings(strSlice []string) []string {
	var newStrSlice []string

	for _, str := range strSlice {
		if len(str) > 0 {
			newStrSlice = append(newStrSlice, str)
		}
	}
	return newStrSlice
}

func getAppInputs() (args [][]byte, accounts []string, foreignApps []uint64, foreignAssets []uint64) {
	if (appArgs != nil || appStrAccounts != nil || foreignApps != nil) && appInputFilename != "" {
		reportErrorf("Cannot specify both command-line arguments/accounts and JSON input filename")
	}
	if appInputFilename != "" {
		return processAppInputFile()
	}

	var encodedArgs []appCallArg

	// we need to filter out empty strings from appArgs first, caused by change to `StringArrayVar`
	newAppArgs := filterEmptyStrings(appArgs)

	for _, arg := range newAppArgs {
		encodingValue := strings.SplitN(arg, ":", 2)
		if len(encodingValue) != 2 {
			reportErrorf("all arguments should be of the form 'encoding:value'")
		}
		encodedArg := appCallArg{
			Encoding: encodingValue[0],
			Value:    encodingValue[1],
		}
		encodedArgs = append(encodedArgs, encodedArg)
	}

	inputs := appCallInputs{
		Accounts:      appStrAccounts,
		ForeignApps:   getForeignApps(),
		ForeignAssets: getForeignAssets(),
		Args:          encodedArgs,
	}

	return parseAppInputs(inputs)
}

var appCmd = &cobra.Command{
	Use:   "app",
	Short: "Manage applications",
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, args []string) {
		// If no arguments passed, we should fallback to help
		cmd.HelpFunc()(cmd, args)
	},
}

func mustParseOnCompletion(ocString string) (oc transactions.OnCompletion) {
	switch strings.ToLower(ocString) {
	case "noop":
		return transactions.NoOpOC
	case "optin":
		return transactions.OptInOC
	case "closeout":
		return transactions.CloseOutOC
	case "clearstate":
		return transactions.ClearStateOC
	case "updateapplication":
		return transactions.UpdateApplicationOC
	case "deleteapplication":
		return transactions.DeleteApplicationOC
	default:
		reportErrorf("unknown value for --on-completion: %s (possible values: {NoOp, OptIn, CloseOut, ClearState, UpdateApplication, DeleteApplication})", ocString)
		return
	}
}

func getDataDirAndClient() (dataDir string, client libgoal.Client) {
	dataDir = ensureSingleDataDir()
	client = ensureFullClient(dataDir)
	return
}

func mustParseProgArgs() (approval []byte, clear []byte) {
	// Ensure we don't have ambiguous or all empty args
	if (approvalProgFile == "") == (approvalProgRawFile == "") {
		reportErrorf(errorApprovProgArgsRequired)
	}
	if (clearProgFile == "") == (clearProgRawFile == "") {
		reportErrorf(errorClearProgArgsRequired)
	}

	if approvalProgFile != "" {
		approval = assembleFile(approvalProgFile)
	} else {
		approval = mustReadFile(approvalProgRawFile)
	}

	if clearProgFile != "" {
		clear = assembleFile(clearProgFile)
	} else {
		clear = mustReadFile(clearProgRawFile)
	}

	return
}

var createAppCmd = &cobra.Command{
	Use:   "create",
	Short: "Create an application",
	Long:  `Issue a transaction that creates an application`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, _ []string) {
		dataDir, client := getDataDirAndClient()

		// Construct schemas from args
		localSchema := basics.StateSchema{
			NumUint:      localSchemaUints,
			NumByteSlice: localSchemaByteSlices,
		}

		globalSchema := basics.StateSchema{
			NumUint:      globalSchemaUints,
			NumByteSlice: globalSchemaByteSlices,
		}

		// Parse transaction parameters
		approvalProg, clearProg := mustParseProgArgs()
		onCompletionEnum := mustParseOnCompletion(onCompletion)
		appArgs, appAccounts, foreignApps, foreignAssets := getAppInputs()

		switch onCompletionEnum {
		case transactions.CloseOutOC, transactions.ClearStateOC:
			reportWarnf("'--on-completion %s' may be ill-formed for 'goal app create'", onCompletion)
		}

		tx, err := client.MakeUnsignedAppCreateTx(onCompletionEnum, approvalProg, clearProg, globalSchema, localSchema, appArgs, appAccounts, foreignApps, foreignAssets, extraPages)
		if err != nil {
			reportErrorf("Cannot create application txn: %v", err)
		}

		// Fill in note and lease
		tx.Note = parseNoteField(cmd)
		tx.Lease = parseLease(cmd)

		// Fill in rounds, fee, etc.
		fv, lv, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
		if err != nil {
			reportErrorf("Cannot determine last valid round: %s", err)
		}

		tx, err = client.FillUnsignedTxTemplate(appCreator, fv, lv, fee, tx)
		if err != nil {
			reportErrorf("Cannot construct transaction: %s", err)
		}
		explicitFee := cmd.Flags().Changed("fee")
		if explicitFee {
			tx.Fee = basics.MicroAlgos{Raw: fee}
		}

		if outFilename == "" {
			// Broadcast
			wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
			signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
			if err != nil {
				reportErrorf(errorSigningTX, err)
			}

			txid, err := client.BroadcastTransaction(signedTxn)
			if err != nil {
				reportErrorf(errorBroadcastingTX, err)
			}

			reportInfof("Attempting to create app (approval size %d, hash %v; clear size %d, hash %v)", len(approvalProg), crypto.HashObj(logic.Program(approvalProg)), len(clearProg), crypto.HashObj(logic.Program(clearProg)))
			reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)

			if !noWaitAfterSend {
				txn, err := waitForCommit(client, txid, lv)
				if err != nil {
					reportErrorf(err.Error())
				}
				if txn.TransactionResults != nil && txn.TransactionResults.CreatedAppIndex != 0 {
					reportInfof("Created app with app index %d", txn.TransactionResults.CreatedAppIndex)
				}
			}
		} else {
			if dumpForDryrun {
				err = writeDryrunReqToFile(client, tx, outFilename)
			} else {
				// Write transaction to file
				err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
			}
			if err != nil {
				reportErrorf(err.Error())
			}
		}
	},
}

var updateAppCmd = &cobra.Command{
	Use:   "update",
	Short: "Update an application's programs",
	Long:  `Issue a transaction that updates an application's ApprovalProgram and ClearStateProgram`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, _ []string) {
		dataDir, client := getDataDirAndClient()

		// Parse transaction parameters
		approvalProg, clearProg := mustParseProgArgs()
		appArgs, appAccounts, foreignApps, foreignAssets := getAppInputs()

		tx, err := client.MakeUnsignedAppUpdateTx(appIdx, appArgs, appAccounts, foreignApps, foreignAssets, approvalProg, clearProg)
		if err != nil {
			reportErrorf("Cannot create application txn: %v", err)
		}

		// Fill in note and lease
		tx.Note = parseNoteField(cmd)
		tx.Lease = parseLease(cmd)

		// Fill in rounds, fee, etc.
		fv, lv, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
		if err != nil {
			reportErrorf("Cannot determine last valid round: %s", err)
		}

		tx, err = client.FillUnsignedTxTemplate(account, fv, lv, fee, tx)
		if err != nil {
			reportErrorf("Cannot construct transaction: %s", err)
		}
		explicitFee := cmd.Flags().Changed("fee")
		if explicitFee {
			tx.Fee = basics.MicroAlgos{Raw: fee}
		}

		// Broadcast or write transaction to file
		if outFilename == "" {
			wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
			signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
			if err != nil {
				reportErrorf(errorSigningTX, err)
			}

			txid, err := client.BroadcastTransaction(signedTxn)
			if err != nil {
				reportErrorf(errorBroadcastingTX, err)
			}

			reportInfof("Attempting to update app (approval size %d, hash %v; clear size %d, hash %v)", len(approvalProg), crypto.HashObj(logic.Program(approvalProg)), len(clearProg), crypto.HashObj(logic.Program(clearProg)))
			reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)

			if !noWaitAfterSend {
				_, err = waitForCommit(client, txid, lv)
				if err != nil {
					reportErrorf(err.Error())
				}
			}
		} else {
			if dumpForDryrun {
				err = writeDryrunReqToFile(client, tx, outFilename)
			} else {
				err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
			}
			if err != nil {
				reportErrorf(err.Error())
			}
		}
	},
}

var optInAppCmd = &cobra.Command{
	Use:   "optin",
	Short: "Opt in to an application",
	Long:  `Opt an account in to an application, allocating local state in your account`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, _ []string) {
		dataDir, client := getDataDirAndClient()

		// Parse transaction parameters
		appArgs, appAccounts, foreignApps, foreignAssets := getAppInputs()

		tx, err := client.MakeUnsignedAppOptInTx(appIdx, appArgs, appAccounts, foreignApps, foreignAssets)
		if err != nil {
			reportErrorf("Cannot create application txn: %v", err)
		}

		// Fill in note and lease
		tx.Note = parseNoteField(cmd)
		tx.Lease = parseLease(cmd)

		// Fill in rounds, fee, etc.
		fv, lv, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
		if err != nil {
			reportErrorf("Cannot determine last valid round: %s", err)
		}

		tx, err = client.FillUnsignedTxTemplate(account, fv, lv, fee, tx)
		if err != nil {
			reportErrorf("Cannot construct transaction: %s", err)
		}
		explicitFee := cmd.Flags().Changed("fee")
		if explicitFee {
			tx.Fee = basics.MicroAlgos{Raw: fee}
		}

		// Broadcast or write transaction to file
		if outFilename == "" {
			wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
			signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
			if err != nil {
				reportErrorf(errorSigningTX, err)
			}

			txid, err := client.BroadcastTransaction(signedTxn)
			if err != nil {
				reportErrorf(errorBroadcastingTX, err)
			}

			// Report tx details to user
			reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)

			if !noWaitAfterSend {
				_, err = waitForCommit(client, txid, lv)
				if err != nil {
					reportErrorf(err.Error())
				}
			}
		} else {
			if dumpForDryrun {
				err = writeDryrunReqToFile(client, tx, outFilename)
			} else {
				err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
			}
			if err != nil {
				reportErrorf(err.Error())
			}
		}
	},
}

var closeOutAppCmd = &cobra.Command{
	Use:   "closeout",
	Short: "Close out of an application",
	Long:  `Close an account out of an application, removing local state from your account. The application must still exist. If it doesn't, use 'goal app clear'.`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, _ []string) {
		dataDir, client := getDataDirAndClient()

		// Parse transaction parameters
		appArgs, appAccounts, foreignApps, foreignAssets := getAppInputs()

		tx, err := client.MakeUnsignedAppCloseOutTx(appIdx, appArgs, appAccounts, foreignApps, foreignAssets)
		if err != nil {
			reportErrorf("Cannot create application txn: %v", err)
		}

		// Fill in note and lease
		tx.Note = parseNoteField(cmd)
		tx.Lease = parseLease(cmd)

		// Fill in rounds, fee, etc.
		fv, lv, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
		if err != nil {
			reportErrorf("Cannot determine last valid round: %s", err)
		}

		tx, err = client.FillUnsignedTxTemplate(account, fv, lv, fee, tx)
		if err != nil {
			reportErrorf("Cannot construct transaction: %s", err)
		}
		explicitFee := cmd.Flags().Changed("fee")
		if explicitFee {
			tx.Fee = basics.MicroAlgos{Raw: fee}
		}

		// Broadcast or write transaction to file
		if outFilename == "" {
			wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
			signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
			if err != nil {
				reportErrorf(errorSigningTX, err)
			}

			txid, err := client.BroadcastTransaction(signedTxn)
			if err != nil {
				reportErrorf(errorBroadcastingTX, err)
			}

			// Report tx details to user
			reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)

			if !noWaitAfterSend {
				_, err = waitForCommit(client, txid, lv)
				if err != nil {
					reportErrorf(err.Error())
				}
			}
		} else {
			if dumpForDryrun {
				err = writeDryrunReqToFile(client, tx, outFilename)
			} else {
				err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
			}
			if err != nil {
				reportErrorf(err.Error())
			}
		}
	},
}

var clearAppCmd = &cobra.Command{
	Use:   "clear",
	Short: "Clear out an application's state in your account",
	Long:  `Remove any local state from your account associated with an application. The application does not need to exist anymore.`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, _ []string) {
		dataDir, client := getDataDirAndClient()

		// Parse transaction parameters
		appArgs, appAccounts, foreignApps, foreignAssets := getAppInputs()

		tx, err := client.MakeUnsignedAppClearStateTx(appIdx, appArgs, appAccounts, foreignApps, foreignAssets)
		if err != nil {
			reportErrorf("Cannot create application txn: %v", err)
		}

		// Fill in note and lease
		tx.Note = parseNoteField(cmd)
		tx.Lease = parseLease(cmd)

		// Fill in rounds, fee, etc.
		fv, lv, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
		if err != nil {
			reportErrorf("Cannot determine last valid round: %s", err)
		}

		tx, err = client.FillUnsignedTxTemplate(account, fv, lv, fee, tx)
		if err != nil {
			reportErrorf("Cannot construct transaction: %s", err)
		}
		explicitFee := cmd.Flags().Changed("fee")
		if explicitFee {
			tx.Fee = basics.MicroAlgos{Raw: fee}
		}

		// Broadcast or write transaction to file
		if outFilename == "" {
			wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
			signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
			if err != nil {
				reportErrorf(errorSigningTX, err)
			}

			txid, err := client.BroadcastTransaction(signedTxn)
			if err != nil {
				reportErrorf(errorBroadcastingTX, err)
			}

			// Report tx details to user
			reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)

			if !noWaitAfterSend {
				_, err = waitForCommit(client, txid, lv)
				if err != nil {
					reportErrorf(err.Error())
				}
			}
		} else {
			if dumpForDryrun {
				err = writeDryrunReqToFile(client, tx, outFilename)
			} else {
				err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
			}
			if err != nil {
				reportErrorf(err.Error())
			}
		}
	},
}

var callAppCmd = &cobra.Command{
	Use:   "call",
	Short: "Call an application",
	Long:  `Call an application, invoking application-specific functionality`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, _ []string) {
		dataDir, client := getDataDirAndClient()

		// Parse transaction parameters
		appArgs, appAccounts, foreignApps, foreignAssets := getAppInputs()

		tx, err := client.MakeUnsignedAppNoOpTx(appIdx, appArgs, appAccounts, foreignApps, foreignAssets)
		if err != nil {
			reportErrorf("Cannot create application txn: %v", err)
		}

		// Fill in note and lease
		tx.Note = parseNoteField(cmd)
		tx.Lease = parseLease(cmd)

		// Fill in rounds, fee, etc.
		fv, lv, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
		if err != nil {
			reportErrorf("Cannot determine last valid round: %s", err)
		}

		tx, err = client.FillUnsignedTxTemplate(account, fv, lv, fee, tx)
		if err != nil {
			reportErrorf("Cannot construct transaction: %s", err)
		}
		explicitFee := cmd.Flags().Changed("fee")
		if explicitFee {
			tx.Fee = basics.MicroAlgos{Raw: fee}
		}

		// Broadcast or write transaction to file
		if outFilename == "" {
			wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
			signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
			if err != nil {
				reportErrorf(errorSigningTX, err)
			}

			txid, err := client.BroadcastTransaction(signedTxn)
			if err != nil {
				reportErrorf(errorBroadcastingTX, err)
			}

			// Report tx details to user
			reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)

			if !noWaitAfterSend {
				_, err = waitForCommit(client, txid, lv)
				if err != nil {
					reportErrorf(err.Error())
				}
			}
		} else {
			if dumpForDryrun {
				err = writeDryrunReqToFile(client, tx, outFilename)
			} else {
				err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)
			}
			if err != nil {
				reportErrorf(err.Error())
			}
		}
	},
}

var deleteAppCmd = &cobra.Command{
	Use:   "delete",
	Short: "Delete an application",
	Long:  `Delete an application, removing the global state and other application parameters from the creator's account`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, _ []string) {
		dataDir, client := getDataDirAndClient()

		// Parse transaction parameters
		appArgs, appAccounts, foreignApps, foreignAssets := getAppInputs()

		tx, err := client.MakeUnsignedAppDeleteTx(appIdx, appArgs, appAccounts, foreignApps, foreignAssets)
		if err != nil {
			reportErrorf("Cannot create application txn: %v", err)
		}

		// Fill in note and lease
		tx.Note = parseNoteField(cmd)
		tx.Lease = parseLease(cmd)

		// Fill in rounds, fee, etc.
		fv, lv, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
		if err != nil {
			reportErrorf("Cannot determine last valid round: %s", err)
		}

		tx, err = client.FillUnsignedTxTemplate(account, fv, lv, fee, tx)
		if err != nil {
			reportErrorf("Cannot construct transaction: %s", err)
		}
		explicitFee := cmd.Flags().Changed("fee")
		if explicitFee {
			tx.Fee = basics.MicroAlgos{Raw: fee}
		}

		// Broadcast or write transaction to file
		if outFilename == "" {
			wh, pw := ensureWalletHandleMaybePassword(dataDir, walletName, true)
			signedTxn, err := client.SignTransactionWithWallet(wh, pw, tx)
			if err != nil {
				reportErrorf(errorSigningTX, err)
			}

			txid, err := client.BroadcastTransaction(signedTxn)
			if err != nil {
				reportErrorf(errorBroadcastingTX, err)
			}

			// Report tx details to user
			reportInfof("Issued transaction from account %s, txid %s (fee %d)", tx.Sender, txid, tx.Fee.Raw)

			if !noWaitAfterSend {
				_, err = waitForCommit(client, txid, lv)
				if err != nil {
					reportErrorf(err.Error())
				}
			}
		} else {
			if dumpForDryrun {
				err = writeDryrunReqToFile(client, tx, outFilename)
			} else {
				err = writeTxnToFile(client, sign, dataDir, walletName, tx, outFilename)

			}
			if err != nil {
				reportErrorf(err.Error())
			}
		}
	},
}

var readStateAppCmd = &cobra.Command{
	Use:   "read",
	Short: "Read local or global state for an application",
	Long:  `Read global or local (account-specific) state for an application`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, _ []string) {
		_, client := getDataDirAndClient()

		// Ensure exactly one of --local or --global is specified
		if fetchLocal == fetchGlobal {
			reportErrorf(errorLocalGlobal)
		}

		// If fetching local state, ensure account is specified
		if fetchLocal && account == "" {
			reportErrorf(errorLocalStateRequiresAccount)
		}

		if fetchLocal {
			// Fetching local state. Get account information
			ad, err := client.AccountData(account)
			if err != nil {
				reportErrorf(errorRequestFail, err)
			}

			// Get application local state
			local, ok := ad.AppLocalStates[basics.AppIndex(appIdx)]
			if !ok {
				reportErrorf(errorAccountNotOptedInToApp, account, appIdx)
			}

			kv := local.KeyValue
			if guessFormat {
				kv = heuristicFormat(kv)
			}

			// Encode local state to json, print, and exit
			enc := protocol.EncodeJSON(kv)

			// Print to stdout
			os.Stdout.Write(enc)
			return
		}

		if fetchGlobal {
			// Fetching global state. Get application creator
			app, err := client.ApplicationInformation(appIdx)
			if err != nil {
				reportErrorf(errorRequestFail, err)
			}

			// Get creator information
			ad, err := client.AccountData(app.Params.Creator)
			if err != nil {
				reportErrorf(errorRequestFail, err)
			}

			// Get app params
			params, ok := ad.AppParams[basics.AppIndex(appIdx)]
			if !ok {
				reportErrorf(errorNoSuchApplication, appIdx)
			}

			kv := params.GlobalState
			if guessFormat {
				kv = heuristicFormat(kv)
			}

			// Encode global state to json, print, and exit
			enc := protocol.EncodeJSON(kv)

			// Print to stdout
			os.Stdout.Write(enc)
			return
		}

		// Should be unreachable
		return
	},
}

var infoAppCmd = &cobra.Command{
	Use:   "info",
	Short: "Look up current parameters for an application",
	Long:  `Look up application information stored on the network, such as program hash.`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, _ []string) {
		_, client := getDataDirAndClient()

		meta, err := client.ApplicationInformation(appIdx)
		if err != nil {
			reportErrorf(errorRequestFail, err)
		}
		params := meta.Params

		gsch := params.GlobalStateSchema
		lsch := params.LocalStateSchema
		epp := params.ExtraProgramPages

		fmt.Printf("Application ID:        %d\n", appIdx)
		fmt.Printf("Application account:   %v\n", basics.AppIndex(appIdx).Address())
		fmt.Printf("Creator:               %v\n", params.Creator)
		fmt.Printf("Approval hash:         %v\n", basics.Address(logic.HashProgram(params.ApprovalProgram)))
		fmt.Printf("Clear hash:            %v\n", basics.Address(logic.HashProgram(params.ClearStateProgram)))

		if epp != nil {
			fmt.Printf("Extra program pages:   %d\n", *epp)
		}

		if gsch != nil {
			fmt.Printf("Max global byteslices: %d\n", gsch.NumByteSlice)
			fmt.Printf("Max global integers:   %d\n", gsch.NumUint)
		}

		if lsch != nil {
			fmt.Printf("Max local byteslices:  %d\n", lsch.NumByteSlice)
			fmt.Printf("Max local integers:    %d\n", lsch.NumUint)
		}
	},
}

// populateMethodCallTxnArgs parses and loads transactions from the files indicated by the values
// slice. An error will occur if the transaction does not matched the expected type, it has a nonzero
// group ID, or if it is signed by a normal signature or Msig signature (but not Lsig signature)
func populateMethodCallTxnArgs(types []string, values []string) ([]transactions.SignedTxn, error) {
	loadedTxns := make([]transactions.SignedTxn, len(values))

	for i, txFilename := range values {
		data, err := readFile(txFilename)
		if err != nil {
			return nil, fmt.Errorf(fileReadError, txFilename, err)
		}

		var txn transactions.SignedTxn
		err = protocol.Decode(data, &txn)
		if err != nil {
			return nil, fmt.Errorf(txDecodeError, txFilename, err)
		}

		if !txn.Sig.Blank() || !txn.Msig.Blank() {
			return nil, fmt.Errorf("Transaction from %s has already been signed", txFilename)
		}

		if !txn.Txn.Group.IsZero() {
			return nil, fmt.Errorf("Transaction from %s already has a group ID: %s", txFilename, txn.Txn.Group)
		}

		expectedType := types[i]
		if expectedType != "txn" && txn.Txn.Type != protocol.TxType(expectedType) {
			return nil, fmt.Errorf("Transaction from %s does not match method argument type. Expected %s, got %s", txFilename, expectedType, txn.Txn.Type)
		}

		loadedTxns[i] = txn
	}

	return loadedTxns, nil
}

var methodAppCmd = &cobra.Command{
	Use:   "method",
	Short: "Invoke a method",
	Long:  `Invoke a method in an App (stateful contract) with an application call transaction`,
	Args:  validateNoPosArgsFn,
	Run: func(cmd *cobra.Command, args []string) {
		dataDir, client := getDataDirAndClient()

		// Parse transaction parameters
		appArgsParsed, appAccounts, foreignApps, foreignAssets := getAppInputs()
		if len(appArgsParsed) > 0 {
			reportErrorf("in goal app method: --arg and --app-arg are mutually exclusive, do not use --app-arg")
		}

		onCompletionEnum := mustParseOnCompletion(onCompletion)

		if appIdx == 0 {
			reportErrorf("app id == 0, goal app create not supported in goal app method")
		}

		var approvalProg, clearProg []byte
		if onCompletionEnum == transactions.UpdateApplicationOC {
			approvalProg, clearProg = mustParseProgArgs()
		}

		var applicationArgs [][]byte

		// insert the method selector hash
		hash := sha512.Sum512_256([]byte(method))
		applicationArgs = append(applicationArgs, hash[0:4])

		// parse down the ABI type from method signature
		_, argTypes, retTypeStr, err := abi.ParseMethodSignature(method)
		if err != nil {
			reportErrorf("cannot parse method signature: %v", err)
		}

		var retType *abi.Type
		if retTypeStr != "void" {
			theRetType, err := abi.TypeOf(retTypeStr)
			if err != nil {
				reportErrorf("cannot cast %s to abi type: %v", retTypeStr, err)
			}
			retType = &theRetType
		}

		if len(methodArgs) != len(argTypes) {
			reportErrorf("incorrect number of arguments, method expected %d but got %d", len(argTypes), len(methodArgs))
		}

		var txnArgTypes []string
		var txnArgValues []string
		var basicArgTypes []string
		var basicArgValues []string
		for i, argType := range argTypes {
			argValue := methodArgs[i]
			if abi.IsTransactionType(argType) {
				txnArgTypes = append(txnArgTypes, argType)
				txnArgValues = append(txnArgValues, argValue)
			} else {
				basicArgTypes = append(basicArgTypes, argType)
				basicArgValues = append(basicArgValues, argValue)
			}
		}

		err = abi.ParseArgJSONtoByteSlice(basicArgTypes, basicArgValues, &applicationArgs)
		if err != nil {
			reportErrorf("cannot parse arguments to ABI encoding: %v", err)
		}

		txnArgs, err := populateMethodCallTxnArgs(txnArgTypes, txnArgValues)
		if err != nil {
			reportErrorf("error populating transaction arguments: %v", err)
		}

		appCallTxn, err := client.MakeUnsignedApplicationCallTx(
			appIdx, applicationArgs, appAccounts, foreignApps, foreignAssets,
			onCompletionEnum, approvalProg, clearProg, basics.StateSchema{}, basics.StateSchema{}, 0)

		if err != nil {
			reportErrorf("Cannot create application txn: %v", err)
		}

		// Fill in note and lease
		appCallTxn.Note = parseNoteField(cmd)
		appCallTxn.Lease = parseLease(cmd)

		// Fill in rounds, fee, etc.
		fv, lv, err := client.ComputeValidityRounds(firstValid, lastValid, numValidRounds)
		if err != nil {
			reportErrorf("Cannot determine last valid round: %s", err)
		}

		appCallTxn, err = client.FillUnsignedTxTemplate(account, fv, lv, fee, appCallTxn)
		if err != nil {
			reportErrorf("Cannot construct transaction: %s", err)
		}
		explicitFee := cmd.Flags().Changed("fee")
		if explicitFee {
			appCallTxn.Fee = basics.MicroAlgos{Raw: fee}
		}

		// Compile group
		var txnGroup []transactions.Transaction
		for i := range txnArgs {
			txnGroup = append(txnGroup, txnArgs[i].Txn)
		}
		txnGroup = append(txnGroup, appCallTxn)
		if len(txnGroup) > 1 {
			// Only if transaction arguments are present, assign group ID
			groupID, err := client.GroupID(txnGroup)
			if err != nil {
				reportErrorf("Cannot assign transaction group ID: %s", err)
			}
			for i := range txnGroup {
				txnGroup[i].Group = groupID
			}
		}

		// Sign transactions
		var signedTxnGroup []transactions.SignedTxn
		shouldSign := sign || outFilename == ""
		for i, unsignedTxn := range txnGroup {
			txnFromArgs := transactions.SignedTxn{}
			if i < len(txnArgs) {
				txnFromArgs = txnArgs[i]
			}

			if !txnFromArgs.Lsig.Blank() {
				signedTxnGroup = append(signedTxnGroup, transactions.SignedTxn{
					Lsig:     txnFromArgs.Lsig,
					AuthAddr: txnFromArgs.AuthAddr,
					Txn:      unsignedTxn,
				})
				continue
			}

			signedTxn, err := createSignedTransaction(client, shouldSign, dataDir, walletName, unsignedTxn, txnFromArgs.AuthAddr)
			if err != nil {
				reportErrorf(errorSigningTX, err)
			}

			signedTxnGroup = append(signedTxnGroup, signedTxn)
		}

		// Output to file
		if outFilename != "" {
			if dumpForDryrun {
				err = writeDryrunReqToFile(client, signedTxnGroup, outFilename)
			} else {
				err = writeSignedTxnsToFile(signedTxnGroup, outFilename)
			}
			if err != nil {
				reportErrorf(err.Error())
			}
			return
		}

		// Broadcast
		err = client.BroadcastTransactionGroup(signedTxnGroup)
		if err != nil {
			reportErrorf(errorBroadcastingTX, err)
		}

		// Report tx details to user
		reportInfof("Issued %d transaction(s):", len(signedTxnGroup))
		// remember the final txid in this variable
		var txid string
		for _, stxn := range signedTxnGroup {
			txid = stxn.Txn.ID().String()
			reportInfof("\tIssued transaction from account %s, txid %s (fee %d)", stxn.Txn.Sender, txid, stxn.Txn.Fee.Raw)
		}

		if !noWaitAfterSend {
			_, err := waitForCommit(client, txid, lv)
			if err != nil {
				reportErrorf(err.Error())
			}

			resp, err := client.PendingTransactionInformationV2(txid)
			if err != nil {
				reportErrorf(err.Error())
			}

			if retType == nil {
				fmt.Printf("method %s succeeded\n", method)
				return
			}

			// specify the return hash prefix
			hashRet := sha512.Sum512_256([]byte("return"))
			hashRetPrefix := hashRet[:4]

			var abiEncodedRet []byte
			foundRet := false
			if resp.Logs != nil {
				for i := len(*resp.Logs) - 1; i >= 0; i-- {
					retLog := (*resp.Logs)[i]
					if bytes.HasPrefix(retLog, hashRetPrefix) {
						abiEncodedRet = retLog[4:]
						foundRet = true
						break
					}
				}
			}

			if !foundRet {
				reportErrorf("cannot find return log for abi type %s", retTypeStr)
			}

			decoded, err := retType.Decode(abiEncodedRet)
			if err != nil {
				reportErrorf("cannot decode return value %v: %v", abiEncodedRet, err)
			}

			decodedJSON, err := retType.MarshalToJSON(decoded)
			if err != nil {
				reportErrorf("cannot marshal returned bytes %v to JSON: %v", decoded, err)
			}
			fmt.Printf("method %s succeeded with output: %s\n", method, string(decodedJSON))
		}
	},
}