2022-12-01 09:19:32 +00:00
|
|
|
package walletevent
|
2019-06-14 10:16:30 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/event"
|
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2020-01-02 09:10:19 +00:00
|
|
|
|
2019-06-14 10:16:30 +00:00
|
|
|
"github.com/status-im/status-go/signal"
|
|
|
|
)
|
|
|
|
|
2022-12-01 09:19:32 +00:00
|
|
|
type Publisher interface {
|
2019-06-14 10:16:30 +00:00
|
|
|
Subscribe(interface{}) event.Subscription
|
|
|
|
}
|
|
|
|
|
|
|
|
// SignalsTransmitter transmits received events as wallet signals.
|
|
|
|
type SignalsTransmitter struct {
|
2022-12-01 09:19:32 +00:00
|
|
|
Publisher
|
2019-06-14 10:16:30 +00:00
|
|
|
|
|
|
|
wg sync.WaitGroup
|
|
|
|
quit chan struct{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start runs loop in background.
|
|
|
|
func (tmr *SignalsTransmitter) Start() error {
|
|
|
|
if tmr.quit != nil {
|
2020-08-18 08:44:56 +00:00
|
|
|
// already running, nothing to do
|
|
|
|
return nil
|
2019-06-14 10:16:30 +00:00
|
|
|
}
|
|
|
|
tmr.quit = make(chan struct{})
|
2022-12-01 09:19:32 +00:00
|
|
|
events := make(chan Event, 10)
|
|
|
|
sub := tmr.Publisher.Subscribe(events)
|
2019-06-14 10:16:30 +00:00
|
|
|
|
|
|
|
tmr.wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer tmr.wg.Done()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-tmr.quit:
|
|
|
|
sub.Unsubscribe()
|
|
|
|
return
|
|
|
|
case err := <-sub.Err():
|
|
|
|
// technically event.Feed cannot send an error to subscription.Err channel.
|
|
|
|
// the only time we will get an event is when that channel is closed.
|
|
|
|
if err != nil {
|
|
|
|
log.Error("wallet signals transmitter failed with", "error", err)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
case event := <-events:
|
2023-10-09 12:43:53 +00:00
|
|
|
if !event.Type.IsInternal() {
|
|
|
|
signal.SendWalletEvent(event)
|
|
|
|
}
|
2019-06-14 10:16:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop stops the loop and waits till it exits.
|
|
|
|
func (tmr *SignalsTransmitter) Stop() {
|
|
|
|
if tmr.quit == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
close(tmr.quit)
|
|
|
|
tmr.wg.Wait()
|
|
|
|
tmr.quit = nil
|
|
|
|
}
|