-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecoder.go
69 lines (66 loc) · 1.41 KB
/
decoder.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
package cadenceDecoder
import (
"github.com/onflow/cadence"
)
// Decode decode cadence to json
func Decode(value cadence.Value) (any, error) {
var err error
switch value := value.(type) {
case cadence.Array:
data := make([]any, len(value.Values))
for i := range value.Values {
data[i], err = Decode(value.Values[i])
if err != nil {
return data, err
}
}
return data, nil
case cadence.Optional:
return Decode(value.Value)
case cadence.Struct:
data := make(map[string]any)
for i := range value.StructType.Fields {
v, err := Decode(value.Fields[i])
if err != nil {
return data, err
}
if v != nil {
data[value.StructType.Fields[i].Identifier] = v
}
}
return data, nil
case cadence.Dictionary:
data := make(map[string]any)
for i := range value.Pairs {
v, err := Decode(value.Pairs[i].Value)
if err != nil {
return data, err
}
if v != nil {
data[replaceBothSideMarks(value.Pairs[i].Key.String())] = v
}
}
return data, nil
case cadence.Address:
return value.String(), nil
case cadence.String:
return replaceBothSideMarks(value.ToGoValue().(string)), nil
default:
if value == nil {
return nil, nil
}
return value.ToGoValue(), nil
}
}
func replaceBothSideMarks(data string) string {
if len(data) < 1 {
return ""
}
if data[0] == '"' {
data = data[1:]
}
if data[len(data)-1] == '"' {
data = data[:len(data)-1]
}
return data
}