This repository has been archived by the owner on Jul 14, 2022. It is now read-only.
forked from flow-hydraulics/flow-wallet-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
1653 lines (1449 loc) · 49.1 KB
/
main_test.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
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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"sort"
"net/http"
"net/http/httptest"
"path/filepath"
"reflect"
"regexp"
"strings"
"testing"
"time"
"github.com/flow-hydraulics/flow-wallet-api/accounts"
"github.com/flow-hydraulics/flow-wallet-api/flow_helpers"
"github.com/flow-hydraulics/flow-wallet-api/handlers"
"github.com/flow-hydraulics/flow-wallet-api/jobs"
"github.com/flow-hydraulics/flow-wallet-api/templates"
"github.com/flow-hydraulics/flow-wallet-api/tests/test"
"github.com/flow-hydraulics/flow-wallet-api/tokens"
"github.com/flow-hydraulics/flow-wallet-api/transactions"
"github.com/gorilla/mux"
"github.com/onflow/cadence"
"github.com/onflow/flow-go-sdk"
)
const testCadenceTxBasePath = "./flow/cadence/transactions"
type httpTestStep struct {
name string
method string
body io.Reader
contentType string
url string
expected string
status int
sync bool
}
func fatal(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
func handleStepRequest(s httpTestStep, r *mux.Router, t *testing.T) *httptest.ResponseRecorder {
req, err := http.NewRequest(s.method, s.url, s.body)
fatal(t, err)
if s.contentType != "" {
req.Header.Set("content-type", "application/json")
}
if s.sync {
q := req.URL.Query()
q.Add(handlers.SyncQueryParameter, "go-ahead")
req.URL.RawQuery = q.Encode()
}
rr := httptest.NewRecorder()
r.ServeHTTP(rr, req)
status := rr.Code
// Check the status code is what we expect.
if status != s.status {
t.Errorf("handler returned wrong status code: got %v want %v",
status, s.status)
}
// Check the response body is what we expect.
re := regexp.MustCompile(s.expected)
match := re.FindString(rr.Body.String())
if match == "" {
t.Errorf(`handler returned unexpected body: got "%s" want "%v"`, rr.Body.String(), re)
}
return rr
}
func TestAccountServices(t *testing.T) {
cfg := test.LoadConfig(t)
app := test.GetServices(t, cfg)
svc := app.GetAccounts()
km := app.GetKeyManager()
t.Run("admin init", func(t *testing.T) {
ctx := context.Background()
err := svc.InitAdminAccount(ctx)
fatal(t, err)
// make sure all requested proposal keys are created
if err := km.CheckAdminProposalKeyCount(context.Background()); err != nil {
t.Fatal(err)
}
})
t.Run("sync create", func(t *testing.T) {
_, account, err := svc.Create(context.Background(), true)
fatal(t, err)
if _, err := flow_helpers.ValidateAddress(account.Address, flow.Emulator); err != nil {
t.Errorf("Account has an invalid address: '%s'", account.Address)
}
})
t.Run("async create", func(t *testing.T) {
job, _, err := svc.Create(context.Background(), false)
fatal(t, err)
job, err = test.WaitForJob(app.GetJobs(), job.ID.String())
fatal(t, err)
account, err := svc.Details(job.Result)
fatal(t, err)
if _, err := flow_helpers.ValidateAddress(account.Address, flow.Emulator); err != nil {
t.Errorf("Account has an invalid address: '%s'", account.Address)
}
if len(account.Keys) == 0 {
t.Error("Account should expose public data on keys")
}
// All Value fields (containing a private key) should be empty
for _, k := range account.Keys {
if len(k.Value) != 0 {
t.Error("Account should not expose private key value")
}
}
})
t.Run("create with custom init script", func(t *testing.T) {
cfg2 := test.LoadConfig(t)
// Set custom script path
cfg2.ScriptPathCreateAccount = "./flow/cadence/transactions/custom_create_account.cdc"
app2 := test.GetServices(t, cfg2)
svc2 := app2.GetAccounts()
expected := "Account initialized with custom script"
// Use the new service to create an account
job, _, err := svc2.Create(context.Background(), false)
fatal(t, err)
if job, err := test.WaitForJob(app2.GetJobs(), job.ID.String()); err != nil {
if !strings.Contains(err.Error(), expected) {
t.Fatalf(`expected error to contain "%s" got: "%s"`, expected, err)
}
} else {
t.Fatalf("expected job to have errored got %s", job.State)
}
})
t.Run("sync create with multiple keys", func(t *testing.T) {
cfg2 := test.LoadConfig(t)
cfg2.DefaultAccountKeyCount = 3
app2 := test.GetServices(t, cfg2)
svc2 := app2.GetAccounts()
_, acc, err := svc2.Create(context.Background(), true)
fatal(t, err)
if len(acc.Keys) != int(cfg2.DefaultAccountKeyCount) {
t.Fatalf("incorrect number of keys for new account, expected %d, got %d", len(acc.Keys), cfg2.DefaultAccountKeyCount)
}
// Keys should be clones w/ a running Index
indexes := []int{}
for _, key := range acc.Keys {
indexes = append(indexes, key.Index)
// Check that all public keys are identical
if key.PublicKey != acc.Keys[0].PublicKey {
t.Fatalf("expected public keys to be identical")
}
}
sort.Ints(indexes)
expectedIndexes := []int{0, 1, 2}
if !reflect.DeepEqual(expectedIndexes, indexes) {
t.Fatalf("incorrect key indexes, expected %v, got %v", expectedIndexes, indexes)
}
})
t.Run("async create with multiple keys", func(t *testing.T) {
cfg2 := test.LoadConfig(t)
cfg2.DefaultAccountKeyCount = 3
app2 := test.GetServices(t, cfg2)
svc2 := app2.GetAccounts()
job, _, err := svc2.Create(context.Background(), false)
fatal(t, err)
job, err = test.WaitForJob(app2.GetJobs(), job.ID.String())
fatal(t, err)
acc, err := svc2.Details(job.Result)
fatal(t, err)
if len(acc.Keys) != int(cfg2.DefaultAccountKeyCount) {
t.Fatalf("incorrect number of keys for new account, expected %d, got %d", len(acc.Keys), cfg2.DefaultAccountKeyCount)
}
// Keys should be clones w/ a running Index
indexes := []int{}
for _, key := range acc.Keys {
indexes = append(indexes, key.Index)
// Check that all public keys are identical
if key.PublicKey != acc.Keys[0].PublicKey {
t.Fatalf("expected public keys to be identical")
}
}
sort.Ints(indexes)
expectedIndexes := []int{0, 1, 2}
if !reflect.DeepEqual(expectedIndexes, indexes) {
t.Fatalf("incorrect key indexes, expected %v, got %v", expectedIndexes, indexes)
}
})
}
func TestAccountHandlers(t *testing.T) {
cfg := test.LoadConfig(t)
app := test.GetServices(t, cfg)
svc := app.GetAccounts()
jobSvc := app.GetJobs()
handler := handlers.NewAccounts(svc)
t.Run("admin init", func(t *testing.T) {
err := svc.InitAdminAccount(context.Background())
fatal(t, err)
})
router := mux.NewRouter()
router.Handle("/", handler.List()).Methods(http.MethodGet)
router.Handle("/", handler.Create()).Methods(http.MethodPost)
router.Handle("/{address}", handler.Details()).Methods(http.MethodGet)
var tempAccAddress string
// NOTE: The order of the test "steps" matters
steps := []httpTestStep{
{
name: "list db empty",
method: http.MethodGet,
url: "/",
expected: fmt.Sprintf(`(?m)^\[{"address":"%s".*}\]$`, cfg.AdminAddress),
status: http.StatusOK,
},
{
name: "create",
method: http.MethodPost,
url: "/",
expected: `(?m)^{"jobId":".+"}$`,
status: http.StatusCreated,
},
{
name: "list db not empty",
method: http.MethodGet,
url: "/",
expected: `(?m)^\[{"address":".+".*}\]$`,
status: http.StatusOK,
},
{
name: "details invalid address",
method: http.MethodGet,
url: "/invalid-address",
expected: "not a valid address",
status: http.StatusBadRequest,
},
{
name: "details unknown address",
method: http.MethodGet,
url: "/e34ea67a850e1585",
expected: "record not found",
status: http.StatusNotFound,
},
{
name: "details known address",
method: http.MethodGet,
url: "/<address>",
expected: `(?m)^{"address":".+"}$`,
status: http.StatusOK,
},
}
for _, step := range steps {
t.Run(step.name, func(t *testing.T) {
replacer := strings.NewReplacer(
"<address>", tempAccAddress,
)
url := replacer.Replace(string(step.url))
req, err := http.NewRequest(step.method, url, nil)
fatal(t, err)
req.Context()
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
// Check the status code is what we expect.
if status := rr.Code; status != step.status {
t.Errorf("handler returned wrong status code: got %v want %v",
status, step.status)
}
// If this step was creating a new account
// wait for the account to become available
// and store the new account in "tempAcc".
if step.status == http.StatusCreated {
var rJob jobs.JSONResponse
json.Unmarshal(rr.Body.Bytes(), &rJob) // nolint
id := rJob.ID.String()
job, err := test.WaitForJob(jobSvc, id)
if err != nil {
t.Fatal(err)
}
tempAccAddress = job.Result
}
// Check the response body is what we expect.
re := regexp.MustCompile(step.expected)
match := re.FindString(rr.Body.String())
if match == "" {
t.Errorf("handler returned unexpected body: got %q want %v", rr.Body.String(), re)
}
})
}
}
func TestAccountTransactionHandlers(t *testing.T) {
cfg := test.LoadConfig(t)
app := test.GetServices(t, cfg)
svc := app.GetTransactions()
templateSvc := app.GetTemplates()
handler := handlers.NewTransactions(svc)
router := mux.NewRouter()
router.Handle("/{address}/sign", handler.Sign()).Methods(http.MethodPost)
router.Handle("/{address}/transactions", handler.List()).Methods(http.MethodGet)
router.Handle("/{address}/transactions", handler.Create()).Methods(http.MethodPost)
router.Handle("/{address}/transactions/{transactionId}", handler.Details()).Methods(http.MethodGet)
token, err := templateSvc.GetTokenByName("FlowToken")
fatal(t, err)
tFlow := templates.FungibleTransferCode(cfg.ChainID, token)
tFlowBytes, err := json.Marshal(tFlow)
fatal(t, err)
validTransferFlow := fmt.Sprintf(`{
"code":%s,
"arguments":[{"type":"UFix64","value":"1.0"},{"type":"Address","value":"%s"}]
}`, tFlowBytes, cfg.AdminAddress)
validHello := `{
"code":"transaction(greeting: String) { prepare(signer: AuthAccount){} execute { log(greeting.concat(\", World!\")) }}",
"arguments":[{"type":"String","value":"Hello"}]
}`
invalidHello := `{
"code":"this is not valid cadence code",
"arguments":[{"type":"String","value":"Hello"}]
}`
var tempTxId string
// NOTE: The order of the test "steps" matters
steps := []httpTestStep{
{
name: "list db empty",
method: http.MethodGet,
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: `(?m)^\[\]$`,
status: http.StatusOK,
},
{
name: "list db empty invalid address",
method: http.MethodGet,
url: "/invalid-address/transactions",
expected: "not a valid address",
status: http.StatusBadRequest,
},
{
name: "create ok async",
method: http.MethodPost,
contentType: "application/json",
body: strings.NewReader(validHello),
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: `(?m)^{"jobId":".+"}$`,
status: http.StatusCreated,
},
{
name: "create ok sync",
method: http.MethodPost,
contentType: "application/json",
body: strings.NewReader(validHello),
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: `(?m)^{"transactionId":".+"}$`,
status: http.StatusCreated,
sync: true,
},
{
name: "create invalid content-type",
method: http.MethodPost,
contentType: "",
body: strings.NewReader(validHello),
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: "Unsupported content type",
status: http.StatusUnsupportedMediaType,
sync: true,
},
{
name: "create ok sync requires authorizer",
method: http.MethodPost,
contentType: "application/json",
body: strings.NewReader(validTransferFlow),
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: `(?m)^{"transactionId":".+"}$`,
status: http.StatusCreated,
sync: true,
},
{
name: "create nil body sync",
method: http.MethodPost,
contentType: "application/json",
body: nil,
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: "empty body",
status: http.StatusBadRequest,
sync: true,
},
{
name: "create empty body sync",
method: http.MethodPost,
contentType: "application/json",
body: strings.NewReader(""),
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: "empty body",
status: http.StatusBadRequest,
sync: true,
},
{
name: "create invalid body sync",
method: http.MethodPost,
contentType: "application/json",
body: strings.NewReader("notvalidobject"),
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: "invalid body",
status: http.StatusBadRequest,
sync: true,
},
{
name: "create invalid code sync",
method: http.MethodPost,
contentType: "application/json",
body: strings.NewReader(invalidHello),
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: "Parsing failed",
status: http.StatusBadRequest,
sync: true,
},
{
name: "create invalid address sync",
method: http.MethodPost,
contentType: "application/json",
body: strings.NewReader(validHello),
url: "/invalid-address/transactions",
expected: "not a valid address",
status: http.StatusBadRequest,
sync: true,
},
{
name: "list db not empty",
method: http.MethodGet,
url: fmt.Sprintf("/%s/transactions", cfg.AdminAddress),
expected: `(?m)^\[{"transactionId":".+".*}\]$`,
status: http.StatusOK,
},
{
name: "details invalid id",
method: http.MethodGet,
url: fmt.Sprintf("/%s/transactions/invalid-id", cfg.AdminAddress),
expected: "not a valid transaction id",
status: http.StatusBadRequest,
},
{
name: "details unknown id",
method: http.MethodGet,
url: fmt.Sprintf("/%s/transactions/0e4f500d6965c7fc0ff1239525e09eb9dd27c00a511976e353d9f6a44ca22921", cfg.AdminAddress),
expected: "transaction not found",
status: http.StatusNotFound,
},
{
name: "details known id",
method: http.MethodGet,
url: fmt.Sprintf("/%s/transactions/<id>", cfg.AdminAddress),
expected: `(?m)^{"transactionId":".+"}$`,
status: http.StatusOK,
},
{
name: "details invalid address",
method: http.MethodGet,
url: "/invalid-address/transactions/invalid-id",
expected: "not a valid address",
status: http.StatusBadRequest,
},
{
name: "sign ok",
method: http.MethodPost,
contentType: "application/json",
body: strings.NewReader(validHello),
url: fmt.Sprintf("/%s/sign", cfg.AdminAddress),
expected: `(?m)^{"code":".*","arguments":\[.*\],"referenceBlockId":"(0x)?[0-9a-f]+","gasLimit":\d+,"proposalKey":{"address":"(0x)?[0-9a-f]+","keyIndex":\d+,"sequenceNumber":\d+},"payer":"(0x)?[0-9a-f]+","authorizers":\[(("[(0x)?[0-9a-f]+"),?)*\],"payloadSignatures":(null|\[({"address":"(0x)?[0-9a-f]+","keyIndex":\d+,"signature":"[0-9a-f]+"},?)*\]),"envelopeSignatures":\[({"address":"(0x)?[0-9a-f]+","keyIndex":\d+,"signature":"[0-9a-f]+"},?)*\]}$`,
status: http.StatusCreated,
sync: true,
},
}
for _, step := range steps {
t.Run(step.name, func(t *testing.T) {
replacer := strings.NewReplacer(
"<id>", tempTxId,
)
url := replacer.Replace(string(step.url))
req, err := http.NewRequest(step.method, url, step.body)
if err != nil {
t.Fatal(err)
}
if step.contentType != "" {
req.Header.Set("content-type", "application/json")
}
if step.sync {
q := req.URL.Query()
q.Add(handlers.SyncQueryParameter, "go-ahead")
req.URL.RawQuery = q.Encode()
}
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
status := rr.Code
// Check the status code is what we expect.
if status != step.status {
t.Errorf("handler returned wrong status code: got %v want %v",
status, step.status)
}
// If this step was creating a new transaction store the new txId in "tempTxId".
if step.sync && status == http.StatusCreated {
var transaction transactions.Transaction
json.Unmarshal(rr.Body.Bytes(), &transaction) // nolint
tempTxId = transaction.TransactionId
}
// Check the response body is what we expect.
re := regexp.MustCompile(step.expected)
match := re.FindString(rr.Body.String())
if match == "" {
t.Errorf("handler returned unexpected body: got %q want %v", rr.Body.String(), re)
}
})
}
}
func TestTransactionHandlers(t *testing.T) {
cfg := test.LoadConfig(t)
app := test.GetServices(t, cfg)
svc := app.GetTransactions()
templateSvc := app.GetTemplates()
handler := handlers.NewTransactions(svc)
router := mux.NewRouter()
router.Handle("/", handler.List()).Methods(http.MethodGet)
router.Handle("/{transactionId}", handler.Details()).Methods(http.MethodGet)
token, err := templateSvc.GetTokenByName("FlowToken")
fatal(t, err)
transferFlow := templates.FungibleTransferCode(cfg.ChainID, token)
_, transaction1, err := svc.Create(
context.Background(),
true,
cfg.AdminAddress,
"transaction() { prepare(signer: AuthAccount){} execute { log(\"Hello World!\") }}",
nil,
transactions.General,
)
fatal(t, err)
_, transaction2, err := svc.Create(
context.Background(),
true,
cfg.AdminAddress,
transferFlow,
[]transactions.Argument{
cadence.UFix64(1.0),
cadence.NewAddress(flow.HexToAddress(cfg.AdminAddress)),
},
transactions.General,
)
fatal(t, err)
// NOTE: The order of the test "steps" matters
steps := []httpTestStep{
{
name: "list db not empty",
method: http.MethodGet,
url: "/",
expected: `(?m)^\[{\"transactionId\":.*\]$`,
status: http.StatusOK,
},
{
name: "details invalid id",
method: http.MethodGet,
url: "/invalid-id",
expected: "not a valid transaction id",
status: http.StatusBadRequest,
},
{
name: "details unknown id",
method: http.MethodGet,
url: "/0e4f500d6965c7fc0ff1239525e09eb9dd27c00a511976e353d9f6a44ca22921",
expected: "transaction not found",
status: http.StatusNotFound,
},
{
name: "details",
method: http.MethodGet,
url: fmt.Sprintf("/%s", transaction1.TransactionId),
expected: `(?m)^{"transactionId":"\w+".*}$`,
status: http.StatusOK,
},
{
name: "details with events",
method: http.MethodGet,
url: fmt.Sprintf("/%s", transaction2.TransactionId),
expected: `(?m)^{"transactionId":"\w+".*"events":.*}$`,
status: http.StatusOK,
},
}
for _, step := range steps {
t.Run(step.name, func(t *testing.T) {
req, err := http.NewRequest(step.method, step.url, step.body)
if err != nil {
t.Fatal(err)
}
if step.contentType != "" {
req.Header.Set("content-type", "application/json")
}
if step.sync {
q := req.URL.Query()
q.Add(handlers.SyncQueryParameter, "go-ahead")
req.URL.RawQuery = q.Encode()
}
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
status := rr.Code
// Check the status code is what we expect.
if status != step.status {
t.Errorf("handler returned wrong status code: got %v want %v",
status, step.status)
}
// Check the response body is what we expect.
re := regexp.MustCompile(step.expected)
match := re.FindString(rr.Body.String())
if match == "" {
t.Errorf("handler returned unexpected body: got %q want %v", rr.Body.String(), re)
}
})
}
}
func TestScriptsHandlers(t *testing.T) {
cfg := test.LoadConfig(t)
app := test.GetServices(t, cfg)
svc := app.GetTransactions()
handler := handlers.NewTransactions(svc)
router := mux.NewRouter()
router.Handle("/", handler.ExecuteScript()).Methods(http.MethodPost)
steps := []httpTestStep{
{
name: "int 1",
method: http.MethodPost,
body: strings.NewReader(`{
"code":"pub fun main(): Int { return 1 }",
"arguments":[]
}`),
contentType: "application/json",
expected: `(?m)^{"Value":1}$`,
status: http.StatusOK,
},
{
name: "get supply",
method: http.MethodPost,
body: strings.NewReader(`{
"code":"import FlowToken from 0x0ae53cb6e3f42a79\npub fun main(): UFix64 {\nlet supply = FlowToken.totalSupply\nreturn supply\n}",
"arguments":[]
}`),
contentType: "application/json",
expected: "100000000000000000",
status: http.StatusOK,
},
{
name: "get balance",
method: http.MethodPost,
body: strings.NewReader(fmt.Sprintf(`{
"code":"import FungibleToken from 0xee82856bf20e2aa6\nimport FlowToken from 0x0ae53cb6e3f42a79\npub fun main(account: Address): UFix64 {\nlet vaultRef = getAccount(account)\n.getCapability(/public/flowTokenBalance)\n.borrow<&FlowToken.Vault{FungibleToken.Balance}>()\n?? panic(\"Could not borrow Balance reference to the Vault\")\nreturn vaultRef.balance\n}",
"arguments":[{"type":"Address","value":"%s"}]
}`, cfg.AdminAddress)),
contentType: "application/json",
expected: "\\d+",
status: http.StatusOK,
},
}
for _, step := range steps {
t.Run(step.name, func(t *testing.T) {
req, err := http.NewRequest(step.method, "/", step.body)
if err != nil {
t.Fatal(err)
}
if step.contentType != "" {
req.Header.Set("content-type", "application/json")
}
rr := httptest.NewRecorder()
router.ServeHTTP(rr, req)
status := rr.Code
// Check the status code is what we expect.
if status != step.status {
t.Errorf("handler returned wrong status code: got %v want %v",
status, step.status)
}
// Check the response body is what we expect.
re := regexp.MustCompile(step.expected)
match := re.FindString(rr.Body.String())
if match == "" {
t.Errorf("handler returned unexpected body: got %s want %v", rr.Body.String(), re)
}
})
}
}
func TestTokenServices(t *testing.T) {
cfg := test.LoadConfig(t)
app := test.GetServices(t, cfg)
svc := app.GetTokens()
accountSvc := app.GetAccounts()
t.Run("account can make a transaction", func(t *testing.T) {
// Create an account
_, account, err := accountSvc.Create(context.Background(), true)
fatal(t, err)
// Fund the account from service account
_, _, err = svc.CreateWithdrawal(
context.Background(),
true,
cfg.AdminAddress,
tokens.WithdrawalRequest{
TokenName: "FlowToken",
Recipient: account.Address,
FtAmount: "1.0",
},
)
fatal(t, err)
_, transfer, err := svc.CreateWithdrawal(
context.Background(),
true,
account.Address,
tokens.WithdrawalRequest{
TokenName: "FlowToken",
Recipient: cfg.AdminAddress,
FtAmount: "1.0",
},
)
fatal(t, err)
if flow.HexToID(transfer.TransactionId) == flow.EmptyID {
t.Fatalf("Expected TransactionId not to be empty")
}
})
t.Run("account can not make a transaction without funds", func(t *testing.T) {
// Create an account
_, account, err := accountSvc.Create(context.Background(), true)
fatal(t, err)
_, _, err = svc.CreateWithdrawal(
context.Background(),
true,
account.Address,
tokens.WithdrawalRequest{
TokenName: "FlowToken",
Recipient: cfg.AdminAddress,
FtAmount: "1.0",
},
)
if err == nil {
t.Fatal("Expected an error")
}
})
t.Run("manage fusd for an account", func(t *testing.T) {
tokenName := "FUSD"
ctx := context.Background()
// Make sure FUSD is deployed
err := svc.DeployTokenContractForAccount(ctx, true, tokenName, cfg.AdminAddress)
if err != nil {
if !strings.Contains(err.Error(), "cannot overwrite existing contract") {
t.Fatal(err)
}
}
// Setup the admin account to be able to handle FUSD
_, _, err = svc.Setup(ctx, true, tokenName, cfg.AdminAddress)
if err != nil {
if !strings.Contains(err.Error(), "vault exists") {
t.Fatal(err)
}
}
// Create an account
_, account, err := accountSvc.Create(ctx, true)
fatal(t, err)
// Setup the new account to be able to handle FUSD
_, setupTx, err := svc.Setup(ctx, true, tokenName, account.Address)
fatal(t, err)
if setupTx.TransactionType != transactions.FtSetup {
t.Errorf("expected %s but got %s", transactions.FtSetup, setupTx.TransactionType)
}
// Create a withdrawal, should error as we can not mint FUSD right now
_, _, err = svc.CreateWithdrawal(
ctx,
true,
cfg.AdminAddress,
tokens.WithdrawalRequest{
TokenName: tokenName,
Recipient: account.Address,
FtAmount: "1.0",
},
)
if err != nil {
if !strings.Contains(err.Error(), "Amount withdrawn must be less than or equal than the balance of the Vault") {
t.Fatal(err)
}
}
})
t.Run(("try to setup a non-existent token"), func(t *testing.T) {
tokenName := "some-non-existent-token"
ctx := context.Background()
// Create an account
_, account, err := accountSvc.Create(ctx, true)
fatal(t, err)
// Setup the new account to be able to handle the non-existent token
_, _, err = svc.Setup(ctx, true, tokenName, account.Address)
if err == nil {
t.Fatal("expected an error")
}
})
}
func TestTokenHandlers(t *testing.T) {
cfg := test.LoadConfig(t)
app := test.GetServices(t, cfg)
svc := app.GetTokens()
accountSvc := app.GetAccounts()
templateSvc := app.GetTemplates()
transactionSvc := app.GetTransactions()
handler := handlers.NewTokens(svc)
router := mux.NewRouter()
router.Handle("/{address}/fungible-tokens", handler.AccountTokens(templates.FT)).Methods(http.MethodGet)
router.Handle("/{address}/fungible-tokens/{tokenName}", handler.Setup()).Methods(http.MethodPost)
router.Handle("/{address}/fungible-tokens/{tokenName}", handler.Details()).Methods(http.MethodGet)
router.Handle("/{address}/fungible-tokens/{tokenName}/withdrawals", handler.CreateWithdrawal()).Methods(http.MethodPost)
router.Handle("/{address}/fungible-tokens/{tokenName}/withdrawals", handler.ListWithdrawals()).Methods(http.MethodGet)
router.Handle("/{address}/fungible-tokens/{tokenName}/withdrawals/{transactionId}", handler.GetWithdrawal()).Methods(http.MethodGet)
router.Handle("/{address}/fungible-tokens/{tokenName}/deposits", handler.ListDeposits()).Methods(http.MethodGet)
router.Handle("/{address}/fungible-tokens/{tokenName}/deposits/{transactionId}", handler.GetDeposit()).Methods(http.MethodGet)
router.Handle("/{address}/non-fungible-tokens", handler.AccountTokens(templates.NFT)).Methods(http.MethodGet)
router.Handle("/{address}/non-fungible-tokens/{tokenName}", handler.Setup()).Methods(http.MethodPost)
router.Handle("/{address}/non-fungible-tokens/{tokenName}", handler.Details()).Methods(http.MethodGet)
router.Handle("/{address}/non-fungible-tokens/{tokenName}/withdrawals", handler.CreateWithdrawal()).Methods(http.MethodPost)
router.Handle("/{address}/non-fungible-tokens/{tokenName}/withdrawals", handler.ListWithdrawals()).Methods(http.MethodGet)
router.Handle("/{address}/non-fungible-tokens/{tokenName}/withdrawals/{transactionId}", handler.GetWithdrawal()).Methods(http.MethodGet)
router.Handle("/{address}/non-fungible-tokens/{tokenName}/deposits", handler.ListDeposits()).Methods(http.MethodGet)
router.Handle("/{address}/non-fungible-tokens/{tokenName}/deposits/{transactionId}", handler.GetDeposit()).Methods(http.MethodGet)
// Setup
// FlowToken
flowToken, err := templateSvc.GetTokenByName("FlowToken")
fatal(t, err)
// FUSD
fusd, err := templateSvc.GetTokenByName("FUSD")
fatal(t, err)
// Make sure FUSD is deployed
err = svc.DeployTokenContractForAccount(context.Background(), true, fusd.Name, fusd.Address)
if err != nil {
if !strings.Contains(err.Error(), "cannot overwrite existing contract") {
fatal(t, err)
}
}
// ExampleNFT
setupBytes, err := ioutil.ReadFile(filepath.Join(testCadenceTxBasePath, "setup_exampleNFT.cdc"))
fatal(t, err)
transferBytes, err := ioutil.ReadFile(filepath.Join(testCadenceTxBasePath, "transfer_exampleNFT.cdc"))
fatal(t, err)
balanceBytes, err := ioutil.ReadFile(filepath.Join(testCadenceTxBasePath, "balance_exampleNFT.cdc"))
fatal(t, err)
mintBytes, err := ioutil.ReadFile(filepath.Join(testCadenceTxBasePath, "mint_exampleNFT.cdc"))
fatal(t, err)
exampleNft := templates.Token{
Name: "ExampleNFT",
Address: cfg.AdminAddress,
Type: templates.NFT,
Setup: string(setupBytes),
Transfer: string(transferBytes),
Balance: string(balanceBytes),
}
// Make sure ExampleNFT is enabled
err = templateSvc.AddToken(&exampleNft)
fatal(t, err)
// Make sure ExampleNFT is deployed