Skip to content

Commit 5a41ac4

Browse files
committed
simplify seawatcher
1 parent b53a78d commit 5a41ac4

File tree

3 files changed

+51
-100
lines changed

3 files changed

+51
-100
lines changed

internal/collections/collectiondb.go

+11
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,17 @@ func (cs *CollectionDB) OpenseaSlugsAndAddresses() map[string]common.Address {
4545
return slugAddresses
4646
}
4747

48+
// OpenseaSlugs returns a slice of slugs for collections with enabled listings.
49+
func (cs *CollectionDB) GetCollectionForSlug(slug string) *Collection {
50+
for _, c := range cs.Collections {
51+
if c.OpenseaSlug == slug {
52+
return c
53+
}
54+
}
55+
56+
return nil
57+
}
58+
4859
// OpenseaSlugs returns a slice of slugs for collections with enabled listings.
4960
func (cs *CollectionDB) OpenseaAddressToSlug() map[common.Address]string {
5061
// slugs := make([]string, 0)

internal/seawa/seawatcher.go

+39-90
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"fmt"
88
"math"
99
"net/url"
10-
"strings"
1110
"sync"
1211
"time"
1312

@@ -40,7 +39,8 @@ type SeaWatcher struct {
4039
channels map[string]*phx.Channel
4140

4241
// subscribed slugs/events
43-
subscriptions map[osmodels.EventType]map[string]func()
42+
// subscriptions map[osmodels.EventType]map[string]func()
43+
subscriptions map[string]map[osmodels.EventType]func()
4444

4545
// redis client
4646
rdb rueidis.Client
@@ -51,9 +51,7 @@ type SeaWatcher struct {
5151
}
5252

5353
var (
54-
// topX = map[string]*models.Bid{}.
55-
56-
AvailableEventTypes = []osmodels.EventType{osmodels.ItemListed, osmodels.ItemReceivedBid, osmodels.ItemMetadataUpdated} // , osmodels.CollectionOffer} //, osmodels.ItemMetadataUpdated} // ItemMetadataUpdated, ItemCancelled
54+
availableEventTypes = []osmodels.EventType{osmodels.ItemListed, osmodels.ItemReceivedBid, osmodels.ItemMetadataUpdated} // , osmodels.CollectionOffer} //, osmodels.ItemMetadataUpdated} // ItemMetadataUpdated, ItemCancelled
5755

5856
eventsReceivedTotal = promauto.NewCounter(prometheus.CounterOpts{
5957
Name: "gloomberg_oswatcher_events_received_total",
@@ -80,13 +78,11 @@ func NewSeaWatcher(apiToken string, gb *gloomberg.Gloomberg) *SeaWatcher {
8078

8179
client := &SeaWatcher{
8280
receivedEvents: make(chan map[string]interface{}, 1024),
83-
subscriptions: make(map[osmodels.EventType]map[string]func(), 0),
81+
subscriptions: make(map[string]map[osmodels.EventType]func(), 0),
8482

85-
// phoenixSocket: socket,
8683
channels: make(map[string]*phx.Channel),
8784

88-
gb: gb,
89-
// rdb: rdb,
85+
gb: gb,
9086
rdb: gb.Rdb,
9187

9288
mu: &sync.Mutex{},
@@ -118,11 +114,6 @@ func NewSeaWatcher(apiToken string, gb *gloomberg.Gloomberg) *SeaWatcher {
118114
}
119115
})
120116

121-
// create subscriptions map/registry
122-
for _, event := range AvailableEventTypes {
123-
client.subscriptions[event] = make(map[string]func(), 0)
124-
}
125-
126117
if client.phoenixSocket != nil {
127118
if err := client.connect(); err != nil {
128119
socketError := errors.New("opensea stream socket connection failed: " + err.Error())
@@ -149,7 +140,7 @@ func (sw *SeaWatcher) EventChannel() chan map[string]interface{} {
149140
return sw.receivedEvents
150141
}
151142

152-
func (sw *SeaWatcher) ActiveSubscriptions() map[osmodels.EventType]map[string]func() {
143+
func (sw *SeaWatcher) ActiveSubscriptions() map[string]map[osmodels.EventType]func() {
153144
return sw.subscriptions
154145
}
155146

@@ -289,85 +280,65 @@ func (sw *SeaWatcher) DecodeCollectionOfferEvent(itemEvent map[string]interface{
289280
return collectionOfferEvent, err
290281
}
291282

292-
// func printItemReceivedOfferEvent(itemOfferEvent osmodels.ItemReceivedOfferEvent) {
293-
// priceWeiRaw, _, err := big.ParseFloat(itemOfferEvent.Payload.BasePrice, 10, 64, big.ToNearestEven)
294-
// if err != nil {
295-
// log.Infof("⚓️❌ werror parsing price: %+v | %s", itemOfferEvent.Payload.BasePrice, err.Error())
296-
297-
// return
298-
// }
299-
// priceWei, _ := priceWeiRaw.Int(nil)
300-
301-
// // nftID is a identification string in the format <chain>/<contract>/<tokenID>
302-
// nftID := strings.Split(itemOfferEvent.Payload.Item.NftID, "/")
303-
// if len(nftID) != 3 {
304-
// log.Infof("⚓️ 🤷‍♀️ error parsing nftID: %s", itemOfferEvent.Payload.Item.NftID)
305-
306-
// return
307-
// }
308-
// eventType := osmodels.TxType[itemOfferEvent.StreamEvent]
309-
// collectionPrimaryStyle := lipgloss.NewStyle().Foreground(style.GenerateColorWithSeed(common.HexToAddress(nftID[1]).Hash().Big().Int64())).Bold(true)
310-
// collectionSecondaryStyle := lipgloss.NewStyle().Foreground(style.GenerateColorWithSeed(common.HexToAddress(nftID[1]).Big().Int64() ^ 2)).Bold(true)
311-
// // get tokenID
312-
// tID, _, _ := big.ParseFloat(nftID[2], 10, 64, big.ToNearestEven)
313-
// tokenID, _ := tID.Int(nil)
314-
// fmtTokenID := style.ShortenedTokenIDStyled(tokenID, collectionPrimaryStyle, collectionSecondaryStyle)
315-
// // for erc1155 tokens itemOfferEvent.Payload.Item.Metadata.Name is the item name
316-
// collectionName := strings.Split(itemOfferEvent.Payload.Item.Metadata.Name, " #")[0]
317-
// fmtToken := style.BoldStyle.Render(fmt.Sprintf("%s %s", collectionPrimaryStyle.Render(collectionName), fmtTokenID))
318-
// fmt.Println(itemOfferEvent.StreamEvent)
319-
// log.Infof("⚓️ %s | %sΞ %s ", eventType.Icon(), style.BoldStyle.Render(fmt.Sprintf("%5.3f", price.NewPrice(priceWei).Ether())), style.TerminalLink(itemOfferEvent.Payload.Item.Permalink, fmtToken))
320-
// }
321-
322-
func (sw *SeaWatcher) SubscribeForSlug(eventType osmodels.EventType, slug string) bool {
283+
func (sw *SeaWatcher) SubscribeForSlug(slug string) bool {
323284
sw.mu.Lock()
324-
alreadySubscribed := sw.subscriptions[eventType][slug]
285+
alreadySubscribed := sw.subscriptions[slug]
325286

326287
if alreadySubscribed != nil {
327288
sw.mu.Unlock()
328289

329-
log.Debugf("⚓️ ☕️ already subscribed to %s for %s", eventType, slug)
290+
log.Debugf("⚓️ ☕️ already subscribed to opensea events for %s", slug)
330291

331292
return false
332293
}
333294

334-
sw.subscriptions[eventType][slug] = sw.on(eventType, slug, sw.eventHandler)
295+
sw.subscriptions[slug] = make(map[osmodels.EventType]func())
296+
297+
for _, eventType := range availableEventTypes {
298+
sw.subscriptions[slug][eventType] = sw.on(eventType, slug, sw.eventHandler)
299+
}
335300
sw.mu.Unlock()
336301

302+
if collection := sw.gb.CollectionDB.GetCollectionForSlug(slug); collection != nil {
303+
log.Debugf("⏮️ resetting stats for %s", slug)
304+
305+
collection.ResetStats()
306+
}
307+
337308
return true
338309
}
339310

340-
func (sw *SeaWatcher) UnubscribeForSlug(eventType osmodels.EventType, slug string) bool {
311+
func (sw *SeaWatcher) UnubscribeForSlug(slug string) bool {
341312
sw.mu.Lock()
342-
unsubscribe := sw.subscriptions[eventType][slug]
313+
slugSubscriptions := sw.subscriptions[slug]
343314
sw.mu.Unlock()
344315

345-
if unsubscribe != nil {
316+
if slugSubscriptions != nil {
346317
// unsubscribe
347-
unsubscribe()
318+
for _, unsubscribe := range slugSubscriptions {
319+
unsubscribe()
320+
}
348321

349322
// remove slug
350323
sw.mu.Lock()
351-
sw.subscriptions[eventType][slug] = nil
324+
sw.subscriptions[slug] = nil
352325
sw.mu.Unlock()
353326

354327
return true
355328
}
356329

357-
log.Debugf("☕️ not subscribed to %s for %s (anymore)", eventType, slug)
330+
log.Debugf("unsubscribed %s from opense events", slug)
358331

359332
return false
360333
}
361334

362335
func (sw *SeaWatcher) IsSubscribed(slug string) bool {
363-
for _, eventType := range AvailableEventTypes {
364-
sw.mu.Lock()
365-
alreadySubscribed, ok := sw.subscriptions[eventType][slug]
366-
sw.mu.Unlock()
336+
sw.mu.Lock()
337+
alreadySubscribed, ok := sw.subscriptions[slug]
338+
sw.mu.Unlock()
367339

368-
if ok && alreadySubscribed != nil {
369-
return true
370-
}
340+
if ok && alreadySubscribed != nil {
341+
return true
371342
}
372343

373344
return false
@@ -466,7 +437,7 @@ func (sw *SeaWatcher) Run() {
466437
return
467438
}
468439

469-
var action func(event osmodels.EventType, slug string) bool
440+
var action func(slug string) bool
470441

471442
switch mgmtEvent.Action {
472443
case models.Subscribe:
@@ -475,20 +446,6 @@ func (sw *SeaWatcher) Run() {
475446
action = sw.UnubscribeForSlug
476447
}
477448

478-
// transform to string
479-
var events []string
480-
for _, event := range AvailableEventTypes {
481-
events = append(events, string(event))
482-
}
483-
484-
// subscribe to which events?
485-
if len(mgmtEvent.Events) == 0 {
486-
// subscribe to all available events if none are specified
487-
sw.Prf("no events specified, subscribing to all available events (%+v)", strings.Join(events, ", "))
488-
489-
mgmtEvent.Events = AvailableEventTypes
490-
}
491-
492449
newSubscriptions := make(map[string][]osmodels.EventType, 0)
493450
newEventSubscriptions := 0
494451

@@ -499,26 +456,18 @@ func (sw *SeaWatcher) Run() {
499456
continue
500457
}
501458

502-
for _, event := range mgmtEvent.Events {
503-
if action(event, slug) {
504-
newEventSubscriptions++
505-
506-
if _, ok := newSubscriptions[slug]; !ok {
507-
newSubscriptions[slug] = make([]osmodels.EventType, 0)
508-
}
509-
510-
newSubscriptions[slug] = append(newSubscriptions[slug], event)
459+
if action(slug) {
460+
newEventSubscriptions++
511461

512-
time.Sleep(257 * time.Millisecond)
513-
}
462+
time.Sleep(337 * time.Millisecond)
514463
}
515464
}
516465

517466
sw.Prf(
518-
"successfully subscribed to %s new collections/slugs (%d events in total) | total subscriptions: %s",
467+
"successfully subscribed to %s new collections/slugs (%d events in total) | total subscribed collections: %s",
519468
style.AlmostWhiteStyle.Render(fmt.Sprint(len(newSubscriptions))),
520469
newEventSubscriptions,
521-
style.AlmostWhiteStyle.Render(fmt.Sprint(len(sw.ActiveSubscriptions()[osmodels.ItemListed]))),
470+
style.AlmostWhiteStyle.Render(fmt.Sprint(len(sw.ActiveSubscriptions()))),
522471
)
523472

524473
default:

internal/trapri/trapri.go

+1-10
Original file line numberDiff line numberDiff line change
@@ -677,22 +677,13 @@ func formatTokenTransaction(gb *gloomberg.Gloomberg, seawa *seawatcher.SeaWatche
677677

678678
//
679679
// auto-subscribe to opensea events after X sales
680-
681680
if autoSubscribeAfterSales := viper.GetUint64("opensea.auto_subscribe_after_sales"); currentCollection.Counters.Sales == autoSubscribeAfterSales {
682681
if currentCollection.OpenseaSlug == "" {
683682
currentCollection.OpenseaSlug = opensea.GetCollectionSlug(currentCollection.ContractAddress)
684683
}
685684

686685
if !seawa.IsSubscribed(currentCollection.OpenseaSlug) {
687-
subscribedTo := make([]string, 0)
688-
for _, eventType := range seawatcher.AvailableEventTypes {
689-
if seawa.SubscribeForSlug(eventType, currentCollection.OpenseaSlug) {
690-
subscribedTo = append(subscribedTo, string(eventType))
691-
}
692-
}
693-
694-
if len(subscribedTo) > 0 {
695-
currentCollection.ResetStats()
686+
if seawa.SubscribeForSlug(currentCollection.OpenseaSlug) {
696687
seawa.Pr(fmt.Sprintf("auto-subscribed to events for %s (after %d sales) | stats resetted", style.AlmostWhiteStyle.Render(currentCollection.OpenseaSlug), autoSubscribeAfterSales))
697688
}
698689
}

0 commit comments

Comments
 (0)