-
Notifications
You must be signed in to change notification settings - Fork 131
/
encode.go
930 lines (819 loc) Β· 22 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
/*
* Cadence - The resource-oriented smart contract programming language
*
* Copyright 2019-2022 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/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 interface{}
type jsonValueObject struct {
Type string `json:"type"`
Value jsonValue `json:"value"`
}
type jsonEmptyValueObject struct {
Type string `json:"type"`
}
type jsonDictionaryItem struct {
Key jsonValue `json:"key"`
Value jsonValue `json:"value"`
}
type jsonCompositeValue struct {
ID string `json:"id"`
Fields []jsonCompositeField `json:"fields"`
}
type jsonCompositeField struct {
Name string `json:"name"`
Value jsonValue `json:"value"`
}
type jsonLinkValue struct {
TargetPath jsonValue `json:"targetPath"`
BorrowType string `json:"borrowType"`
}
type jsonPathValue struct {
Domain string `json:"domain"`
Identifier string `json:"identifier"`
}
type jsonFieldType struct {
Id string `json:"id"`
Type jsonValue `json:"type"`
}
type jsonNominalType struct {
Kind string `json:"kind"`
TypeID string `json:"typeID"`
Fields []jsonFieldType `json:"fields"`
Initializers [][]jsonParameterType `json:"initializers"`
Type jsonValue `json:"type"`
}
type jsonSimpleType struct {
Kind string `json:"kind"`
}
type jsonUnaryType struct {
Kind string `json:"kind"`
Type jsonValue `json:"type"`
}
type jsonConstantSizedArrayType struct {
Kind string `json:"kind"`
Type jsonValue `json:"type"`
Size uint `json:"size"`
}
type jsonDictionaryType struct {
Kind string `json:"kind"`
KeyType jsonValue `json:"key"`
ValueType jsonValue `json:"value"`
}
type jsonReferenceType struct {
Kind string `json:"kind"`
Type jsonValue `json:"type"`
Authorized bool `json:"authorized"`
}
type jsonRestrictedType struct {
Kind string `json:"kind"`
TypeID string `json:"typeID"`
Type jsonValue `json:"type"`
Restrictions []jsonValue `json:"restrictions"`
}
type jsonParameterType struct {
Label string `json:"label"`
Id string `json:"id"`
Type jsonValue `json:"type"`
}
type jsonFunctionType struct {
Kind string `json:"kind"`
TypeID string `json:"typeID"`
Parameters []jsonParameterType `json:"parameters"`
Return jsonValue `json:"return"`
}
type jsonTypeValue struct {
StaticType jsonValue `json:"staticType"`
}
type jsonCapabilityValue struct {
Path jsonValue `json:"path"`
Address string `json:"address"`
BorrowType jsonValue `json:"borrowType"`
}
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"
fix64TypeStr = "Fix64"
ufix64TypeStr = "UFix64"
arrayTypeStr = "Array"
dictionaryTypeStr = "Dictionary"
structTypeStr = "Struct"
resourceTypeStr = "Resource"
eventTypeStr = "Event"
contractTypeStr = "Contract"
linkTypeStr = "Link"
pathTypeStr = "Path"
typeTypeStr = "Type"
capabilityTypeStr = "Capability"
enumTypeStr = "Enum"
)
// 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 x := v.(type) {
case cadence.Void:
return prepareVoid()
case cadence.Optional:
return prepareOptional(x)
case cadence.Bool:
return prepareBool(x)
case cadence.Character:
return prepareCharacter(x)
case cadence.String:
return prepareString(x)
case cadence.Address:
return prepareAddress(x)
case cadence.Int:
return prepareInt(x)
case cadence.Int8:
return prepareInt8(x)
case cadence.Int16:
return prepareInt16(x)
case cadence.Int32:
return prepareInt32(x)
case cadence.Int64:
return prepareInt64(x)
case cadence.Int128:
return prepareInt128(x)
case cadence.Int256:
return prepareInt256(x)
case cadence.UInt:
return prepareUInt(x)
case cadence.UInt8:
return prepareUInt8(x)
case cadence.UInt16:
return prepareUInt16(x)
case cadence.UInt32:
return prepareUInt32(x)
case cadence.UInt64:
return prepareUInt64(x)
case cadence.UInt128:
return prepareUInt128(x)
case cadence.UInt256:
return prepareUInt256(x)
case cadence.Word8:
return prepareWord8(x)
case cadence.Word16:
return prepareWord16(x)
case cadence.Word32:
return prepareWord32(x)
case cadence.Word64:
return prepareWord64(x)
case cadence.Fix64:
return prepareFix64(x)
case cadence.UFix64:
return prepareUFix64(x)
case cadence.Array:
return prepareArray(x)
case cadence.Dictionary:
return prepareDictionary(x)
case cadence.Struct:
return prepareStruct(x)
case cadence.Resource:
return prepareResource(x)
case cadence.Event:
return prepareEvent(x)
case cadence.Contract:
return prepareContract(x)
case cadence.Link:
return prepareLink(x)
case cadence.Path:
return preparePath(x)
case cadence.TypeValue:
return prepareTypeValue(x)
case cadence.Capability:
return prepareCapability(x)
case cadence.Enum:
return prepareEnum(x)
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 interface{}
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 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 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 prepareComposite(kind, id string, fieldTypes []cadence.Field, fields []cadence.Value) jsonValue {
nonFunctionFieldTypes := make([]cadence.Field, 0)
for _, field := range fieldTypes {
if _, ok := field.Type.(*cadence.FunctionType); !ok {
nonFunctionFieldTypes = append(nonFunctionFieldTypes, field)
}
}
if len(nonFunctionFieldTypes) != len(fields) {
panic(fmt.Errorf(
"%s field count (%d) does not match declared type (%d)",
kind,
len(fields),
len(nonFunctionFieldTypes),
))
}
compositeFields := make([]jsonCompositeField, len(fields))
for i, value := range fields {
fieldType := nonFunctionFieldTypes[i]
compositeFields[i] = jsonCompositeField{
Name: fieldType.Identifier,
Value: Prepare(value),
}
}
return jsonValueObject{
Type: kind,
Value: jsonCompositeValue{
ID: id,
Fields: compositeFields,
},
}
}
func prepareLink(x cadence.Link) jsonValue {
return jsonValueObject{
Type: linkTypeStr,
Value: jsonLinkValue{
TargetPath: preparePath(x.TargetPath),
BorrowType: x.BorrowType,
},
}
}
func preparePath(x cadence.Path) jsonValue {
return jsonValueObject{
Type: pathTypeStr,
Value: jsonPathValue{
Domain: x.Domain,
Identifier: x.Identifier,
},
}
}
func prepareParameterType(parameterType cadence.Parameter, results typeResults) jsonParameterType {
return jsonParameterType{
Label: parameterType.Label,
Id: parameterType.Identifier,
Type: prepareType(parameterType.Type, results),
}
}
func prepareFieldType(fieldType cadence.Field, results typeResults) jsonFieldType {
return jsonFieldType{
Id: fieldType.Identifier,
Type: prepareType(fieldType.Type, results),
}
}
func prepareFields(fieldTypes []cadence.Field, results typeResults) []jsonFieldType {
fields := make([]jsonFieldType, 0)
for _, field := range fieldTypes {
fields = append(fields, prepareFieldType(field, results))
}
return fields
}
func prepareParameters(parameterTypes []cadence.Parameter, results typeResults) []jsonParameterType {
parameters := make([]jsonParameterType, 0)
for _, param := range parameterTypes {
parameters = append(parameters, prepareParameterType(param, results))
}
return parameters
}
func prepareInitializers(initializerTypes [][]cadence.Parameter, results typeResults) [][]jsonParameterType {
initializers := make([][]jsonParameterType, 0)
for _, params := range initializerTypes {
initializers = append(initializers, prepareParameters(params, results))
}
return initializers
}
func prepareType(typ cadence.Type, results typeResults) 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.AnyType,
cadence.AnyStructType,
cadence.AnyResourceType,
cadence.AddressType,
cadence.MetaType,
cadence.VoidType,
cadence.NeverType,
cadence.BoolType,
cadence.StringType,
cadence.CharacterType,
cadence.BytesType,
cadence.NumberType,
cadence.SignedNumberType,
cadence.IntegerType,
cadence.SignedIntegerType,
cadence.FixedPointType,
cadence.SignedFixedPointType,
cadence.IntType,
cadence.Int8Type,
cadence.Int16Type,
cadence.Int32Type,
cadence.Int64Type,
cadence.Int128Type,
cadence.Int256Type,
cadence.UIntType,
cadence.UInt8Type,
cadence.UInt16Type,
cadence.UInt32Type,
cadence.UInt64Type,
cadence.UInt128Type,
cadence.UInt256Type,
cadence.Word8Type,
cadence.Word16Type,
cadence.Word32Type,
cadence.Word64Type,
cadence.Fix64Type,
cadence.UFix64Type,
cadence.BlockType,
cadence.PathType,
cadence.CapabilityPathType,
cadence.StoragePathType,
cadence.PublicPathType,
cadence.PrivatePathType,
cadence.AccountKeyType,
cadence.AuthAccountContractsType,
cadence.AuthAccountKeysType,
cadence.AuthAccountType,
cadence.PublicAccountContractsType,
cadence.PublicAccountKeysType,
cadence.PublicAccountType,
cadence.DeployedContractType:
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.StructType:
return jsonNominalType{
Kind: "Struct",
Type: "",
TypeID: string(typ.Location.TypeID(nil, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.ResourceType:
return jsonNominalType{
Kind: "Resource",
Type: "",
TypeID: string(typ.Location.TypeID(nil, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.EventType:
return jsonNominalType{
Kind: "Event",
Type: "",
TypeID: string(typ.Location.TypeID(nil, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: [][]jsonParameterType{prepareParameters(typ.Initializer, results)},
}
case *cadence.ContractType:
return jsonNominalType{
Kind: "Contract",
Type: "",
TypeID: string(typ.Location.TypeID(nil, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.StructInterfaceType:
return jsonNominalType{
Kind: "StructInterface",
Type: "",
TypeID: string(typ.Location.TypeID(nil, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.ResourceInterfaceType:
return jsonNominalType{
Kind: "ResourceInterface",
Type: "",
TypeID: string(typ.Location.TypeID(nil, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.ContractInterfaceType:
return jsonNominalType{
Kind: "ContractInterface",
Type: "",
TypeID: string(typ.Location.TypeID(nil, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
}
case *cadence.FunctionType:
return jsonFunctionType{
Kind: "Function",
TypeID: typ.ID(),
Return: prepareType(typ.ReturnType, results),
Parameters: prepareParameters(typ.Parameters, results),
}
case cadence.ReferenceType:
return jsonReferenceType{
Kind: "Reference",
Authorized: typ.Authorized,
Type: prepareType(typ.Type, results),
}
case *cadence.RestrictedType:
restrictions := make([]jsonValue, 0)
for _, restriction := range typ.Restrictions {
restrictions = append(restrictions, prepareType(restriction, results))
}
return jsonRestrictedType{
Kind: "Restriction",
TypeID: typ.ID(),
Type: prepareType(typ.Type, results),
Restrictions: restrictions,
}
case cadence.CapabilityType:
return jsonUnaryType{
Kind: "Capability",
Type: prepareType(typ.BorrowType, results),
}
case *cadence.EnumType:
return jsonNominalType{
Kind: "Enum",
TypeID: string(typ.Location.TypeID(nil, typ.QualifiedIdentifier)),
Fields: prepareFields(typ.Fields, results),
Initializers: prepareInitializers(typ.Initializers, results),
Type: prepareType(typ.RawType, results),
}
case nil:
return ""
default:
panic(fmt.Errorf("unsupported type: %T, %v", typ, typ))
}
}
type typeResults map[cadence.Type]struct{}
func prepareTypeValue(typeValue cadence.TypeValue) jsonValue {
return jsonValueObject{
Type: typeTypeStr,
Value: jsonTypeValue{
StaticType: prepareType(typeValue.StaticType, typeResults{}),
},
}
}
func prepareCapability(capability cadence.Capability) jsonValue {
return jsonValueObject{
Type: capabilityTypeStr,
Value: jsonCapabilityValue{
Path: preparePath(capability.Path),
Address: encodeBytes(capability.Address.Bytes()),
BorrowType: prepareType(capability.BorrowType, typeResults{}),
},
}
}
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.WriteRune('-')
}
}
builder.WriteString(fmt.Sprintf(
"%d.%08d",
integer,
fraction,
))
return builder.String()
}
func encodeUFix64(v uint64) string {
integer := v / sema.Fix64Factor
fraction := v % sema.Fix64Factor
return fmt.Sprintf(
"%d.%08d",
integer,
fraction,
)
}