-
Notifications
You must be signed in to change notification settings - Fork 131
/
encode.go
1012 lines (891 loc) Β· 24.9 KB
/
encode.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
/*
* Cadence - The resource-oriented smart contract programming language
*
* Copyright 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 json
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math/big"
goRuntime "runtime"
"strconv"
"strings"
"github.com/onflow/cadence"
"github.com/onflow/cadence/runtime/common"
"github.com/onflow/cadence/runtime/sema"
)
// An Encoder converts Cadence values into JSON-encoded bytes.
type Encoder struct {
enc *json.Encoder
}
// Encode returns the JSON-encoded representation of the given value.
//
// This function returns an error if the Cadence value cannot be represented as JSON.
func Encode(value cadence.Value) ([]byte, error) {
var w bytes.Buffer
enc := NewEncoder(&w)
err := enc.Encode(value)
if err != nil {
return nil, err
}
return w.Bytes(), nil
}
// MustEncode returns the JSON-encoded representation of the given value, or panics
// if the value cannot be represented as JSON.
func MustEncode(value cadence.Value) []byte {
b, err := Encode(value)
if err != nil {
panic(err)
}
return b
}
// NewEncoder initializes an Encoder that will write JSON-encoded bytes to the
// given io.Writer.
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{enc: json.NewEncoder(w)}
}
// Encode writes the JSON-encoded representation of the given value to this
// encoder's io.Writer.
//
// This function returns an error if the given value's type is not supported
// by this encoder.
func (e *Encoder) Encode(value cadence.Value) (err error) {
// capture panics that occur during struct preparation
defer func() {
if r := recover(); r != nil {
// don't recover Go errors
goErr, ok := r.(goRuntime.Error)
if ok {
panic(goErr)
}
panicErr, isError := r.(error)
if !isError {
panic(r)
}
err = fmt.Errorf("failed to encode value: %w", panicErr)
}
}()
preparedValue := Prepare(value)
return e.enc.Encode(&preparedValue)
}
// JSON struct definitions
type jsonValue any
type jsonValueObject struct {
Value jsonValue `json:"value"`
Type string `json:"type"`
}
type jsonEmptyValueObject struct {
Type string `json:"type"`
}
type jsonDictionaryItem struct {
Key jsonValue `json:"key"`
Value jsonValue `json:"value"`
}
type jsonInclusiveRangeValue struct {
Start jsonValue `json:"start"`
End jsonValue `json:"end"`
Step jsonValue `json:"step"`
}
type jsonCompositeValue struct {
ID string `json:"id"`
Fields []jsonCompositeField `json:"fields"`
}
type jsonCompositeField struct {
Value jsonValue `json:"value"`
Name string `json:"name"`
}
type jsonPathValue struct {
Domain string `json:"domain"`
Identifier string `json:"identifier"`
}
type jsonFieldType struct {
Type jsonValue `json:"type"`
Id string `json:"id"`
}
type jsonNominalType struct {
Type jsonValue `json:"type"`
Kind string `json:"kind"`
TypeID string `json:"typeID"`
Fields []jsonFieldType `json:"fields"`
Initializers [][]jsonParameterType `json:"initializers"`
}
type jsonSimpleType struct {
Kind string `json:"kind"`
}
type jsonUnaryType struct {
Type jsonValue `json:"type"`
Kind string `json:"kind"`
}
type jsonConstantSizedArrayType struct {
Type jsonValue `json:"type"`
Kind string `json:"kind"`
Size uint `json:"size"`
}
type jsonDictionaryType struct {
KeyType jsonValue `json:"key"`
ValueType jsonValue `json:"value"`
Kind string `json:"kind"`
}
type jsonAuthorization struct {
Kind string `json:"kind"`
Entitlements []jsonNominalType `json:"entitlements"`
}
type jsonReferenceType struct {
Type jsonValue `json:"type"`
Kind string `json:"kind"`
Authorization jsonAuthorization `json:"authorization"`
}
type jsonIntersectionType struct {
Kind string `json:"kind"`
TypeID string `json:"typeID"`
Types []jsonValue `json:"types"`
}
type jsonTypeParameter struct {
Name string `json:"name"`
TypeBound jsonValue `json:"typeBound"`
}
type jsonParameterType struct {
Type jsonValue `json:"type"`
Label string `json:"label"`
Id string `json:"id"`
}
type jsonFunctionType struct {
Kind string `json:"kind"`
TypeID string `json:"typeID"`
TypeParameters []jsonTypeParameter `json:"typeParameters"`
Parameters []jsonParameterType `json:"parameters"`
Return jsonValue `json:"return"`
Purity string `json:"purity"`
}
type jsonTypeValue struct {
StaticType jsonValue `json:"staticType"`
}
type jsonCapabilityValue struct {
BorrowType jsonValue `json:"borrowType"`
Address string `json:"address"`
ID string `json:"id"`
}
type jsonFunctionValue struct {
FunctionType jsonValue `json:"functionType"`
}
type jsonInclusiveRangeType struct {
ElementType jsonValue `json:"element"`
Kind string `json:"kind"`
}
const (
voidTypeStr = "Void"
optionalTypeStr = "Optional"
boolTypeStr = "Bool"
characterTypeStr = "Character"
stringTypeStr = "String"
addressTypeStr = "Address"
intTypeStr = "Int"
int8TypeStr = "Int8"
int16TypeStr = "Int16"
int32TypeStr = "Int32"
int64TypeStr = "Int64"
int128TypeStr = "Int128"
int256TypeStr = "Int256"
uintTypeStr = "UInt"
uint8TypeStr = "UInt8"
uint16TypeStr = "UInt16"
uint32TypeStr = "UInt32"
uint64TypeStr = "UInt64"
uint128TypeStr = "UInt128"
uint256TypeStr = "UInt256"
word8TypeStr = "Word8"
word16TypeStr = "Word16"
word32TypeStr = "Word32"
word64TypeStr = "Word64"
word128TypeStr = "Word128"
word256TypeStr = "Word256"
fix64TypeStr = "Fix64"
ufix64TypeStr = "UFix64"
arrayTypeStr = "Array"
dictionaryTypeStr = "Dictionary"
structTypeStr = "Struct"
resourceTypeStr = "Resource"
attachmentTypeStr = "Attachment"
eventTypeStr = "Event"
contractTypeStr = "Contract"
pathTypeStr = "Path"
typeTypeStr = "Type"
capabilityTypeStr = "Capability"
enumTypeStr = "Enum"
functionTypeStr = "Function"
inclusiveRangeTypeStr = "InclusiveRange"
)
// Prepare traverses the object graph of the provided value and constructs
// a struct representation that can be marshalled to JSON.
func Prepare(v cadence.Value) jsonValue {
switch v := v.(type) {
case cadence.Void:
return prepareVoid()
case cadence.Optional:
return prepareOptional(v)
case cadence.Bool:
return prepareBool(v)
case cadence.Character:
return prepareCharacter(v)
case cadence.String:
return prepareString(v)
case cadence.Address:
return prepareAddress(v)
case cadence.Int:
return prepareInt(v)
case cadence.Int8:
return prepareInt8(v)
case cadence.Int16:
return prepareInt16(v)
case cadence.Int32:
return prepareInt32(v)
case cadence.Int64:
return prepareInt64(v)
case cadence.Int128:
return prepareInt128(v)
case cadence.Int256:
return prepareInt256(v)
case cadence.UInt:
return prepareUInt(v)
case cadence.UInt8:
return prepareUInt8(v)
case cadence.UInt16:
return prepareUInt16(v)
case cadence.UInt32:
return prepareUInt32(v)
case cadence.UInt64:
return prepareUInt64(v)
case cadence.UInt128:
return prepareUInt128(v)
case cadence.UInt256:
return prepareUInt256(v)
case cadence.Word8:
return prepareWord8(v)
case cadence.Word16:
return prepareWord16(v)
case cadence.Word32:
return prepareWord32(v)
case cadence.Word64:
return prepareWord64(v)
case cadence.Word128:
return prepareWord128(v)
case cadence.Word256:
return prepareWord256(v)
case cadence.Fix64:
return prepareFix64(v)
case cadence.UFix64:
return prepareUFix64(v)
case cadence.Array:
return prepareArray(v)
case cadence.Dictionary:
return prepareDictionary(v)
case *cadence.InclusiveRange:
return prepareInclusiveRange(v)
case cadence.Struct:
return prepareStruct(v)
case cadence.Resource:
return prepareResource(v)
case cadence.Event:
return prepareEvent(v)
case cadence.Contract:
return prepareContract(v)
case cadence.Path:
return preparePath(v)
case cadence.TypeValue:
return prepareTypeValue(v)
case cadence.Capability:
return prepareCapability(v)
case cadence.Enum:
return prepareEnum(v)
case cadence.Attachment:
return prepareAttachment(v)
case cadence.Function:
return prepareFunction(v)
case nil:
return nil
default:
panic(fmt.Errorf("unsupported value: %T, %v", v, v))
}
}
func prepareVoid() jsonValue {
return jsonEmptyValueObject{Type: voidTypeStr}
}
func prepareOptional(v cadence.Optional) jsonValue {
var value any
if v.Value != nil {
value = Prepare(v.Value)
}
return jsonValueObject{
Type: optionalTypeStr,
Value: value,
}
}
func prepareBool(v cadence.Bool) jsonValue {
return jsonValueObject{
Type: boolTypeStr,
Value: v,
}
}
func prepareCharacter(v cadence.Character) jsonValue {
return jsonValueObject{
Type: characterTypeStr,
Value: v,
}
}
func prepareString(v cadence.String) jsonValue {
return jsonValueObject{
Type: stringTypeStr,
Value: v,
}
}
func prepareAddress(v cadence.Address) jsonValue {
return jsonValueObject{
Type: addressTypeStr,
Value: encodeBytes(v.Bytes()),
}
}
func prepareInt(v cadence.Int) jsonValue {
return jsonValueObject{
Type: intTypeStr,
Value: encodeBig(v.Big()),
}
}
func prepareInt8(v cadence.Int8) jsonValue {
return jsonValueObject{
Type: int8TypeStr,
Value: encodeInt(int64(v)),
}
}
func prepareInt16(v cadence.Int16) jsonValue {
return jsonValueObject{
Type: int16TypeStr,
Value: encodeInt(int64(v)),
}
}
func prepareInt32(v cadence.Int32) jsonValue {
return jsonValueObject{
Type: int32TypeStr,
Value: encodeInt(int64(v)),
}
}
func prepareInt64(v cadence.Int64) jsonValue {
return jsonValueObject{
Type: int64TypeStr,
Value: encodeInt(int64(v)),
}
}
func prepareInt128(v cadence.Int128) jsonValue {
return jsonValueObject{
Type: int128TypeStr,
Value: encodeBig(v.Big()),
}
}
func prepareInt256(v cadence.Int256) jsonValue {
return jsonValueObject{
Type: int256TypeStr,
Value: encodeBig(v.Big()),
}
}
func prepareUInt(v cadence.UInt) jsonValue {
return jsonValueObject{
Type: uintTypeStr,
Value: encodeBig(v.Big()),
}
}
func prepareUInt8(v cadence.UInt8) jsonValue {
return jsonValueObject{
Type: uint8TypeStr,
Value: encodeUInt(uint64(v)),
}
}
func prepareUInt16(v cadence.UInt16) jsonValue {
return jsonValueObject{
Type: uint16TypeStr,
Value: encodeUInt(uint64(v)),
}
}
func prepareUInt32(v cadence.UInt32) jsonValue {
return jsonValueObject{
Type: uint32TypeStr,
Value: encodeUInt(uint64(v)),
}
}
func prepareUInt64(v cadence.UInt64) jsonValue {
return jsonValueObject{
Type: uint64TypeStr,
Value: encodeUInt(uint64(v)),
}
}
func prepareUInt128(v cadence.UInt128) jsonValue {
return jsonValueObject{
Type: uint128TypeStr,
Value: encodeBig(v.Big()),
}
}
func prepareUInt256(v cadence.UInt256) jsonValue {
return jsonValueObject{
Type: uint256TypeStr,
Value: encodeBig(v.Big()),
}
}
func prepareWord8(v cadence.Word8) jsonValue {
return jsonValueObject{
Type: word8TypeStr,
Value: encodeUInt(uint64(v)),
}
}
func prepareWord16(v cadence.Word16) jsonValue {
return jsonValueObject{
Type: word16TypeStr,
Value: encodeUInt(uint64(v)),
}
}
func prepareWord32(v cadence.Word32) jsonValue {
return jsonValueObject{
Type: word32TypeStr,
Value: encodeUInt(uint64(v)),
}
}
func prepareWord64(v cadence.Word64) jsonValue {
return jsonValueObject{
Type: word64TypeStr,
Value: encodeUInt(uint64(v)),
}
}
func prepareWord128(v cadence.Word128) jsonValue {
return jsonValueObject{
Type: word128TypeStr,
Value: encodeBig(v.Big()),
}
}
func prepareWord256(v cadence.Word256) jsonValue {
return jsonValueObject{
Type: word256TypeStr,
Value: encodeBig(v.Big()),
}
}
func prepareFix64(v cadence.Fix64) jsonValue {
return jsonValueObject{
Type: fix64TypeStr,
Value: encodeFix64(int64(v)),
}
}
func prepareUFix64(v cadence.UFix64) jsonValue {
return jsonValueObject{
Type: ufix64TypeStr,
Value: encodeUFix64(uint64(v)),
}
}
func prepareArray(v cadence.Array) jsonValue {
values := make([]jsonValue, len(v.Values))
for i, value := range v.Values {
values[i] = Prepare(value)
}
return jsonValueObject{
Type: arrayTypeStr,
Value: values,
}
}
func prepareDictionary(v cadence.Dictionary) jsonValue {
items := make([]jsonDictionaryItem, len(v.Pairs))
for i, pair := range v.Pairs {
items[i] = jsonDictionaryItem{
Key: Prepare(pair.Key),
Value: Prepare(pair.Value),
}
}
return jsonValueObject{
Type: dictionaryTypeStr,
Value: items,
}
}
func prepareInclusiveRange(v *cadence.InclusiveRange) jsonValue {
return jsonValueObject{
Type: inclusiveRangeTypeStr,
Value: jsonInclusiveRangeValue{
Start: Prepare(v.Start),
End: Prepare(v.End),
Step: Prepare(v.Step),
},
}
}
func prepareStruct(v cadence.Struct) jsonValue {
return prepareComposite(structTypeStr, v.StructType.ID(), v.StructType.Fields, v.Fields)
}
func prepareResource(v cadence.Resource) jsonValue {
return prepareComposite(resourceTypeStr, v.ResourceType.ID(), v.ResourceType.Fields, v.Fields)
}
func prepareEvent(v cadence.Event) jsonValue {
return prepareComposite(eventTypeStr, v.EventType.ID(), v.EventType.Fields, v.Fields)
}
func prepareContract(v cadence.Contract) jsonValue {
return prepareComposite(contractTypeStr, v.ContractType.ID(), v.ContractType.Fields, v.Fields)
}
func prepareEnum(v cadence.Enum) jsonValue {
return prepareComposite(enumTypeStr, v.EnumType.ID(), v.EnumType.Fields, v.Fields)
}
func prepareAttachment(v cadence.Attachment) jsonValue {
return prepareComposite(attachmentTypeStr, v.AttachmentType.ID(), v.AttachmentType.Fields, v.Fields)
}
func prepareComposite(kind, id string, fieldTypes []cadence.Field, fields []cadence.Value) jsonValue {
// Ensure there are _at least _ as many field values as field types.
// There might be more field values in the case of attachments.
if len(fields) < len(fieldTypes) {
panic(fmt.Errorf(
"%s field count (%d) does not match declared type (%d)",
kind,
len(fields),
len(fieldTypes),
))
}
compositeFields := make([]jsonCompositeField, len(fields))
for i, value := range fields {
var name string
// Provide the field name, if the field type is available.
// In the case of attachments, they are provided as field values,
// but there is no corresponding field type.
if i < len(fieldTypes) {
fieldType := fieldTypes[i]
name = fieldType.Identifier
}
compositeFields[i] = jsonCompositeField{
Name: name,
Value: Prepare(value),
}
}
return jsonValueObject{
Type: kind,
Value: jsonCompositeValue{
ID: id,
Fields: compositeFields,
},
}
}
func prepareAuthorization(auth cadence.Authorization) jsonAuthorization {
var kind string
var entitlements []jsonNominalType
switch auth := auth.(type) {
case cadence.Unauthorized:
kind = "Unauthorized"
case cadence.EntitlementMapAuthorization:
kind = "EntitlementMapAuthorization"
entitlements = []jsonNominalType{
{
Kind: "EntitlementMap",
TypeID: string(auth.TypeID),
},
}
case *cadence.EntitlementSetAuthorization:
for _, entitlement := range auth.Entitlements {
entitlements = append(entitlements, jsonNominalType{
Kind: "Entitlement",
TypeID: string(entitlement),
})
}
switch auth.Kind {
case cadence.Conjunction:
kind = "EntitlementConjunctionSet"
case cadence.Disjunction:
kind = "EntitlementDisjunctionSet"
}
}
return jsonAuthorization{
Kind: kind,
Entitlements: entitlements,
}
}
func preparePath(x cadence.Path) jsonValue {
return jsonValueObject{
Type: pathTypeStr,
Value: jsonPathValue{
Domain: x.Domain.Identifier(),
Identifier: x.Identifier,
},
}
}
func prepareTypeParameter(typeParameter cadence.TypeParameter, results typePreparationResults) jsonTypeParameter {
typeBound := typeParameter.TypeBound
var preparedTypeBound jsonValue
if typeBound != nil {
preparedTypeBound = prepareType(typeBound, results)
}
return jsonTypeParameter{
Name: typeParameter.Name,
TypeBound: preparedTypeBound,
}
}
func prepareParameter(parameterType cadence.Parameter, results typePreparationResults) jsonParameterType {
return jsonParameterType{
Label: parameterType.Label,
Id: parameterType.Identifier,
Type: prepareType(parameterType.Type, results),
}
}
func prepareFieldType(fieldType cadence.Field, results typePreparationResults) jsonFieldType {
return jsonFieldType{
Id: fieldType.Identifier,
Type: prepareType(fieldType.Type, results),
}
}
func prepareFields(fieldTypes []cadence.Field, results typePreparationResults) []jsonFieldType {
fields := make([]jsonFieldType, len(fieldTypes))
for i, fieldType := range fieldTypes {
fields[i] = prepareFieldType(fieldType, results)
}
return fields
}
func prepareTypeParameters(typeParameters []cadence.TypeParameter, results typePreparationResults) []jsonTypeParameter {
result := make([]jsonTypeParameter, len(typeParameters))
for i, typeParameter := range typeParameters {
result[i] = prepareTypeParameter(typeParameter, results)
}
return result
}
func prepareParameters(parameters []cadence.Parameter, results typePreparationResults) []jsonParameterType {
result := make([]jsonParameterType, len(parameters))
for i, param := range parameters {
result[i] = prepareParameter(param, results)
}
return result
}
func prepareInitializers(initializers [][]cadence.Parameter, results typePreparationResults) [][]jsonParameterType {
result := make([][]jsonParameterType, len(initializers))
for i, params := range initializers {
result[i] = prepareParameters(params, results)
}
return result
}
func prepareType(typ cadence.Type, results typePreparationResults) jsonValue {
var supportedRecursiveType bool
switch typ.(type) {
case cadence.CompositeType, cadence.InterfaceType:
supportedRecursiveType = true
}
if _, ok := results[typ]; ok {
if !supportedRecursiveType {
panic(fmt.Errorf("failed to prepare type: unsupported recursive type: %T", typ))
}
return typ.ID()
}
if supportedRecursiveType {
results[typ] = struct{}{}
}
switch typ := typ.(type) {
case cadence.BytesType:
return jsonSimpleType{
Kind: typ.ID(),
}
case *cadence.OptionalType:
return jsonUnaryType{
Kind: "Optional",
Type: prepareType(typ.Type, results),
}
case *cadence.VariableSizedArrayType:
return jsonUnaryType{
Kind: "VariableSizedArray",
Type: prepareType(typ.ElementType, results),
}
case *cadence.ConstantSizedArrayType:
return jsonConstantSizedArrayType{
Kind: "ConstantSizedArray",
Type: prepareType(typ.ElementType, results),
Size: typ.Size,
}
case *cadence.DictionaryType:
return jsonDictionaryType{
Kind: "Dictionary",
KeyType: prepareType(typ.KeyType, results),
ValueType: prepareType(typ.ElementType, results),
}
case *cadence.InclusiveRangeType:
return jsonInclusiveRangeType{
Kind: "InclusiveRange",
ElementType: prepareType(typ.ElementType, results),
}
case *cadence.StructType:
return jsonNominalType{
Kind: "Struct",
Type: "",
TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.ResourceType:
return jsonNominalType{
Kind: "Resource",
Type: "",
TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.EventType:
return jsonNominalType{
Kind: "Event",
Type: "",
TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: [][]jsonParameterType{prepareParameters(typ.Initializer, results)},
}
case *cadence.ContractType:
return jsonNominalType{
Kind: "Contract",
Type: "",
TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.StructInterfaceType:
return jsonNominalType{
Kind: "StructInterface",
Type: "",
TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.ResourceInterfaceType:
return jsonNominalType{
Kind: "ResourceInterface",
Type: "",
TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.ContractInterfaceType:
return jsonNominalType{
Kind: "ContractInterface",
Type: "",
TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.FunctionType:
typeJson := jsonFunctionType{
Kind: "Function",
TypeID: typ.ID(),
TypeParameters: prepareTypeParameters(typ.TypeParameters, results),
Parameters: prepareParameters(typ.Parameters, results),
Return: prepareType(typ.ReturnType, results),
}
if typ.Purity == cadence.FunctionPurityView {
typeJson.Purity = "view"
}
return typeJson
case *cadence.ReferenceType:
return jsonReferenceType{
Kind: "Reference",
Authorization: prepareAuthorization(typ.Authorization),
Type: prepareType(typ.Type, results),
}
case *cadence.IntersectionType:
types := make([]jsonValue, len(typ.Types))
for i, typ := range typ.Types {
types[i] = prepareType(typ, results)
}
return jsonIntersectionType{
Kind: "Intersection",
Types: types,
TypeID: typ.ID(),
}
case *cadence.CapabilityType:
return jsonUnaryType{
Kind: "Capability",
Type: prepareType(typ.BorrowType, results),
}
case *cadence.EnumType:
return jsonNominalType{
Kind: "Enum",
TypeID: string(common.NewTypeIDFromQualifiedName(nil, typ.Location, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
Type: prepareType(typ.RawType, results),
}
case cadence.PrimitiveType:
return jsonSimpleType{
Kind: typ.ID(),
}
case nil:
return ""
}
panic(fmt.Errorf("unsupported type: %T, %s", typ, typ))
}
type typePreparationResults map[cadence.Type]struct{}
func prepareTypeValue(typeValue cadence.TypeValue) jsonValue {
return jsonValueObject{
Type: typeTypeStr,
Value: jsonTypeValue{
StaticType: prepareType(typeValue.StaticType, typePreparationResults{}),
},
}
}
func prepareCapability(capability cadence.Capability) jsonValue {
return jsonValueObject{
Type: capabilityTypeStr,
Value: jsonCapabilityValue{
ID: encodeUInt(uint64(capability.ID)),
Address: encodeBytes(capability.Address.Bytes()),
BorrowType: prepareType(capability.BorrowType, typePreparationResults{}),
},
}
}
func prepareFunction(function cadence.Function) jsonValue {
return jsonValueObject{
Type: functionTypeStr,
Value: jsonFunctionValue{
FunctionType: prepareType(function.FunctionType, typePreparationResults{}),
},
}
}
func encodeBytes(v []byte) string {
return fmt.Sprintf("0x%x", v)
}
func encodeBig(v *big.Int) string {
return v.String()
}
func encodeInt(v int64) string {
return strconv.FormatInt(v, 10)
}
func encodeUInt(v uint64) string {
return strconv.FormatUint(v, 10)
}
func encodeFix64(v int64) string {
integer := v / sema.Fix64Factor
fraction := v % sema.Fix64Factor
negative := fraction < 0
var builder strings.Builder
if negative {
fraction = -fraction
if integer == 0 {
builder.WriteByte('-')
}
}
builder.WriteString(fmt.Sprintf(
"%d.%08d",
integer,
fraction,
))
return builder.String()