forked from onflow/flow-playground-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresolver.go
752 lines (592 loc) · 19.2 KB
/
resolver.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
/*
* Flow Playground
*
* Copyright 2019-2021 Dapper Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package playground
import (
"context"
"fmt"
"github.com/Masterminds/semver"
"github.com/google/uuid"
"github.com/onflow/cadence"
jsoncdc "github.com/onflow/cadence/encoding/json"
"github.com/onflow/cadence/runtime/ast"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/cadence/runtime/parser2"
"github.com/onflow/flow-go-sdk"
"github.com/onflow/flow-go-sdk/templates"
flowgo "github.com/onflow/flow-go/model/flow"
"github.com/pkg/errors"
"github.com/dapperlabs/flow-playground-api/auth"
"github.com/dapperlabs/flow-playground-api/compute"
"github.com/dapperlabs/flow-playground-api/controller"
"github.com/dapperlabs/flow-playground-api/migrate"
"github.com/dapperlabs/flow-playground-api/model"
"github.com/dapperlabs/flow-playground-api/storage"
)
const MaxAccounts = 5
type Resolver struct {
version *semver.Version
store storage.Store
computer *compute.Computer
auth *auth.Authenticator
migrator *migrate.Migrator
projects *controller.Projects
scripts *controller.Scripts
lastCreatedProject *model.InternalProject
}
func NewResolver(
version *semver.Version,
store storage.Store,
computer *compute.Computer,
auth *auth.Authenticator,
) *Resolver {
projects := controller.NewProjects(version, store, computer, MaxAccounts)
scripts := controller.NewScripts(store, computer)
migrator := migrate.NewMigrator(projects)
return &Resolver{
version: version,
store: store,
computer: computer,
auth: auth,
migrator: migrator,
projects: projects,
scripts: scripts,
}
}
func (r *Resolver) Mutation() MutationResolver {
return &mutationResolver{r}
}
func (r *Resolver) Project() ProjectResolver {
return &projectResolver{r}
}
func (r *Resolver) Query() QueryResolver {
return &queryResolver{r}
}
func (r *Resolver) TransactionExecution() TransactionExecutionResolver {
return &transactionExecutionResolver{r}
}
func (r *Resolver) LastCreatedProject() *model.InternalProject {
return r.lastCreatedProject
}
type mutationResolver struct {
*Resolver
}
func (r *mutationResolver) CreateProject(ctx context.Context, input model.NewProject) (*model.Project, error) {
user, err := r.auth.GetOrCreateUser(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to get or create user")
}
proj, err := r.projects.Create(user, input)
if err != nil {
return nil, err
}
r.lastCreatedProject = proj
return proj.ExportPublicMutable(), nil
}
func (r *mutationResolver) UpdateProject(ctx context.Context, input model.UpdateProject) (*model.Project, error) {
var proj model.InternalProject
err := r.projects.Get(input.ID, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return nil, err
}
err = r.projects.Update(input, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to update project")
}
return proj.ExportPublicMutable(), nil
}
func (r *mutationResolver) UpdateAccount(ctx context.Context, input model.UpdateAccount) (*model.Account, error) {
var proj model.InternalProject
err := r.projects.Get(input.ProjectID, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return nil, err
}
var acc model.InternalAccount
err = r.store.GetAccount(model.NewProjectChildID(input.ID, proj.ID), &acc)
if err != nil {
return nil, errors.Wrap(err, "failed to get account")
}
if input.DeployedCode == nil {
err = r.store.UpdateAccount(input, &acc)
if err != nil {
return nil, errors.Wrap(err, "failed to update account")
}
return acc.Export(), nil
}
// Redeploy: clear all state
if acc.DeployedCode != "" {
err := r.projects.Reset(&proj)
if err != nil {
return nil, errors.Wrap(err, "failed to clear project state")
}
}
address := acc.Address.ToFlowAddress()
source := *input.DeployedCode
contractName, err := getSourceContractName(source)
if err != nil {
return nil, errors.Wrap(err, "failed to deploy account code")
}
tx := templates.AddAccountContract(address, templates.Contract{
Name: contractName,
Source: source,
})
result, err := r.computer.ExecuteTransaction(
proj.ID,
proj.TransactionCount,
func() ([]*model.RegisterDelta, error) {
var deltas []*model.RegisterDelta
err := r.store.GetRegisterDeltasForProject(proj.ID, &deltas)
if err != nil {
return nil, err
}
return deltas, nil
},
toTransactionBody(tx),
)
if err != nil {
return nil, errors.Wrap(err, "failed to deploy account code")
}
if result.Err != nil {
return nil, errors.Wrap(result.Err, "failed to deploy account code")
}
states, err := r.getAccountStates(proj.ID, result.States)
if err != nil {
return nil, err
}
input.DeployedContracts = &[]string{contractName}
err = r.store.UpdateAccountAfterDeployment(input, states, result.Delta, &acc)
if err != nil {
return nil, errors.Wrap(err, "failed to update account")
}
return acc.Export(), nil
}
func getSourceContractName(code string) (string, error) {
program, err := parser2.ParseProgram(code)
if err != nil {
return "", err
}
return getProgramContractName(program)
}
func getProgramContractName(program *ast.Program) (string, error) {
// The code may declare exactly one contract or one contract interface.
var contractDeclarations []*ast.CompositeDeclaration
var contractInterfaceDeclarations []*ast.InterfaceDeclaration
for _, compositeDeclaration := range program.CompositeDeclarations() {
if compositeDeclaration.CompositeKind == common.CompositeKindContract {
contractDeclarations = append(contractDeclarations, compositeDeclaration)
} else {
return "", fmt.Errorf(
"invalid %s: the code must declare exactly one contract or contract interface",
compositeDeclaration.DeclarationKind().Name(),
)
}
}
for _, interfaceDeclaration := range program.InterfaceDeclarations() {
if interfaceDeclaration.CompositeKind == common.CompositeKindContract {
contractInterfaceDeclarations = append(contractInterfaceDeclarations, interfaceDeclaration)
} else {
return "", fmt.Errorf(
"invalid %s: the code must declare exactly one contract or contract interface",
interfaceDeclaration.DeclarationKind().Name(),
)
}
}
switch {
case len(contractDeclarations) == 1 && len(contractInterfaceDeclarations) == 0:
return contractDeclarations[0].Identifier.Identifier, nil
case len(contractInterfaceDeclarations) == 1 && len(contractDeclarations) == 0:
return contractInterfaceDeclarations[0].Identifier.Identifier, nil
default:
return "", errors.New(
"the code must declare exactly one contract or contract interface",
)
}
}
func (r *mutationResolver) getAccountStates(
projectID uuid.UUID,
newStates compute.AccountStates,
) (map[uuid.UUID]model.AccountState, error) {
var accounts []*model.InternalAccount
err := r.store.GetAccountsForProject(projectID, &accounts)
if err != nil {
return nil, errors.Wrap(err, "failed to get project accounts")
}
states := make(map[uuid.UUID]model.AccountState)
for _, account := range accounts {
stateDelta, ok := newStates[account.Address]
if !ok {
continue
}
state, err := account.State()
if err != nil {
return nil, errors.Wrap(err, "failed to get account state")
}
for key, value := range stateDelta {
state[key] = value
}
states[account.ID] = state
}
return states, nil
}
func (r *mutationResolver) CreateTransactionTemplate(ctx context.Context, input model.NewTransactionTemplate) (*model.TransactionTemplate, error) {
tpl := &model.TransactionTemplate{
ProjectChildID: model.ProjectChildID{
ID: uuid.New(),
ProjectID: input.ProjectID,
},
Title: input.Title,
Script: input.Script,
}
var proj model.InternalProject
err := r.projects.Get(input.ProjectID, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return nil, err
}
err = r.store.InsertTransactionTemplate(tpl)
if err != nil {
return nil, errors.Wrap(err, "failed to store transaction template")
}
return tpl, nil
}
func (r *mutationResolver) UpdateTransactionTemplate(ctx context.Context, input model.UpdateTransactionTemplate) (*model.TransactionTemplate, error) {
var tpl model.TransactionTemplate
var proj model.InternalProject
err := r.projects.Get(input.ProjectID, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return nil, err
}
err = r.store.UpdateTransactionTemplate(input, &tpl)
if err != nil {
return nil, errors.Wrap(err, "failed to update transaction template")
}
return &tpl, nil
}
func (r *mutationResolver) DeleteTransactionTemplate(ctx context.Context, id uuid.UUID, projectID uuid.UUID) (uuid.UUID, error) {
var proj model.InternalProject
err := r.projects.Get(projectID, &proj)
if err != nil {
return uuid.Nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return uuid.Nil, err
}
err = r.store.DeleteTransactionTemplate(model.NewProjectChildID(id, projectID))
if err != nil {
return uuid.Nil, errors.Wrap(err, "failed to delete transaction template")
}
return id, nil
}
func (r *mutationResolver) CreateTransactionExecution(
ctx context.Context,
input model.NewTransactionExecution,
) (*model.TransactionExecution, error) {
var proj model.InternalProject
err := r.projects.Get(input.ProjectID, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return nil, err
}
tx := flow.NewTransaction().
SetScript([]byte(input.Script))
for i, argument := range input.Arguments {
// Decode and then encode again to ensure the value is valid
value, err := jsoncdc.Decode([]byte(argument))
if err == nil {
err = tx.AddArgument(value)
}
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to decode argument %d", i))
}
}
for _, authorizer := range input.Signers {
tx.AddAuthorizer(authorizer.ToFlowAddress())
}
result, err := r.computer.ExecuteTransaction(
proj.ID,
proj.TransactionCount,
func() ([]*model.RegisterDelta, error) {
var deltas []*model.RegisterDelta
err := r.store.GetRegisterDeltasForProject(proj.ID, &deltas)
if err != nil {
return nil, err
}
return deltas, nil
},
toTransactionBody(tx),
)
if err != nil {
return nil, errors.Wrap(err, "failed to execute transaction")
}
exe := model.TransactionExecution{
ProjectChildID: model.ProjectChildID{
ID: uuid.New(),
ProjectID: input.ProjectID,
},
Script: input.Script,
Arguments: input.Arguments,
Logs: result.Logs,
}
var states map[uuid.UUID]model.AccountState
if result.Err != nil {
exe.Errors = compute.ExtractProgramErrors(result.Err)
} else {
var err error
states, err = r.getAccountStates(proj.ID, result.States)
if err != nil {
return nil, err
}
}
events, err := parseEvents(result.Events)
if err != nil {
return nil, errors.Wrap(err, "failed to parse events")
}
exe.Events = events
err = r.store.InsertTransactionExecution(&exe, states, result.Delta)
if err != nil {
return nil, errors.Wrap(err, "failed to insert transaction execution record")
}
return &exe, nil
}
func (r *mutationResolver) CreateScriptTemplate(ctx context.Context, input model.NewScriptTemplate) (*model.ScriptTemplate, error) {
var proj model.InternalProject
err := r.projects.Get(input.ProjectID, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return nil, err
}
tpl, err := r.scripts.CreateTemplate(proj.ID, input)
if err != nil {
return nil, errors.Wrap(err, "failed to create script template")
}
return tpl, nil
}
func (r *mutationResolver) UpdateScriptTemplate(ctx context.Context, input model.UpdateScriptTemplate) (*model.ScriptTemplate, error) {
var proj model.InternalProject
err := r.projects.Get(input.ProjectID, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return nil, err
}
var tpl model.ScriptTemplate
err = r.scripts.UpdateTemplate(input, &tpl)
if err != nil {
return nil, errors.Wrap(err, "failed to update script template")
}
return &tpl, nil
}
func (r *mutationResolver) DeleteScriptTemplate(
ctx context.Context,
id uuid.UUID,
projectID uuid.UUID,
) (uuid.UUID, error) {
var proj model.InternalProject
err := r.projects.Get(projectID, &proj)
if err != nil {
return uuid.Nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return uuid.Nil, err
}
err = r.scripts.DeleteTemplate(id, projectID)
if err != nil {
return uuid.Nil, err
}
return id, nil
}
func (r *mutationResolver) CreateScriptExecution(
ctx context.Context,
input model.NewScriptExecution,
) (*model.ScriptExecution, error) {
var proj model.InternalProject
err := r.projects.Get(input.ProjectID, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return nil, err
}
exe, err := r.scripts.CreateExecution(&proj, input.Script, input.Arguments)
if err != nil {
return nil, err
}
return exe, nil
}
type projectResolver struct{ *Resolver }
func (r *projectResolver) Accounts(ctx context.Context, obj *model.Project) ([]*model.Account, error) {
var accs []*model.InternalAccount
err := r.store.GetAccountsForProject(obj.ID, &accs)
if err != nil {
return nil, errors.Wrap(err, "failed to get accounts")
}
exportedAccs := make([]*model.Account, len(accs))
for i, acc := range accs {
exported, err := acc.ExportWithJSONState()
if err != nil {
return nil, errors.Wrap(err, "failed to export")
}
exportedAccs[i] = exported
}
return exportedAccs, nil
}
func (r *projectResolver) TransactionTemplates(ctx context.Context, obj *model.Project) ([]*model.TransactionTemplate, error) {
var tpls []*model.TransactionTemplate
err := r.store.GetTransactionTemplatesForProject(obj.ID, &tpls)
if err != nil {
return nil, errors.Wrap(err, "failed to get transaction templates")
}
return tpls, nil
}
func (r *projectResolver) TransactionExecutions(ctx context.Context, obj *model.Project) ([]*model.TransactionExecution, error) {
var exes []*model.TransactionExecution
err := r.store.GetTransactionExecutionsForProject(obj.ID, &exes)
if err != nil {
return nil, errors.Wrap(err, "failed to get transaction executions")
}
return exes, nil
}
func (r *projectResolver) ScriptTemplates(ctx context.Context, obj *model.Project) ([]*model.ScriptTemplate, error) {
var tpls []*model.ScriptTemplate
err := r.store.GetScriptTemplatesForProject(obj.ID, &tpls)
if err != nil {
return nil, errors.Wrap(err, "failed to get script templates")
}
return tpls, nil
}
func (r *projectResolver) ScriptExecutions(ctx context.Context, obj *model.Project) ([]*model.ScriptExecution, error) {
panic("not implemented")
}
type queryResolver struct{ *Resolver }
func (r *queryResolver) PlaygroundInfo(ctx context.Context) (*model.PlaygroundInfo, error) {
return &model.PlaygroundInfo{
APIVersion: *r.version,
CadenceVersion: *semver.MustParse(cadence.Version),
}, nil
}
func (r *queryResolver) Project(ctx context.Context, id uuid.UUID) (*model.Project, error) {
var proj model.InternalProject
err := r.projects.Get(id, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
if err := r.auth.CheckProjectAccess(ctx, &proj); err != nil {
return proj.ExportPublicImmutable(), nil
}
// only migrate if current user has access to this project
migrated, err := r.migrator.MigrateProject(id, proj.Version, r.version)
if err != nil {
return nil, errors.Wrap(err, "failed to migrate project")
}
// reload project if needed
if migrated {
err := r.projects.Get(id, &proj)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
}
return proj.ExportPublicMutable(), nil
}
func (r *queryResolver) Account(ctx context.Context, id uuid.UUID, projectID uuid.UUID) (*model.Account, error) {
var acc model.InternalAccount
err := r.store.GetAccount(model.NewProjectChildID(id, projectID), &acc)
if err != nil {
return nil, errors.Wrap(err, "failed to get account")
}
exported, err := acc.ExportWithJSONState()
if err != nil {
return nil, errors.Wrap(err, "failed to export")
}
return exported, nil
}
func (r *queryResolver) TransactionTemplate(ctx context.Context, id uuid.UUID, projectID uuid.UUID) (*model.TransactionTemplate, error) {
var tpl model.TransactionTemplate
err := r.store.GetTransactionTemplate(model.NewProjectChildID(id, projectID), &tpl)
if err != nil {
return nil, errors.Wrap(err, "failed to get transaction template")
}
return &tpl, nil
}
func (r *queryResolver) ScriptTemplate(ctx context.Context, id uuid.UUID, projectID uuid.UUID) (*model.ScriptTemplate, error) {
var tpl model.ScriptTemplate
err := r.store.GetScriptTemplate(model.NewProjectChildID(id, projectID), &tpl)
if err != nil {
return nil, errors.Wrap(err, "failed to get script template")
}
return &tpl, nil
}
type transactionExecutionResolver struct{ *Resolver }
func (*transactionExecutionResolver) Signers(_ context.Context, _ *model.TransactionExecution) ([]*model.Account, error) {
panic("not implemented")
}
func parseEvents(flowEvents []flowgo.Event) ([]model.Event, error) {
events := make([]model.Event, len(flowEvents))
for i, event := range flowEvents {
parsedEvent, err := parseEvent(event)
if err != nil {
return nil, errors.Wrap(err, "failed to parse event")
}
events[i] = parsedEvent
}
return events, nil
}
func parseEvent(event flowgo.Event) (model.Event, error) {
payload, err := jsoncdc.Decode(event.Payload)
if err != nil {
return model.Event{}, errors.Wrap(err, "failed to decode event payload (JSON-CDC)")
}
fields := payload.(cadence.Event).Fields
values := make([]string, len(fields))
for j, field := range fields {
enc, err := jsoncdc.Encode(field)
if err != nil {
return model.Event{}, errors.Wrap(err, "failed to encode event field to JSON-CDC")
}
values[j] = string(enc)
}
return model.Event{
Type: string(event.Type),
Values: values,
}, nil
}
func toTransactionBody(tx *flow.Transaction) *flowgo.TransactionBody {
txBody := flowgo.NewTransactionBody()
txBody.SetScript(tx.Script)
for _, authorizer := range tx.Authorizers {
txBody.AddAuthorizer(flowgo.Address(authorizer))
}
for _, arg := range tx.Arguments {
txBody.AddArgument(arg)
}
return txBody
}