-
Notifications
You must be signed in to change notification settings - Fork 170
/
service_event.go
73 lines (64 loc) · 1.48 KB
/
service_event.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
package flow
import (
"encoding/json"
"fmt"
)
const (
ServiceEventSetup = "setup"
ServiceEventCommit = "commit"
)
// ServiceEvent represents a service event, which is a special event that when
// emitted from a service account smart contract, is propagated to the protocol
// and included in blocks. Service events typically cause changes to the
// protocol state. See EpochSetup and EpochCommit events in this package for examples.
//
// This type represents a generic service event and primarily exists to simplify
// encoding and decoding.
type ServiceEvent struct {
Type string
Event interface{}
}
func (se *ServiceEvent) UnmarshalJSON(b []byte) error {
var enc map[string]interface{}
err := json.Unmarshal(b, &enc)
if err != nil {
return err
}
tp, ok := enc["Type"].(string)
if !ok {
return fmt.Errorf("missing type key")
}
ev, ok := enc["Event"]
if !ok {
return fmt.Errorf("missing event key")
}
// re-marshal the event, we'll unmarshal it into the appropriate type
evb, err := json.Marshal(ev)
if err != nil {
return err
}
var event interface{}
switch tp {
case ServiceEventSetup:
setup := new(EpochSetup)
err = json.Unmarshal(evb, setup)
if err != nil {
return err
}
event = setup
case ServiceEventCommit:
commit := new(EpochCommit)
err = json.Unmarshal(evb, commit)
if err != nil {
return err
}
event = commit
default:
return fmt.Errorf("invalid type: %s", tp)
}
*se = ServiceEvent{
Type: tp,
Event: event,
}
return nil
}