code.vegaprotocol.io/vega@v0.79.0/core/events/bus.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 events
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  	"strconv"
    22  	"strings"
    23  
    24  	vgcontext "code.vegaprotocol.io/vega/libs/context"
    25  	eventspb "code.vegaprotocol.io/vega/protos/vega/events/v1"
    26  
    27  	"github.com/pkg/errors"
    28  )
    29  
    30  var ErrInvalidEventType = errors.New("invalid proto event type")
    31  
    32  type Type int
    33  
    34  // simple interface for event filtering on market ID.
    35  type marketFilterable interface {
    36  	Event
    37  	MarketID() string
    38  }
    39  
    40  // simple interface for event filtering on party ID.
    41  type partyFilterable interface {
    42  	Event
    43  	IsParty(id string) bool
    44  }
    45  
    46  // simple interface for event filtering by party and market ID.
    47  type marketPartyFilterable interface {
    48  	Event
    49  	MarketID() string
    50  	PartyID() string
    51  }
    52  
    53  // Base common denominator all event-bus events share.
    54  type Base struct {
    55  	ctx     context.Context
    56  	traceID string
    57  	chainID string
    58  	txHash  string
    59  	blockNr int64
    60  	seq     uint64
    61  	et      Type
    62  }
    63  
    64  // Event - the base event interface type, add sequence ID setter here, because the type assertions in broker
    65  // seem to be a bottleneck. Change its behaviour so as to only set the sequence ID once.
    66  type Event interface {
    67  	Type() Type
    68  	Context() context.Context
    69  	TraceID() string
    70  	TxHash() string
    71  	ChainID() string
    72  	Sequence() uint64
    73  	SetSequenceID(s uint64)
    74  	BlockNr() int64
    75  	StreamMessage() *eventspb.BusEvent
    76  	// used for events like ExpiredOrders. It is used to increment the sequence ID by the number of records
    77  	// this event will produce to ensure history tables using time + sequence number to function properly.
    78  	CompositeCount() uint64
    79  	Replace(context.Context)
    80  }
    81  
    82  const (
    83  	// All event type -> used by subscribers to just receive all events, has no actual corresponding event payload.
    84  	All Type = iota
    85  	// other event types that DO have corresponding event types.
    86  	TimeUpdate
    87  	LedgerMovementsEvent
    88  	PositionResolution
    89  	MarketEvent // this event is not used for any specific event, but by subscribers that aggregate all market events (e.g. for logging)
    90  	OrderEvent
    91  	LiquidityProvisionEvent
    92  	AccountEvent
    93  	PartyEvent
    94  	TradeEvent
    95  	MarginLevelsEvent
    96  	ProposalEvent
    97  	VoteEvent
    98  	MarketDataEvent
    99  	NodeSignatureEvent
   100  	LossSocializationEvent
   101  	SettlePositionEvent
   102  	SettleDistressedEvent
   103  	MarketCreatedEvent
   104  	MarketUpdatedEvent
   105  	AssetEvent
   106  	MarketTickEvent
   107  	AuctionEvent
   108  	WithdrawalEvent
   109  	DepositEvent
   110  	RiskFactorEvent
   111  	NetworkParameterEvent
   112  	TxErrEvent
   113  	OracleSpecEvent
   114  	OracleDataEvent
   115  	EpochUpdate
   116  	DelegationBalanceEvent
   117  	StakeLinkingEvent
   118  	ValidatorUpdateEvent
   119  	RewardPayoutEvent
   120  	CheckpointEvent
   121  	ValidatorScoreEvent
   122  	KeyRotationEvent
   123  	StateVarEvent
   124  	NetworkLimitsEvent
   125  	TransferEvent
   126  	ValidatorRankingEvent
   127  	ERC20MultiSigThresholdSetEvent
   128  	ERC20MultiSigSignerEvent
   129  	ERC20MultiSigSignerAddedEvent
   130  	ERC20MultiSigSignerRemovedEvent
   131  	PositionStateEvent
   132  	EthereumKeyRotationEvent
   133  	ProtocolUpgradeEvent
   134  	BeginBlockEvent
   135  	EndBlockEvent
   136  	ProtocolUpgradeStartedEvent
   137  	SettleMarketEvent
   138  	TransactionResultEvent
   139  	CoreSnapshotEvent
   140  	ProtocolUpgradeDataNodeReadyEvent
   141  	DistressedOrdersClosedEvent
   142  	ExpiredOrdersEvent
   143  	DistressedPositionsEvent
   144  	SpotLiquidityProvisionEvent
   145  	StopOrderEvent
   146  	FundingPeriodEvent
   147  	FundingPeriodDataPointEvent
   148  	TeamCreatedEvent
   149  	TeamUpdatedEvent
   150  	RefereeSwitchedTeamEvent
   151  	RefereeJoinedTeamEvent
   152  	ReferralProgramStartedEvent
   153  	ReferralProgramEndedEvent
   154  	ReferralProgramUpdatedEvent
   155  	ReferralSetCreatedEvent
   156  	RefereeJoinedReferralSetEvent
   157  	PartyActivityStreakEvent
   158  	VolumeDiscountProgramStartedEvent
   159  	VolumeDiscountProgramEndedEvent
   160  	VolumeDiscountProgramUpdatedEvent
   161  	ReferralSetStatsUpdatedEvent
   162  	VestingStatsUpdatedEvent
   163  	VolumeDiscountStatsUpdatedEvent
   164  	FeesStatsEvent
   165  	FundingPaymentsEvent
   166  	PaidLiquidityFeesStatsEvent
   167  	VestingBalancesSummaryEvent
   168  	TransferFeesEvent
   169  	TransferFeesDiscountUpdatedEvent
   170  	PartyMarginModeUpdatedEvent
   171  	PartyProfileUpdatedEvent
   172  	TeamsStatsUpdatedEvent
   173  	TimeWeightedNotionalPositionUpdatedEvent
   174  	CancelledOrdersEvent
   175  	GameScoresEvent
   176  	AMMPoolEvent
   177  	VolumeRebateProgramStartedEvent
   178  	VolumeRebateProgramEndedEvent
   179  	VolumeRebateProgramUpdatedEvent
   180  	VolumeRebateStatsUpdatedEvent
   181  	AutomatedPurchaseAnnouncedEvent
   182  )
   183  
   184  var (
   185  	marketEvents = []Type{
   186  		PositionResolution,
   187  		MarketCreatedEvent,
   188  		MarketUpdatedEvent,
   189  		MarketTickEvent,
   190  		AuctionEvent,
   191  	}
   192  
   193  	protoMap = map[eventspb.BusEventType]Type{
   194  		eventspb.BusEventType_BUS_EVENT_TYPE_ALL:                                     All,
   195  		eventspb.BusEventType_BUS_EVENT_TYPE_TIME_UPDATE:                             TimeUpdate,
   196  		eventspb.BusEventType_BUS_EVENT_TYPE_LEDGER_MOVEMENTS:                        LedgerMovementsEvent,
   197  		eventspb.BusEventType_BUS_EVENT_TYPE_POSITION_RESOLUTION:                     PositionResolution,
   198  		eventspb.BusEventType_BUS_EVENT_TYPE_MARKET:                                  MarketEvent,
   199  		eventspb.BusEventType_BUS_EVENT_TYPE_ORDER:                                   OrderEvent,
   200  		eventspb.BusEventType_BUS_EVENT_TYPE_ACCOUNT:                                 AccountEvent,
   201  		eventspb.BusEventType_BUS_EVENT_TYPE_PARTY:                                   PartyEvent,
   202  		eventspb.BusEventType_BUS_EVENT_TYPE_TRADE:                                   TradeEvent,
   203  		eventspb.BusEventType_BUS_EVENT_TYPE_MARGIN_LEVELS:                           MarginLevelsEvent,
   204  		eventspb.BusEventType_BUS_EVENT_TYPE_PROPOSAL:                                ProposalEvent,
   205  		eventspb.BusEventType_BUS_EVENT_TYPE_VOTE:                                    VoteEvent,
   206  		eventspb.BusEventType_BUS_EVENT_TYPE_MARKET_DATA:                             MarketDataEvent,
   207  		eventspb.BusEventType_BUS_EVENT_TYPE_NODE_SIGNATURE:                          NodeSignatureEvent,
   208  		eventspb.BusEventType_BUS_EVENT_TYPE_LOSS_SOCIALIZATION:                      LossSocializationEvent,
   209  		eventspb.BusEventType_BUS_EVENT_TYPE_SETTLE_POSITION:                         SettlePositionEvent,
   210  		eventspb.BusEventType_BUS_EVENT_TYPE_SETTLE_DISTRESSED:                       SettleDistressedEvent,
   211  		eventspb.BusEventType_BUS_EVENT_TYPE_MARKET_CREATED:                          MarketCreatedEvent,
   212  		eventspb.BusEventType_BUS_EVENT_TYPE_MARKET_UPDATED:                          MarketUpdatedEvent,
   213  		eventspb.BusEventType_BUS_EVENT_TYPE_ASSET:                                   AssetEvent,
   214  		eventspb.BusEventType_BUS_EVENT_TYPE_MARKET_TICK:                             MarketTickEvent,
   215  		eventspb.BusEventType_BUS_EVENT_TYPE_WITHDRAWAL:                              WithdrawalEvent,
   216  		eventspb.BusEventType_BUS_EVENT_TYPE_DEPOSIT:                                 DepositEvent,
   217  		eventspb.BusEventType_BUS_EVENT_TYPE_AUCTION:                                 AuctionEvent,
   218  		eventspb.BusEventType_BUS_EVENT_TYPE_RISK_FACTOR:                             RiskFactorEvent,
   219  		eventspb.BusEventType_BUS_EVENT_TYPE_NETWORK_PARAMETER:                       NetworkParameterEvent,
   220  		eventspb.BusEventType_BUS_EVENT_TYPE_LIQUIDITY_PROVISION:                     LiquidityProvisionEvent,
   221  		eventspb.BusEventType_BUS_EVENT_TYPE_TX_ERROR:                                TxErrEvent,
   222  		eventspb.BusEventType_BUS_EVENT_TYPE_ORACLE_SPEC:                             OracleSpecEvent,
   223  		eventspb.BusEventType_BUS_EVENT_TYPE_ORACLE_DATA:                             OracleDataEvent,
   224  		eventspb.BusEventType_BUS_EVENT_TYPE_EPOCH_UPDATE:                            EpochUpdate,
   225  		eventspb.BusEventType_BUS_EVENT_TYPE_REWARD_PAYOUT_EVENT:                     RewardPayoutEvent,
   226  		eventspb.BusEventType_BUS_EVENT_TYPE_DELEGATION_BALANCE:                      DelegationBalanceEvent,
   227  		eventspb.BusEventType_BUS_EVENT_TYPE_VALIDATOR_SCORE:                         ValidatorScoreEvent,
   228  		eventspb.BusEventType_BUS_EVENT_TYPE_STAKE_LINKING:                           StakeLinkingEvent,
   229  		eventspb.BusEventType_BUS_EVENT_TYPE_VALIDATOR_UPDATE:                        ValidatorUpdateEvent,
   230  		eventspb.BusEventType_BUS_EVENT_TYPE_CHECKPOINT:                              CheckpointEvent,
   231  		eventspb.BusEventType_BUS_EVENT_TYPE_KEY_ROTATION:                            KeyRotationEvent,
   232  		eventspb.BusEventType_BUS_EVENT_TYPE_STATE_VAR:                               StateVarEvent,
   233  		eventspb.BusEventType_BUS_EVENT_TYPE_NETWORK_LIMITS:                          NetworkLimitsEvent,
   234  		eventspb.BusEventType_BUS_EVENT_TYPE_TRANSFER:                                TransferEvent,
   235  		eventspb.BusEventType_BUS_EVENT_TYPE_VALIDATOR_RANKING:                       ValidatorRankingEvent,
   236  		eventspb.BusEventType_BUS_EVENT_TYPE_ERC20_MULTI_SIG_SET_THRESHOLD:           ERC20MultiSigThresholdSetEvent,
   237  		eventspb.BusEventType_BUS_EVENT_TYPE_ERC20_MULTI_SIG_SIGNER_EVENT:            ERC20MultiSigSignerEvent,
   238  		eventspb.BusEventType_BUS_EVENT_TYPE_ERC20_MULTI_SIG_SIGNER_ADDED:            ERC20MultiSigSignerAddedEvent,
   239  		eventspb.BusEventType_BUS_EVENT_TYPE_ERC20_MULTI_SIG_SIGNER_REMOVED:          ERC20MultiSigSignerRemovedEvent,
   240  		eventspb.BusEventType_BUS_EVENT_TYPE_POSITION_STATE:                          PositionStateEvent,
   241  		eventspb.BusEventType_BUS_EVENT_TYPE_ETHEREUM_KEY_ROTATION:                   EthereumKeyRotationEvent,
   242  		eventspb.BusEventType_BUS_EVENT_TYPE_PROTOCOL_UPGRADE_PROPOSAL:               ProtocolUpgradeEvent,
   243  		eventspb.BusEventType_BUS_EVENT_TYPE_BEGIN_BLOCK:                             BeginBlockEvent,
   244  		eventspb.BusEventType_BUS_EVENT_TYPE_END_BLOCK:                               EndBlockEvent,
   245  		eventspb.BusEventType_BUS_EVENT_TYPE_PROTOCOL_UPGRADE_STARTED:                ProtocolUpgradeStartedEvent,
   246  		eventspb.BusEventType_BUS_EVENT_TYPE_SETTLE_MARKET:                           SettleMarketEvent,
   247  		eventspb.BusEventType_BUS_EVENT_TYPE_TRANSACTION_RESULT:                      TransactionResultEvent,
   248  		eventspb.BusEventType_BUS_EVENT_TYPE_SNAPSHOT_TAKEN:                          CoreSnapshotEvent,
   249  		eventspb.BusEventType_BUS_EVENT_TYPE_PROTOCOL_UPGRADE_DATA_NODE_READY:        ProtocolUpgradeDataNodeReadyEvent,
   250  		eventspb.BusEventType_BUS_EVENT_TYPE_DISTRESSED_ORDERS_CLOSED:                DistressedOrdersClosedEvent,
   251  		eventspb.BusEventType_BUS_EVENT_TYPE_EXPIRED_ORDERS:                          ExpiredOrdersEvent,
   252  		eventspb.BusEventType_BUS_EVENT_TYPE_DISTRESSED_POSITIONS:                    DistressedPositionsEvent,
   253  		eventspb.BusEventType_BUS_EVENT_TYPE_STOP_ORDER:                              StopOrderEvent,
   254  		eventspb.BusEventType_BUS_EVENT_TYPE_FUNDING_PERIOD:                          FundingPeriodEvent,
   255  		eventspb.BusEventType_BUS_EVENT_TYPE_FUNDING_PERIOD_DATA_POINT:               FundingPeriodDataPointEvent,
   256  		eventspb.BusEventType_BUS_EVENT_TYPE_TEAM_CREATED:                            TeamCreatedEvent,
   257  		eventspb.BusEventType_BUS_EVENT_TYPE_TEAM_UPDATED:                            TeamUpdatedEvent,
   258  		eventspb.BusEventType_BUS_EVENT_TYPE_REFEREE_SWITCHED_TEAM:                   RefereeSwitchedTeamEvent,
   259  		eventspb.BusEventType_BUS_EVENT_TYPE_REFEREE_JOINED_TEAM:                     RefereeJoinedTeamEvent,
   260  		eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_PROGRAM_STARTED:                ReferralProgramStartedEvent,
   261  		eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_PROGRAM_ENDED:                  ReferralProgramEndedEvent,
   262  		eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_PROGRAM_UPDATED:                ReferralProgramUpdatedEvent,
   263  		eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_SET_CREATED:                    ReferralSetCreatedEvent,
   264  		eventspb.BusEventType_BUS_EVENT_TYPE_REFEREE_JOINED_REFERRAL_SET:             RefereeJoinedReferralSetEvent,
   265  		eventspb.BusEventType_BUS_EVENT_TYPE_PARTY_ACTIVITY_STREAK:                   PartyActivityStreakEvent,
   266  		eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_DISCOUNT_PROGRAM_STARTED:         VolumeDiscountProgramStartedEvent,
   267  		eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_DISCOUNT_PROGRAM_ENDED:           VolumeDiscountProgramEndedEvent,
   268  		eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_DISCOUNT_PROGRAM_UPDATED:         VolumeDiscountProgramUpdatedEvent,
   269  		eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_SET_STATS_UPDATED:              ReferralSetStatsUpdatedEvent,
   270  		eventspb.BusEventType_BUS_EVENT_TYPE_VESTING_STATS_UPDATED:                   VestingStatsUpdatedEvent,
   271  		eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_DISCOUNT_STATS_UPDATED:           VolumeDiscountStatsUpdatedEvent,
   272  		eventspb.BusEventType_BUS_EVENT_TYPE_FEES_STATS_UPDATED:                      FeesStatsEvent,
   273  		eventspb.BusEventType_BUS_EVENT_TYPE_FUNDING_PAYMENTS:                        FundingPaymentsEvent,
   274  		eventspb.BusEventType_BUS_EVENT_TYPE_PAID_LIQUIDITY_FEES_STATS_UPDATED:       PaidLiquidityFeesStatsEvent,
   275  		eventspb.BusEventType_BUS_EVENT_TYPE_VESTING_SUMMARY:                         VestingBalancesSummaryEvent,
   276  		eventspb.BusEventType_BUS_EVENT_TYPE_TRANSFER_FEES_PAID:                      TransferFeesEvent,
   277  		eventspb.BusEventType_BUS_EVENT_TYPE_TRANSFER_FEES_DISCOUNT_UPDATED:          TransferFeesDiscountUpdatedEvent,
   278  		eventspb.BusEventType_BUS_EVENT_TYPE_PARTY_MARGIN_MODE_UPDATED:               PartyMarginModeUpdatedEvent,
   279  		eventspb.BusEventType_BUS_EVENT_TYPE_PARTY_PROFILE_UPDATED:                   PartyProfileUpdatedEvent,
   280  		eventspb.BusEventType_BUS_EVENT_TYPE_TEAMS_STATS_UPDATED:                     TeamsStatsUpdatedEvent,
   281  		eventspb.BusEventType_BUS_EVENT_TYPE_TIME_WEIGHTED_NOTIONAL_POSITION_UPDATED: TimeWeightedNotionalPositionUpdatedEvent,
   282  		eventspb.BusEventType_BUS_EVENT_TYPE_CANCELLED_ORDERS:                        CancelledOrdersEvent,
   283  		eventspb.BusEventType_BUS_EVENT_TYPE_GAME_SCORES:                             GameScoresEvent,
   284  		eventspb.BusEventType_BUS_EVENT_TYPE_AMM:                                     AMMPoolEvent,
   285  		eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_REBATE_PROGRAM_STARTED:           VolumeRebateProgramStartedEvent,
   286  		eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_REBATE_PROGRAM_ENDED:             VolumeRebateProgramEndedEvent,
   287  		eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_REBATE_PROGRAM_UPDATED:           VolumeRebateProgramUpdatedEvent,
   288  		eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_REBATE_STATS_UPDATED:             VolumeRebateStatsUpdatedEvent,
   289  		eventspb.BusEventType_BUS_EVENT_TYPE_AUTOMATED_PURCHASE_ANNOUNCED:            AutomatedPurchaseAnnouncedEvent,
   290  		// If adding a type here, please also add it to datanode/broker/convert.go
   291  	}
   292  
   293  	toProto = map[Type]eventspb.BusEventType{
   294  		ValidatorRankingEvent:                    eventspb.BusEventType_BUS_EVENT_TYPE_VALIDATOR_RANKING,
   295  		TimeUpdate:                               eventspb.BusEventType_BUS_EVENT_TYPE_TIME_UPDATE,
   296  		LedgerMovementsEvent:                     eventspb.BusEventType_BUS_EVENT_TYPE_LEDGER_MOVEMENTS,
   297  		PositionResolution:                       eventspb.BusEventType_BUS_EVENT_TYPE_POSITION_RESOLUTION,
   298  		MarketEvent:                              eventspb.BusEventType_BUS_EVENT_TYPE_MARKET,
   299  		OrderEvent:                               eventspb.BusEventType_BUS_EVENT_TYPE_ORDER,
   300  		AccountEvent:                             eventspb.BusEventType_BUS_EVENT_TYPE_ACCOUNT,
   301  		PartyEvent:                               eventspb.BusEventType_BUS_EVENT_TYPE_PARTY,
   302  		TradeEvent:                               eventspb.BusEventType_BUS_EVENT_TYPE_TRADE,
   303  		MarginLevelsEvent:                        eventspb.BusEventType_BUS_EVENT_TYPE_MARGIN_LEVELS,
   304  		ProposalEvent:                            eventspb.BusEventType_BUS_EVENT_TYPE_PROPOSAL,
   305  		VoteEvent:                                eventspb.BusEventType_BUS_EVENT_TYPE_VOTE,
   306  		MarketDataEvent:                          eventspb.BusEventType_BUS_EVENT_TYPE_MARKET_DATA,
   307  		NodeSignatureEvent:                       eventspb.BusEventType_BUS_EVENT_TYPE_NODE_SIGNATURE,
   308  		LossSocializationEvent:                   eventspb.BusEventType_BUS_EVENT_TYPE_LOSS_SOCIALIZATION,
   309  		SettlePositionEvent:                      eventspb.BusEventType_BUS_EVENT_TYPE_SETTLE_POSITION,
   310  		SettleDistressedEvent:                    eventspb.BusEventType_BUS_EVENT_TYPE_SETTLE_DISTRESSED,
   311  		MarketCreatedEvent:                       eventspb.BusEventType_BUS_EVENT_TYPE_MARKET_CREATED,
   312  		MarketUpdatedEvent:                       eventspb.BusEventType_BUS_EVENT_TYPE_MARKET_UPDATED,
   313  		AssetEvent:                               eventspb.BusEventType_BUS_EVENT_TYPE_ASSET,
   314  		MarketTickEvent:                          eventspb.BusEventType_BUS_EVENT_TYPE_MARKET_TICK,
   315  		WithdrawalEvent:                          eventspb.BusEventType_BUS_EVENT_TYPE_WITHDRAWAL,
   316  		DepositEvent:                             eventspb.BusEventType_BUS_EVENT_TYPE_DEPOSIT,
   317  		AuctionEvent:                             eventspb.BusEventType_BUS_EVENT_TYPE_AUCTION,
   318  		RiskFactorEvent:                          eventspb.BusEventType_BUS_EVENT_TYPE_RISK_FACTOR,
   319  		NetworkParameterEvent:                    eventspb.BusEventType_BUS_EVENT_TYPE_NETWORK_PARAMETER,
   320  		LiquidityProvisionEvent:                  eventspb.BusEventType_BUS_EVENT_TYPE_LIQUIDITY_PROVISION,
   321  		TxErrEvent:                               eventspb.BusEventType_BUS_EVENT_TYPE_TX_ERROR,
   322  		OracleSpecEvent:                          eventspb.BusEventType_BUS_EVENT_TYPE_ORACLE_SPEC,
   323  		OracleDataEvent:                          eventspb.BusEventType_BUS_EVENT_TYPE_ORACLE_DATA,
   324  		EpochUpdate:                              eventspb.BusEventType_BUS_EVENT_TYPE_EPOCH_UPDATE,
   325  		DelegationBalanceEvent:                   eventspb.BusEventType_BUS_EVENT_TYPE_DELEGATION_BALANCE,
   326  		StakeLinkingEvent:                        eventspb.BusEventType_BUS_EVENT_TYPE_STAKE_LINKING,
   327  		ValidatorUpdateEvent:                     eventspb.BusEventType_BUS_EVENT_TYPE_VALIDATOR_UPDATE,
   328  		RewardPayoutEvent:                        eventspb.BusEventType_BUS_EVENT_TYPE_REWARD_PAYOUT_EVENT,
   329  		CheckpointEvent:                          eventspb.BusEventType_BUS_EVENT_TYPE_CHECKPOINT,
   330  		ValidatorScoreEvent:                      eventspb.BusEventType_BUS_EVENT_TYPE_VALIDATOR_SCORE,
   331  		KeyRotationEvent:                         eventspb.BusEventType_BUS_EVENT_TYPE_KEY_ROTATION,
   332  		StateVarEvent:                            eventspb.BusEventType_BUS_EVENT_TYPE_STATE_VAR,
   333  		NetworkLimitsEvent:                       eventspb.BusEventType_BUS_EVENT_TYPE_NETWORK_LIMITS,
   334  		TransferEvent:                            eventspb.BusEventType_BUS_EVENT_TYPE_TRANSFER,
   335  		ERC20MultiSigThresholdSetEvent:           eventspb.BusEventType_BUS_EVENT_TYPE_ERC20_MULTI_SIG_SET_THRESHOLD,
   336  		ERC20MultiSigSignerEvent:                 eventspb.BusEventType_BUS_EVENT_TYPE_ERC20_MULTI_SIG_SIGNER_EVENT,
   337  		ERC20MultiSigSignerAddedEvent:            eventspb.BusEventType_BUS_EVENT_TYPE_ERC20_MULTI_SIG_SIGNER_ADDED,
   338  		ERC20MultiSigSignerRemovedEvent:          eventspb.BusEventType_BUS_EVENT_TYPE_ERC20_MULTI_SIG_SIGNER_REMOVED,
   339  		PositionStateEvent:                       eventspb.BusEventType_BUS_EVENT_TYPE_POSITION_STATE,
   340  		EthereumKeyRotationEvent:                 eventspb.BusEventType_BUS_EVENT_TYPE_ETHEREUM_KEY_ROTATION,
   341  		ProtocolUpgradeEvent:                     eventspb.BusEventType_BUS_EVENT_TYPE_PROTOCOL_UPGRADE_PROPOSAL,
   342  		BeginBlockEvent:                          eventspb.BusEventType_BUS_EVENT_TYPE_BEGIN_BLOCK,
   343  		EndBlockEvent:                            eventspb.BusEventType_BUS_EVENT_TYPE_END_BLOCK,
   344  		ProtocolUpgradeStartedEvent:              eventspb.BusEventType_BUS_EVENT_TYPE_PROTOCOL_UPGRADE_STARTED,
   345  		SettleMarketEvent:                        eventspb.BusEventType_BUS_EVENT_TYPE_SETTLE_MARKET,
   346  		TransactionResultEvent:                   eventspb.BusEventType_BUS_EVENT_TYPE_TRANSACTION_RESULT,
   347  		CoreSnapshotEvent:                        eventspb.BusEventType_BUS_EVENT_TYPE_SNAPSHOT_TAKEN,
   348  		ProtocolUpgradeDataNodeReadyEvent:        eventspb.BusEventType_BUS_EVENT_TYPE_PROTOCOL_UPGRADE_DATA_NODE_READY,
   349  		DistressedOrdersClosedEvent:              eventspb.BusEventType_BUS_EVENT_TYPE_DISTRESSED_ORDERS_CLOSED,
   350  		ExpiredOrdersEvent:                       eventspb.BusEventType_BUS_EVENT_TYPE_EXPIRED_ORDERS,
   351  		DistressedPositionsEvent:                 eventspb.BusEventType_BUS_EVENT_TYPE_DISTRESSED_POSITIONS,
   352  		StopOrderEvent:                           eventspb.BusEventType_BUS_EVENT_TYPE_STOP_ORDER,
   353  		FundingPeriodEvent:                       eventspb.BusEventType_BUS_EVENT_TYPE_FUNDING_PERIOD,
   354  		FundingPeriodDataPointEvent:              eventspb.BusEventType_BUS_EVENT_TYPE_FUNDING_PERIOD_DATA_POINT,
   355  		TeamCreatedEvent:                         eventspb.BusEventType_BUS_EVENT_TYPE_TEAM_CREATED,
   356  		TeamUpdatedEvent:                         eventspb.BusEventType_BUS_EVENT_TYPE_TEAM_UPDATED,
   357  		RefereeSwitchedTeamEvent:                 eventspb.BusEventType_BUS_EVENT_TYPE_REFEREE_SWITCHED_TEAM,
   358  		RefereeJoinedTeamEvent:                   eventspb.BusEventType_BUS_EVENT_TYPE_REFEREE_JOINED_TEAM,
   359  		ReferralProgramStartedEvent:              eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_PROGRAM_STARTED,
   360  		ReferralProgramEndedEvent:                eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_PROGRAM_ENDED,
   361  		ReferralProgramUpdatedEvent:              eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_PROGRAM_UPDATED,
   362  		ReferralSetCreatedEvent:                  eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_SET_CREATED,
   363  		RefereeJoinedReferralSetEvent:            eventspb.BusEventType_BUS_EVENT_TYPE_REFEREE_JOINED_REFERRAL_SET,
   364  		PartyActivityStreakEvent:                 eventspb.BusEventType_BUS_EVENT_TYPE_PARTY_ACTIVITY_STREAK,
   365  		VolumeDiscountProgramStartedEvent:        eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_DISCOUNT_PROGRAM_STARTED,
   366  		VolumeDiscountProgramEndedEvent:          eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_DISCOUNT_PROGRAM_ENDED,
   367  		VolumeDiscountProgramUpdatedEvent:        eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_DISCOUNT_PROGRAM_UPDATED,
   368  		ReferralSetStatsUpdatedEvent:             eventspb.BusEventType_BUS_EVENT_TYPE_REFERRAL_SET_STATS_UPDATED,
   369  		VestingStatsUpdatedEvent:                 eventspb.BusEventType_BUS_EVENT_TYPE_VESTING_STATS_UPDATED,
   370  		VolumeDiscountStatsUpdatedEvent:          eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_DISCOUNT_STATS_UPDATED,
   371  		FeesStatsEvent:                           eventspb.BusEventType_BUS_EVENT_TYPE_FEES_STATS_UPDATED,
   372  		FundingPaymentsEvent:                     eventspb.BusEventType_BUS_EVENT_TYPE_FUNDING_PAYMENTS,
   373  		PaidLiquidityFeesStatsEvent:              eventspb.BusEventType_BUS_EVENT_TYPE_PAID_LIQUIDITY_FEES_STATS_UPDATED,
   374  		VestingBalancesSummaryEvent:              eventspb.BusEventType_BUS_EVENT_TYPE_VESTING_SUMMARY,
   375  		TransferFeesEvent:                        eventspb.BusEventType_BUS_EVENT_TYPE_TRANSFER_FEES_PAID,
   376  		TransferFeesDiscountUpdatedEvent:         eventspb.BusEventType_BUS_EVENT_TYPE_TRANSFER_FEES_DISCOUNT_UPDATED,
   377  		PartyMarginModeUpdatedEvent:              eventspb.BusEventType_BUS_EVENT_TYPE_PARTY_MARGIN_MODE_UPDATED,
   378  		PartyProfileUpdatedEvent:                 eventspb.BusEventType_BUS_EVENT_TYPE_PARTY_PROFILE_UPDATED,
   379  		TeamsStatsUpdatedEvent:                   eventspb.BusEventType_BUS_EVENT_TYPE_TEAMS_STATS_UPDATED,
   380  		TimeWeightedNotionalPositionUpdatedEvent: eventspb.BusEventType_BUS_EVENT_TYPE_TIME_WEIGHTED_NOTIONAL_POSITION_UPDATED,
   381  		CancelledOrdersEvent:                     eventspb.BusEventType_BUS_EVENT_TYPE_CANCELLED_ORDERS,
   382  		GameScoresEvent:                          eventspb.BusEventType_BUS_EVENT_TYPE_GAME_SCORES,
   383  		AMMPoolEvent:                             eventspb.BusEventType_BUS_EVENT_TYPE_AMM,
   384  		VolumeRebateProgramStartedEvent:          eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_REBATE_PROGRAM_STARTED,
   385  		VolumeRebateProgramEndedEvent:            eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_REBATE_PROGRAM_ENDED,
   386  		VolumeRebateProgramUpdatedEvent:          eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_REBATE_PROGRAM_UPDATED,
   387  		VolumeRebateStatsUpdatedEvent:            eventspb.BusEventType_BUS_EVENT_TYPE_VOLUME_REBATE_STATS_UPDATED,
   388  		AutomatedPurchaseAnnouncedEvent:          eventspb.BusEventType_BUS_EVENT_TYPE_AUTOMATED_PURCHASE_ANNOUNCED,
   389  
   390  		// If adding a type here, please also add it to datanode/broker/convert.go
   391  	}
   392  
   393  	eventStrings = map[Type]string{
   394  		All:                                      "ALL",
   395  		TimeUpdate:                               "TimeUpdate",
   396  		LedgerMovementsEvent:                     "LedgerMovements",
   397  		PositionResolution:                       "PositionResolution",
   398  		MarketEvent:                              "MarketEvent",
   399  		OrderEvent:                               "OrderEvent",
   400  		AccountEvent:                             "AccountEvent",
   401  		PartyEvent:                               "PartyEvent",
   402  		TradeEvent:                               "TradeEvent",
   403  		MarginLevelsEvent:                        "MarginLevelsEvent",
   404  		ProposalEvent:                            "ProposalEvent",
   405  		VoteEvent:                                "VoteEvent",
   406  		MarketDataEvent:                          "MarketDataEvent",
   407  		NodeSignatureEvent:                       "NodeSignatureEvent",
   408  		LossSocializationEvent:                   "LossSocializationEvent",
   409  		SettlePositionEvent:                      "SettlePositionEvent",
   410  		SettleDistressedEvent:                    "SettleDistressedEvent",
   411  		MarketCreatedEvent:                       "MarketCreatedEvent",
   412  		MarketUpdatedEvent:                       "MarketUpdatedEvent",
   413  		AssetEvent:                               "AssetEvent",
   414  		MarketTickEvent:                          "MarketTickEvent",
   415  		AuctionEvent:                             "AuctionEvent",
   416  		WithdrawalEvent:                          "WithdrawalEvent",
   417  		DepositEvent:                             "DepositEvent",
   418  		RiskFactorEvent:                          "RiskFactorEvent",
   419  		NetworkParameterEvent:                    "NetworkParameterEvent",
   420  		LiquidityProvisionEvent:                  "LiquidityProvisionEvent",
   421  		TxErrEvent:                               "TxErrEvent",
   422  		OracleSpecEvent:                          "OracleSpecEvent",
   423  		OracleDataEvent:                          "OracleDataEvent",
   424  		EpochUpdate:                              "EpochUpdate",
   425  		DelegationBalanceEvent:                   "DelegationBalanceEvent",
   426  		StakeLinkingEvent:                        "StakeLinkingEvent",
   427  		ValidatorUpdateEvent:                     "ValidatorUpdateEvent",
   428  		RewardPayoutEvent:                        "RewardPayoutEvent",
   429  		CheckpointEvent:                          "CheckpointEvent",
   430  		ValidatorScoreEvent:                      "ValidatorScoreEvent",
   431  		KeyRotationEvent:                         "KeyRotationEvent",
   432  		StateVarEvent:                            "StateVarEvent",
   433  		NetworkLimitsEvent:                       "NetworkLimitsEvent",
   434  		TransferEvent:                            "TransferEvent",
   435  		ValidatorRankingEvent:                    "ValidatorRankingEvent",
   436  		ERC20MultiSigSignerEvent:                 "ERC20MultiSigSignerEvent",
   437  		ERC20MultiSigThresholdSetEvent:           "ERC20MultiSigThresholdSetEvent",
   438  		ERC20MultiSigSignerAddedEvent:            "ERC20MultiSigSignerAddedEvent",
   439  		ERC20MultiSigSignerRemovedEvent:          "ERC20MultiSigSignerRemovedEvent",
   440  		PositionStateEvent:                       "PositionStateEvent",
   441  		EthereumKeyRotationEvent:                 "EthereumKeyRotationEvent",
   442  		ProtocolUpgradeEvent:                     "ProtocolUpgradeEvent",
   443  		BeginBlockEvent:                          "BeginBlockEvent",
   444  		EndBlockEvent:                            "EndBlockEvent",
   445  		ProtocolUpgradeStartedEvent:              "ProtocolUpgradeStartedEvent",
   446  		SettleMarketEvent:                        "SettleMarketEvent",
   447  		TransactionResultEvent:                   "TransactionResultEvent",
   448  		CoreSnapshotEvent:                        "CoreSnapshotEvent",
   449  		ProtocolUpgradeDataNodeReadyEvent:        "UpgradeDataNodeEvent",
   450  		DistressedOrdersClosedEvent:              "DistressedOrdersClosedEvent",
   451  		ExpiredOrdersEvent:                       "ExpiredOrdersEvent",
   452  		DistressedPositionsEvent:                 "DistressedPositionsEvent",
   453  		StopOrderEvent:                           "StopOrderEvent",
   454  		FundingPeriodEvent:                       "FundingPeriodEvent",
   455  		FundingPeriodDataPointEvent:              "FundingPeriodDataPointEvent",
   456  		TeamCreatedEvent:                         "TeamCreatedEvent",
   457  		TeamUpdatedEvent:                         "TeamUpdatedEvent",
   458  		RefereeSwitchedTeamEvent:                 "RefereeSwitchedTeamEvent",
   459  		RefereeJoinedTeamEvent:                   "RefereeJoinedTeamEvent",
   460  		ReferralProgramStartedEvent:              "ReferralProgramStartedEvent",
   461  		ReferralProgramEndedEvent:                "ReferralProgramEndedEvent",
   462  		ReferralProgramUpdatedEvent:              "ReferralProgramUpdatedEvent",
   463  		ReferralSetCreatedEvent:                  "ReferralSetCreatedEvent",
   464  		RefereeJoinedReferralSetEvent:            "RefereeJoinReferralSetEvent",
   465  		PartyActivityStreakEvent:                 "PartyActivityStreakEvent",
   466  		VolumeDiscountProgramStartedEvent:        "VolumeDiscountProgramStartedEvent",
   467  		VolumeDiscountProgramEndedEvent:          "VolumeDiscountProgramEndedEvent",
   468  		VolumeDiscountProgramUpdatedEvent:        "VolumeDiscountProgramUpdatedEvent",
   469  		ReferralSetStatsUpdatedEvent:             "ReferralSetStatsUpdatedEvent",
   470  		VestingStatsUpdatedEvent:                 "VestingStatsUpdatedEvent",
   471  		VolumeDiscountStatsUpdatedEvent:          "VolumeDiscountStatsUpdatedEvent",
   472  		FeesStatsEvent:                           "FeesStatsEvent",
   473  		FundingPaymentsEvent:                     "FundingPaymentsEvent",
   474  		PaidLiquidityFeesStatsEvent:              "LiquidityFeesStatsEvent",
   475  		VestingBalancesSummaryEvent:              "VestingBalancesSummaryEvent",
   476  		PartyMarginModeUpdatedEvent:              "PartyMarginModeUpdatedEvent",
   477  		PartyProfileUpdatedEvent:                 "PartyProfileUpdatedEvent",
   478  		TeamsStatsUpdatedEvent:                   "TeamsStatsUpdatedEvent",
   479  		TimeWeightedNotionalPositionUpdatedEvent: "TimeWeightedNotionalPositionUpdatedEvent",
   480  		CancelledOrdersEvent:                     "CancelledOrdersEvent",
   481  		GameScoresEvent:                          "GameScoresEvent",
   482  		AMMPoolEvent:                             "AMMPoolEvent",
   483  		VolumeRebateProgramStartedEvent:          "VolumeRebateProgramStartedEvent",
   484  		VolumeRebateProgramEndedEvent:            "VolumeRebateProgramEndedEvent",
   485  		VolumeRebateProgramUpdatedEvent:          "VolumeRebateProgramUpdatedEvent",
   486  		VolumeRebateStatsUpdatedEvent:            "VolumeRebateStatsUpdatedEvent",
   487  		AutomatedPurchaseAnnouncedEvent:          "AutomatedPurchaseAnnouncedEvent",
   488  	}
   489  )
   490  
   491  // A base event holds no data, so the constructor will not be called directly.
   492  func newBase(ctx context.Context, t Type) *Base {
   493  	ctx, tID := vgcontext.TraceIDFromContext(ctx)
   494  	cID, _ := vgcontext.ChainIDFromContext(ctx)
   495  	h, _ := vgcontext.BlockHeightFromContext(ctx)
   496  	txHash, _ := vgcontext.TxHashFromContext(ctx)
   497  	return &Base{
   498  		ctx:     ctx,
   499  		traceID: tID,
   500  		chainID: cID,
   501  		txHash:  txHash,
   502  		blockNr: int64(h),
   503  		et:      t,
   504  	}
   505  }
   506  
   507  // Replace updates the event to be based on the new given context.
   508  func (b *Base) Replace(ctx context.Context) {
   509  	nb := newBase(ctx, b.Type())
   510  	*b = *nb
   511  }
   512  
   513  // CompositeCount on the base event will default to 1.
   514  func (b Base) CompositeCount() uint64 {
   515  	return 1
   516  }
   517  
   518  // TraceID returns the... traceID obviously.
   519  func (b Base) TraceID() string {
   520  	return b.traceID
   521  }
   522  
   523  func (b Base) ChainID() string {
   524  	return b.chainID
   525  }
   526  
   527  func (b Base) TxHash() string {
   528  	return b.txHash
   529  }
   530  
   531  func (b *Base) SetSequenceID(s uint64) {
   532  	// sequence ID can only be set once
   533  	if b.seq != 0 {
   534  		return
   535  	}
   536  	b.seq = s
   537  }
   538  
   539  // Sequence returns event sequence number.
   540  func (b Base) Sequence() uint64 {
   541  	return b.seq
   542  }
   543  
   544  // Context returns context.
   545  func (b Base) Context() context.Context {
   546  	return b.ctx
   547  }
   548  
   549  // Type returns the event type.
   550  func (b Base) Type() Type {
   551  	return b.et
   552  }
   553  
   554  func (b Base) eventID() string {
   555  	return fmt.Sprintf("%d-%d", b.blockNr, b.seq)
   556  }
   557  
   558  // BlockNr returns the current block number.
   559  func (b Base) BlockNr() int64 {
   560  	return b.blockNr
   561  }
   562  
   563  // MarketEvents return all the possible market events.
   564  func MarketEvents() []Type {
   565  	return marketEvents
   566  }
   567  
   568  // String get string representation of event type.
   569  func (t Type) String() string {
   570  	s, ok := eventStrings[t]
   571  	if !ok {
   572  		return "UNKNOWN EVENT"
   573  	}
   574  	return s
   575  }
   576  
   577  // TryFromString tries to parse a raw string into an event type, false indicates that.
   578  func TryFromString(s string) (*Type, bool) {
   579  	for k, v := range eventStrings {
   580  		if strings.EqualFold(s, v) {
   581  			return &k, true
   582  		}
   583  	}
   584  	return nil, false
   585  }
   586  
   587  // ProtoToInternal converts the proto message enum to our internal constants
   588  // we're not using a map to de-duplicate the event types here, so we can exploit
   589  // duplicating the same event to control the internal subscriber channel buffer.
   590  func ProtoToInternal(pTypes ...eventspb.BusEventType) ([]Type, error) {
   591  	ret := make([]Type, 0, len(pTypes))
   592  	for _, t := range pTypes {
   593  		// all events -> subscriber should return a nil slice
   594  		if t == eventspb.BusEventType_BUS_EVENT_TYPE_ALL {
   595  			return nil, nil
   596  		}
   597  		it, ok := protoMap[t]
   598  		if !ok {
   599  			return nil, ErrInvalidEventType
   600  		}
   601  		if it == MarketEvent {
   602  			ret = append(ret, marketEvents...)
   603  		} else {
   604  			ret = append(ret, it)
   605  		}
   606  	}
   607  	return ret, nil
   608  }
   609  
   610  func GetMarketIDFilter(mID string) func(Event) bool {
   611  	return func(e Event) bool {
   612  		me, ok := e.(marketFilterable)
   613  		if !ok {
   614  			return false
   615  		}
   616  		return me.MarketID() == mID
   617  	}
   618  }
   619  
   620  func GetPartyIDFilter(pID string) func(Event) bool {
   621  	return func(e Event) bool {
   622  		pe, ok := e.(partyFilterable)
   623  		if !ok {
   624  			return false
   625  		}
   626  		return pe.IsParty(pID)
   627  	}
   628  }
   629  
   630  func GetPartyAndMarketFilter(mID, pID string) func(Event) bool {
   631  	return func(e Event) bool {
   632  		mpe, ok := e.(marketPartyFilterable)
   633  		if !ok {
   634  			return false
   635  		}
   636  		return mpe.MarketID() == mID && mpe.PartyID() == pID
   637  	}
   638  }
   639  
   640  func (t Type) ToProto() eventspb.BusEventType {
   641  	pt, ok := toProto[t]
   642  	if !ok {
   643  		panic(fmt.Sprintf("Converting events.Type %s to proto BusEventType: no corresponding value found", t))
   644  	}
   645  	return pt
   646  }
   647  
   648  func newBusEventFromBase(base *Base) *eventspb.BusEvent {
   649  	event := &eventspb.BusEvent{
   650  		Version: eventspb.Version,
   651  		Id:      base.eventID(),
   652  		Type:    base.Type().ToProto(),
   653  		Block:   base.TraceID(),
   654  		ChainId: base.ChainID(),
   655  		TxHash:  base.TxHash(),
   656  	}
   657  
   658  	return event
   659  }
   660  
   661  func newBaseFromBusEvent(ctx context.Context, t Type, be *eventspb.BusEvent) *Base {
   662  	evtCtx := vgcontext.WithTraceID(ctx, be.Block)
   663  	evtCtx = vgcontext.WithChainID(evtCtx, be.ChainId)
   664  	evtCtx = vgcontext.WithTxHash(evtCtx, be.TxHash)
   665  	blockNr, seq := decodeEventID(be.Id)
   666  	return &Base{
   667  		ctx:     evtCtx,
   668  		traceID: be.Block,
   669  		chainID: be.ChainId,
   670  		txHash:  be.TxHash,
   671  		blockNr: blockNr,
   672  		seq:     seq,
   673  		et:      t,
   674  	}
   675  }
   676  
   677  func decodeEventID(id string) (blockNr int64, seq uint64) {
   678  	arr := strings.Split(id, "-")
   679  	s1, s2 := arr[0], arr[1]
   680  	blockNr, _ = strconv.ParseInt(s1, 10, 64)
   681  	n, _ := strconv.ParseInt(s2, 10, 64)
   682  	seq = uint64(n)
   683  	return
   684  }