github.com/status-im/status-go@v1.1.0/services/wallet/connection/status_notifier.go (about)

     1  package connection
     2  
     3  import (
     4  	"encoding/json"
     5  	"sync"
     6  	"time"
     7  
     8  	"github.com/ethereum/go-ethereum/common"
     9  	"github.com/ethereum/go-ethereum/event"
    10  	"github.com/status-im/status-go/services/wallet/walletevent"
    11  )
    12  
    13  // Client expects a single event with all states
    14  type StatusNotification map[string]State // id -> State
    15  
    16  type StatusNotifier struct {
    17  	statuses  *sync.Map // id -> Status
    18  	eventType walletevent.EventType
    19  	feed      *event.Feed
    20  }
    21  
    22  func NewStatusNotifier(statuses *sync.Map, eventType walletevent.EventType, feed *event.Feed) *StatusNotifier {
    23  	n := StatusNotifier{
    24  		statuses:  statuses,
    25  		eventType: eventType,
    26  		feed:      feed,
    27  	}
    28  
    29  	statuses.Range(func(_, value interface{}) bool {
    30  		value.(*Status).SetStateChangeCb(n.notify)
    31  		return true
    32  	})
    33  
    34  	return &n
    35  }
    36  
    37  func (n *StatusNotifier) notify(state State) {
    38  	// state is ignored, as client expects all valid states in
    39  	// a single event, so we fetch them from the map
    40  	if n.feed != nil {
    41  		statusMap := make(StatusNotification)
    42  		n.statuses.Range(func(id, value interface{}) bool {
    43  			state := value.(*Status).GetState()
    44  			if state.Value == StateValueUnknown {
    45  				return true
    46  			}
    47  			statusMap[id.(string)] = state
    48  			return true
    49  		})
    50  
    51  		encodedMessage, err := json.Marshal(statusMap)
    52  		if err != nil {
    53  			return
    54  		}
    55  
    56  		n.feed.Send(walletevent.Event{
    57  			Type:     n.eventType,
    58  			Accounts: []common.Address{},
    59  			Message:  string(encodedMessage),
    60  			At:       time.Now().Unix(),
    61  		})
    62  	}
    63  }