forked from crypto-com/chain-indexing
/
txs_results_log_event.go
82 lines (65 loc) · 2.01 KB
/
txs_results_log_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
74
75
76
77
78
79
80
81
82
package utils
import (
"fmt"
"github.com/WilliamXieCrypto/chain-indexing/usecase/model"
)
// ParsedTxsResultLogEvent is only usable in txs_results log because it has unique attribute key.
// For txs_results.events, begin_block_events, end_block_events, they have to be parsed manually.
type ParsedTxsResultLogEvent struct {
keyIndex map[string]int
rawEvent model.BlockResultsEvent
}
func NewParsedTxsResultLogEvent(rawEvent *model.BlockResultsEvent) *ParsedTxsResultLogEvent {
event := &ParsedTxsResultLogEvent{
make(map[string]int),
*rawEvent,
}
for i, attribute := range rawEvent.Attributes {
if event.HasAttribute(attribute.Key) {
panic(fmt.Sprintf("duplciated attribute key `%s`", attribute.Key))
}
event.keyIndex[attribute.Key] = i
}
return event
}
// In the txs_results log, multiple event of the same types are grouped
// together into single event. This method pars txs_results log and split into
// a new event when a same key name appears.
func NewParsedTxsResultLogEventsSplitByKey(
rawEvent *model.BlockResultsEvent,
) []ParsedTxsResultLogEvent {
events := make([]ParsedTxsResultLogEvent, 0)
event := ParsedTxsResultLogEvent{
make(map[string]int),
*rawEvent,
}
for i, attribute := range rawEvent.Attributes {
if event.HasAttribute(attribute.Key) {
events = append(events, event)
event = ParsedTxsResultLogEvent{
make(map[string]int),
*rawEvent,
}
}
event.keyIndex[attribute.Key] = i
}
events = append(events, event)
return events
}
func (log *ParsedTxsResultLogEvent) HasAttribute(key string) bool {
_, ok := log.keyIndex[key]
return ok
}
func (log *ParsedTxsResultLogEvent) MustGetAttributeByKey(key string) string {
attr := log.GetAttributeByKey(key)
if attr == nil {
panic(fmt.Sprintf("expected block_results event to have attribute %s, but found none", key))
}
return *attr
}
func (log *ParsedTxsResultLogEvent) GetAttributeByKey(key string) *string {
if !log.HasAttribute(key) {
return nil
}
return &log.rawEvent.Attributes[log.keyIndex[key]].Value
}