code.vegaprotocol.io/vega@v0.79.0/datanode/sqlsubscribers/trades.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package sqlsubscribers 17 18 import ( 19 "context" 20 "time" 21 22 "code.vegaprotocol.io/vega/core/events" 23 "code.vegaprotocol.io/vega/datanode/entities" 24 types "code.vegaprotocol.io/vega/protos/vega" 25 26 "github.com/pkg/errors" 27 ) 28 29 type TradeEvent interface { 30 events.Event 31 Trade() types.Trade 32 } 33 34 type TradesStore interface { 35 Add(*entities.Trade) error 36 Flush(ctx context.Context) error 37 } 38 39 type TradeSubscriber struct { 40 subscriber 41 store TradesStore 42 } 43 44 func NewTradesSubscriber(store TradesStore) *TradeSubscriber { 45 return &TradeSubscriber{ 46 store: store, 47 } 48 } 49 50 func (ts *TradeSubscriber) Types() []events.Type { 51 return []events.Type{events.TradeEvent} 52 } 53 54 func (ts *TradeSubscriber) Flush(ctx context.Context) error { 55 return ts.store.Flush(ctx) 56 } 57 58 func (ts *TradeSubscriber) Push(ctx context.Context, evt events.Event) error { 59 return ts.consume(evt.(TradeEvent)) 60 } 61 62 func (ts *TradeSubscriber) consume(te TradeEvent) error { 63 trade := te.Trade() 64 return errors.Wrap(ts.addTrade(&trade, entities.TxHash(te.TxHash()), ts.vegaTime, te.Sequence()), "failed to consume trade") 65 } 66 67 func (ts *TradeSubscriber) addTrade(t *types.Trade, txHash entities.TxHash, vegaTime time.Time, blockSeqNumber uint64) error { 68 trade, err := entities.TradeFromProto(t, txHash, vegaTime, blockSeqNumber) 69 if err != nil { 70 return errors.Wrap(err, "converting event to trade") 71 } 72 73 return errors.Wrap(ts.store.Add(trade), "adding trade to store") 74 } 75 76 func (ts *TradeSubscriber) Name() string { 77 return "TradeSubscriber" 78 }