/
events_mediation.go
77 lines (66 loc) · 1.91 KB
/
events_mediation.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
package web3
import (
"context"
"github.com/bacalhau-project/lilypad/pkg/system"
"github.com/bacalhau-project/lilypad/pkg/web3/bindings/mediation"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/event"
"github.com/rs/zerolog/log"
)
type MediationEventChannels struct {
mediationRequestedChan chan *mediation.MediationMediationRequested
mediationRequestedSubs []func(mediation.MediationMediationRequested)
}
func NewMediationEventChannels() *MediationEventChannels {
return &MediationEventChannels{
mediationRequestedChan: make(chan *mediation.MediationMediationRequested),
}
}
func (m *MediationEventChannels) Start(
sdk *Web3SDK,
ctx context.Context,
cm *system.CleanupManager,
) error {
blockNumber, err := sdk.getBlockNumber()
if err != nil {
return err
}
var mediationRequestedSub event.Subscription
connectMediationRequestedSub := func() (event.Subscription, error) {
log.Debug().
Str("mediation->connect", "MediationRequested").
Msgf("")
return sdk.Contracts.Mediation.WatchMediationRequested(
&bind.WatchOpts{Start: &blockNumber, Context: ctx},
m.mediationRequestedChan,
)
}
mediationRequestedSub, err = connectMediationRequestedSub()
if err != nil {
return err
}
go func() {
<-ctx.Done()
mediationRequestedSub.Unsubscribe()
}()
for {
select {
case event := <-m.mediationRequestedChan:
log.Debug().
Str("mediation->event", "MediationRequested").
Msgf("%+v", event)
for _, handler := range m.mediationRequestedSubs {
go handler(*event)
}
case err := <-mediationRequestedSub.Err():
mediationRequestedSub.Unsubscribe()
mediationRequestedSub, err = connectMediationRequestedSub()
if err != nil {
return err
}
}
}
}
func (m *MediationEventChannels) SubscribeMediationRequested(handler func(mediation.MediationMediationRequested)) {
m.mediationRequestedSubs = append(m.mediationRequestedSubs, handler)
}