From dd41872f18e8821ddbd44a7290cdb0da03bb1c56 Mon Sep 17 00:00:00 2001 From: Kirill Date: Thu, 16 Jan 2025 13:09:41 +0400 Subject: [PATCH 1/3] Replace usage of types.Error with error interface (#122) --- internal/db/model/delegation.go | 33 +----- internal/services/bootstrap.go | 11 +- internal/services/consumer_events.go | 17 ++- internal/services/delegation.go | 121 +++++---------------- internal/services/delegation_helpers.go | 17 +-- internal/services/events.go | 139 ++++++------------------ internal/services/finality_provider.go | 63 +++-------- 7 files changed, 93 insertions(+), 308 deletions(-) diff --git a/internal/db/model/delegation.go b/internal/db/model/delegation.go index 5e5fd3f..c22ac1d 100644 --- a/internal/db/model/delegation.go +++ b/internal/db/model/delegation.go @@ -2,7 +2,6 @@ package model import ( "fmt" - "net/http" "strconv" "github.com/babylonlabs-io/babylon-staking-indexer/internal/types" @@ -59,50 +58,30 @@ func FromEventBTCDelegationCreated( event *bbntypes.EventBTCDelegationCreated, bbnBlockHeight, bbnBlockTime int64, -) (*BTCDelegationDetails, *types.Error) { +) (*BTCDelegationDetails, error) { stakingOutputIdx, err := strconv.ParseUint(event.StakingOutputIndex, 10, 32) if err != nil { - return nil, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to parse staking output index: %w", err), - ) + return nil, fmt.Errorf("failed to parse staking output index: %w", err) } paramsVersion, err := strconv.ParseUint(event.ParamsVersion, 10, 32) if err != nil { - return nil, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to parse params version: %w", err), - ) + return nil, fmt.Errorf("failed to parse params version: %w", err) } stakingTime, err := strconv.ParseUint(event.StakingTime, 10, 32) if err != nil { - return nil, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to parse staking time: %w", err), - ) + return nil, fmt.Errorf("failed to parse staking time: %w", err) } unbondingTime, err := strconv.ParseUint(event.UnbondingTime, 10, 32) if err != nil { - return nil, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to parse unbonding time: %w", err), - ) + return nil, fmt.Errorf("failed to parse unbonding time: %w", err) } stakingTx, err := utils.DeserializeBtcTransactionFromHex(event.StakingTxHex) if err != nil { - return nil, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to deserialize staking tx: %w", err), - ) + return nil, fmt.Errorf("failed to deserialize staking tx: %w", err) } stakingValue := btcutil.Amount(stakingTx.TxOut[stakingOutputIdx].Value) diff --git a/internal/services/bootstrap.go b/internal/services/bootstrap.go index cdca25b..2e4a7d6 100644 --- a/internal/services/bootstrap.go +++ b/internal/services/bootstrap.go @@ -3,9 +3,6 @@ package services import ( "context" "fmt" - "net/http" - - "github.com/babylonlabs-io/babylon-staking-indexer/internal/types" "github.com/rs/zerolog/log" ) @@ -86,15 +83,11 @@ func (s *Service) processBlocksSequentially(ctx context.Context) error { // /block_result endpoint of the BBN blockchain. func (s *Service) getEventsFromBlock( ctx context.Context, blockHeight int64, -) ([]BbnEvent, *types.Error) { +) ([]BbnEvent, error) { events := make([]BbnEvent, 0) blockResult, err := s.bbn.GetBlockResults(ctx, &blockHeight) if err != nil { - return nil, types.NewError( - http.StatusInternalServerError, - types.ClientRequestError, - fmt.Errorf("failed to get block results: %w", err), - ) + return nil, fmt.Errorf("failed to get block results: %w", err) } // Append transaction-level events for _, txResult := range blockResult.TxsResults { diff --git a/internal/services/consumer_events.go b/internal/services/consumer_events.go index 8bbaa55..c761af2 100644 --- a/internal/services/consumer_events.go +++ b/internal/services/consumer_events.go @@ -5,14 +5,13 @@ import ( "fmt" "github.com/babylonlabs-io/babylon-staking-indexer/internal/db/model" - "github.com/babylonlabs-io/babylon-staking-indexer/internal/types" queuecli "github.com/babylonlabs-io/staking-queue-client/client" ) func (s *Service) emitActiveDelegationEvent( ctx context.Context, delegation *model.BTCDelegationDetails, -) *types.Error { +) error { stateHistoryStrs := model.ToStateStrings(delegation.StateHistory) stakingEvent := queuecli.NewActiveStakingEvent( delegation.StakingTxHashHex, @@ -23,7 +22,7 @@ func (s *Service) emitActiveDelegationEvent( ) if err := s.queueManager.PushActiveStakingEvent(ctx, &stakingEvent); err != nil { - return types.NewInternalServiceError(fmt.Errorf("failed to push the staking event to the queue: %w", err)) + return fmt.Errorf("failed to push the staking event to the queue: %w", err) } return nil } @@ -31,7 +30,7 @@ func (s *Service) emitActiveDelegationEvent( func (s *Service) emitUnbondingDelegationEvent( ctx context.Context, delegation *model.BTCDelegationDetails, -) *types.Error { +) error { stateHistoryStrs := model.ToStateStrings(delegation.StateHistory) ev := queuecli.NewUnbondingStakingEvent( delegation.StakingTxHashHex, @@ -41,7 +40,7 @@ func (s *Service) emitUnbondingDelegationEvent( stateHistoryStrs, ) if err := s.queueManager.PushUnbondingStakingEvent(ctx, &ev); err != nil { - return types.NewInternalServiceError(fmt.Errorf("failed to push the unbonding event to the queue: %w", err)) + return fmt.Errorf("failed to push the unbonding event to the queue: %w", err) } return nil } @@ -49,7 +48,7 @@ func (s *Service) emitUnbondingDelegationEvent( func (s *Service) emitWithdrawableDelegationEvent( ctx context.Context, delegation *model.BTCDelegationDetails, -) *types.Error { +) error { stateHistoryStrs := model.ToStateStrings(delegation.StateHistory) ev := queuecli.NewWithdrawableStakingEvent( delegation.StakingTxHashHex, @@ -59,7 +58,7 @@ func (s *Service) emitWithdrawableDelegationEvent( stateHistoryStrs, ) if err := s.queueManager.PushWithdrawableStakingEvent(ctx, &ev); err != nil { - return types.NewInternalServiceError(fmt.Errorf("failed to push the withdrawable event to the queue: %w", err)) + return fmt.Errorf("failed to push the withdrawable event to the queue: %w", err) } return nil } @@ -67,7 +66,7 @@ func (s *Service) emitWithdrawableDelegationEvent( func (s *Service) emitWithdrawnDelegationEvent( ctx context.Context, delegation *model.BTCDelegationDetails, -) *types.Error { +) error { stateHistoryStrs := model.ToStateStrings(delegation.StateHistory) ev := queuecli.NewWithdrawnStakingEvent( delegation.StakingTxHashHex, @@ -77,7 +76,7 @@ func (s *Service) emitWithdrawnDelegationEvent( stateHistoryStrs, ) if err := s.queueManager.PushWithdrawnStakingEvent(ctx, &ev); err != nil { - return types.NewInternalServiceError(fmt.Errorf("failed to push the withdrawn event to the queue: %w", err)) + return fmt.Errorf("failed to push the withdrawn event to the queue: %w", err) } return nil } diff --git a/internal/services/delegation.go b/internal/services/delegation.go index 3af7c3d..063b2dd 100644 --- a/internal/services/delegation.go +++ b/internal/services/delegation.go @@ -3,7 +3,6 @@ package services import ( "context" "fmt" - "net/http" "strconv" "github.com/babylonlabs-io/babylon-staking-indexer/internal/db" @@ -27,7 +26,7 @@ const ( func (s *Service) processNewBTCDelegationEvent( ctx context.Context, event abcitypes.Event, bbnBlockHeight int64, -) *types.Error { +) error { newDelegation, err := parseEvent[*bbntypes.EventBTCDelegationCreated]( EventBTCDelegationCreated, event, ) @@ -42,11 +41,7 @@ func (s *Service) processNewBTCDelegationEvent( // Get block info to get timestamp bbnBlock, bbnErr := s.bbn.GetBlock(ctx, &bbnBlockHeight) if bbnErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.ClientRequestError, - fmt.Errorf("failed to get block: %w", bbnErr), - ) + return fmt.Errorf("failed to get block: %w", bbnErr) } bbnBlockTime := bbnBlock.Block.Time.Unix() @@ -62,11 +57,7 @@ func (s *Service) processNewBTCDelegationEvent( // BTC delegation already exists, ignore the event return nil } - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to save new BTC delegation: %w", dbErr), - ) + return fmt.Errorf("failed to save new BTC delegation: %w", dbErr) } // TODO: start watching for BTC confirmation if we need PendingBTCConfirmation state @@ -76,7 +67,7 @@ func (s *Service) processNewBTCDelegationEvent( func (s *Service) processCovenantSignatureReceivedEvent( ctx context.Context, event abcitypes.Event, -) *types.Error { +) error { covenantSignatureReceivedEvent, err := parseEvent[*bbntypes.EventCovenantSignatureReceived]( EventCovenantSignatureReceived, event, ) @@ -86,11 +77,7 @@ func (s *Service) processCovenantSignatureReceivedEvent( stakingTxHash := covenantSignatureReceivedEvent.StakingTxHash delegation, dbErr := s.db.GetBTCDelegationByStakingTxHash(ctx, stakingTxHash) if dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr), - ) + return fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr) } // Check if the covenant signature already exists, if it does, ignore the event for _, signature := range delegation.CovenantUnbondingSignatures { @@ -108,13 +95,9 @@ func (s *Service) processCovenantSignatureReceivedEvent( covenantBtcPkHex, signatureHex, ); dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf( - "failed to save BTC delegation unbonding covenant signature: %w for staking tx hash %s", - dbErr, stakingTxHash, - ), + return fmt.Errorf( + "failed to save BTC delegation unbonding covenant signature: %w for staking tx hash %s", + dbErr, stakingTxHash, ) } @@ -123,7 +106,7 @@ func (s *Service) processCovenantSignatureReceivedEvent( func (s *Service) processCovenantQuorumReachedEvent( ctx context.Context, event abcitypes.Event, bbnBlockHeight int64, -) *types.Error { +) error { covenantQuorumReachedEvent, err := parseEvent[*bbntypes.EventCovenantQuorumReached]( EventCovenantQuorumReached, event, ) @@ -143,11 +126,7 @@ func (s *Service) processCovenantQuorumReachedEvent( // Emit event and register spend notification delegation, dbErr := s.db.GetBTCDelegationByStakingTxHash(ctx, covenantQuorumReachedEvent.StakingTxHash) if dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr), - ) + return fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr) } newState := types.DelegationState(covenantQuorumReachedEvent.NewState) @@ -185,11 +164,7 @@ func (s *Service) processCovenantQuorumReachedEvent( newState, db.WithBbnHeight(bbnBlockHeight), ); dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to update BTC delegation state: %w", dbErr), - ) + return fmt.Errorf("failed to update BTC delegation state: %w", dbErr) } return nil @@ -197,7 +172,7 @@ func (s *Service) processCovenantQuorumReachedEvent( func (s *Service) processBTCDelegationInclusionProofReceivedEvent( ctx context.Context, event abcitypes.Event, bbnBlockHeight int64, -) *types.Error { +) error { inclusionProofEvent, err := parseEvent[*bbntypes.EventBTCDelegationInclusionProofReceived]( EventBTCDelegationInclusionProofReceived, event, ) @@ -217,11 +192,7 @@ func (s *Service) processBTCDelegationInclusionProofReceivedEvent( // Emit event and register spend notification delegation, dbErr := s.db.GetBTCDelegationByStakingTxHash(ctx, inclusionProofEvent.StakingTxHash) if dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr), - ) + return fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr) } newState := types.DelegationState(inclusionProofEvent.NewState) if newState == types.StateActive { @@ -258,11 +229,7 @@ func (s *Service) processBTCDelegationInclusionProofReceivedEvent( bbnBlockHeight, model.FromEventBTCDelegationInclusionProofReceived(inclusionProofEvent), ); dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to update BTC delegation details: %w", dbErr), - ) + return fmt.Errorf("failed to update BTC delegation details: %w", dbErr) } return nil @@ -274,7 +241,7 @@ func (s *Service) processBTCDelegationInclusionProofReceivedEvent( // then this event will be silently ignored with help of validateBTCDelegationUnbondedEarlyEvent func (s *Service) processBTCDelegationUnbondedEarlyEvent( ctx context.Context, event abcitypes.Event, bbnBlockHeight int64, -) *types.Error { +) error { unbondedEarlyEvent, err := parseEvent[*bbntypes.EventBTCDelgationUnbondedEarly]( EventBTCDelgationUnbondedEarly, event, @@ -294,11 +261,7 @@ func (s *Service) processBTCDelegationUnbondedEarlyEvent( delegation, dbErr := s.db.GetBTCDelegationByStakingTxHash(ctx, unbondedEarlyEvent.StakingTxHash) if dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr), - ) + return fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr) } // Emit consumer event @@ -308,11 +271,7 @@ func (s *Service) processBTCDelegationUnbondedEarlyEvent( unbondingStartHeight, parseErr := strconv.ParseUint(unbondedEarlyEvent.StartHeight, 10, 32) if parseErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to parse start height: %w", parseErr), - ) + return fmt.Errorf("failed to parse start height: %w", parseErr) } subState := types.SubStateEarlyUnbonding @@ -325,11 +284,7 @@ func (s *Service) processBTCDelegationUnbondedEarlyEvent( unbondingExpireHeight, subState, ); err != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to save timelock expire: %w", err), - ) + return fmt.Errorf("failed to save timelock expire: %w", err) } log.Debug(). @@ -361,11 +316,7 @@ func (s *Service) processBTCDelegationUnbondedEarlyEvent( return nil } - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to update BTC delegation state: %w", err), - ) + return fmt.Errorf("failed to update BTC delegation state: %w", err) } return nil @@ -373,7 +324,7 @@ func (s *Service) processBTCDelegationUnbondedEarlyEvent( func (s *Service) processBTCDelegationExpiredEvent( ctx context.Context, event abcitypes.Event, bbnBlockHeight int64, -) *types.Error { +) error { expiredEvent, err := parseEvent[*bbntypes.EventBTCDelegationExpired]( EventBTCDelegationExpired, event, @@ -393,11 +344,7 @@ func (s *Service) processBTCDelegationExpiredEvent( delegation, dbErr := s.db.GetBTCDelegationByStakingTxHash(ctx, expiredEvent.StakingTxHash) if dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr), - ) + return fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr) } // Emit consumer event @@ -414,11 +361,7 @@ func (s *Service) processBTCDelegationExpiredEvent( delegation.EndHeight, subState, ); err != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to save timelock expire: %w", err), - ) + return fmt.Errorf("failed to save timelock expire: %w", err) } // Update delegation state @@ -430,11 +373,7 @@ func (s *Service) processBTCDelegationExpiredEvent( db.WithSubState(subState), db.WithBbnHeight(bbnBlockHeight), ); err != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to update BTC delegation state: %w", err), - ) + return fmt.Errorf("failed to update BTC delegation state: %w", err) } return nil @@ -442,7 +381,7 @@ func (s *Service) processBTCDelegationExpiredEvent( func (s *Service) processSlashedFinalityProviderEvent( ctx context.Context, event abcitypes.Event, bbnBlockHeight int64, -) *types.Error { +) error { slashedFinalityProviderEvent, err := parseEvent[*ftypes.EventSlashedFinalityProvider]( EventSlashedFinalityProvider, event, @@ -466,20 +405,12 @@ func (s *Service) processSlashedFinalityProviderEvent( if dbErr := s.db.UpdateDelegationsStateByFinalityProvider( ctx, fpBTCPKHex, types.StateSlashed, bbnBlockHeight, ); dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to update BTC delegation state: %w", dbErr), - ) + return fmt.Errorf("failed to update BTC delegation state: %w", dbErr) } delegations, dbErr := s.db.GetDelegationsByFinalityProvider(ctx, fpBTCPKHex) if dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegations by finality provider: %w", dbErr), - ) + return fmt.Errorf("failed to get BTC delegations by finality provider: %w", dbErr) } for _, delegation := range delegations { diff --git a/internal/services/delegation_helpers.go b/internal/services/delegation_helpers.go index ccf876c..5e5cb4e 100644 --- a/internal/services/delegation_helpers.go +++ b/internal/services/delegation_helpers.go @@ -4,10 +4,7 @@ import ( "context" "encoding/hex" "fmt" - "net/http" - "github.com/babylonlabs-io/babylon-staking-indexer/internal/db/model" - "github.com/babylonlabs-io/babylon-staking-indexer/internal/types" "github.com/babylonlabs-io/babylon-staking-indexer/internal/utils" bbn "github.com/babylonlabs-io/babylon/types" "github.com/btcsuite/btcd/chaincfg/chainhash" @@ -70,23 +67,15 @@ func (s *Service) registerStakingSpendNotification( stakingTxHex string, stakingOutputIdx uint32, stakingStartHeight uint32, -) *types.Error { +) error { stakingTxHash, err := chainhash.NewHashFromStr(stakingTxHashHex) if err != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to parse staking tx hash: %w", err), - ) + return fmt.Errorf("failed to parse staking tx hash: %w", err) } stakingTx, err := utils.DeserializeBtcTransactionFromHex(stakingTxHex) if err != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to deserialize staking tx: %w", err), - ) + return fmt.Errorf("failed to deserialize staking tx: %w", err) } stakingOutpoint := wire.OutPoint{ diff --git a/internal/services/events.go b/internal/services/events.go index 02983d9..608a8dd 100644 --- a/internal/services/events.go +++ b/internal/services/events.go @@ -3,7 +3,6 @@ package services import ( "context" "fmt" - "net/http" "strings" "time" @@ -53,7 +52,7 @@ func (s *Service) processEvent( // process the event based on its type. bbnEvent := event.Event - var err *types.Error + var err error switch EventTypes(bbnEvent.Type) { case EventFinalityProviderCreatedType: @@ -99,31 +98,23 @@ func (s *Service) processEvent( func parseEvent[T proto.Message]( expectedType EventTypes, event abcitypes.Event, -) (T, *types.Error) { +) (T, error) { var result T // Check if the event type matches the expected type if EventTypes(event.Type) != expectedType { - return result, types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Sprintf( - "unexpected event type: %s received when processing %s", - event.Type, - expectedType, - ), + return result, fmt.Errorf( + "unexpected event type: %s received when processing %s", + event.Type, + expectedType, ) } // Check if the event has attributes if len(event.Attributes) == 0 { - return result, types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Sprintf( - "no attributes found in the %s event", - expectedType, - ), + return result, fmt.Errorf( + "no attributes found in the %s event", + expectedType, ) } @@ -134,76 +125,52 @@ func parseEvent[T proto.Message]( protoMsg, err := sdk.ParseTypedEvent(sanitizedEvent) if err != nil { log.Debug().Interface("raw_event", event).Msg("Raw event data") - return result, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to parse typed event: %w", err), - ) + return result, fmt.Errorf("failed to parse typed event: %w", err) } // Type assertion to ensure we have the correct concrete type concreteMsg, ok := protoMsg.(T) if !ok { - return result, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("parsed event type %T does not match expected type %T", protoMsg, result), - ) + return result, fmt.Errorf("parsed event type %T does not match expected type %T", protoMsg, result) } return concreteMsg, nil } -func (s *Service) validateBTCDelegationCreatedEvent(event *bstypes.EventBTCDelegationCreated) *types.Error { +func (s *Service) validateBTCDelegationCreatedEvent(event *bstypes.EventBTCDelegationCreated) error { // Check if the staking tx hex is present if event.StakingTxHex == "" { - return types.NewValidationFailedError( - fmt.Errorf("new BTC delegation event missing staking tx hex"), - ) + return fmt.Errorf("new BTC delegation event missing staking tx hex") } if event.StakingOutputIndex == "" { - return types.NewValidationFailedError( - fmt.Errorf("new BTC delegation event missing staking output index"), - ) + return fmt.Errorf("new BTC delegation event missing staking output index") } // Validate the event state if event.NewState != bstypes.BTCDelegationStatus_PENDING.String() { - return types.NewValidationFailedError( - fmt.Errorf("invalid delegation state from Babylon when processing EventBTCDelegationCreated: expected PENDING, got %s", event.NewState), - ) + return fmt.Errorf("invalid delegation state from Babylon when processing EventBTCDelegationCreated: expected PENDING, got %s", event.NewState) } return nil } -func (s *Service) validateCovenantQuorumReachedEvent(ctx context.Context, event *bstypes.EventCovenantQuorumReached) (bool, *types.Error) { +func (s *Service) validateCovenantQuorumReachedEvent(ctx context.Context, event *bstypes.EventCovenantQuorumReached) (bool, error) { // Check if the staking tx hash is present if event.StakingTxHash == "" { - return false, types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - "covenant quorum reached event missing staking tx hash", - ) + return false, fmt.Errorf("covenant quorum reached event missing staking tx hash") } // Fetch the current delegation state from the database delegation, dbErr := s.db.GetBTCDelegationByStakingTxHash(ctx, event.StakingTxHash) if dbErr != nil { - return false, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr), - ) + return false, fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr) } // Retrieve the qualified states for the intended transition qualifiedStates := types.QualifiedStatesForCovenantQuorumReached(event.NewState) if qualifiedStates == nil { - return false, types.NewValidationFailedError( - fmt.Errorf("invalid delegation state from Babylon: %s", event.NewState), - ) + return false, fmt.Errorf("invalid delegation state from Babylon: %s", event.NewState) } // Check if the current state is qualified for the transition @@ -246,32 +213,22 @@ func (s *Service) validateCovenantQuorumReachedEvent(ctx context.Context, event return true, nil } -func (s *Service) validateBTCDelegationInclusionProofReceivedEvent(ctx context.Context, event *bstypes.EventBTCDelegationInclusionProofReceived) (bool, *types.Error) { +func (s *Service) validateBTCDelegationInclusionProofReceivedEvent(ctx context.Context, event *bstypes.EventBTCDelegationInclusionProofReceived) (bool, error) { // Check if the staking tx hash is present if event.StakingTxHash == "" { - return false, types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - "inclusion proof received event missing staking tx hash", - ) + return false, fmt.Errorf("inclusion proof received event missing staking tx hash") } // Fetch the current delegation state from the database delegation, dbErr := s.db.GetBTCDelegationByStakingTxHash(ctx, event.StakingTxHash) if dbErr != nil { - return false, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr), - ) + return false, fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr) } // Retrieve the qualified states for the intended transition qualifiedStates := types.QualifiedStatesForInclusionProofReceived(event.NewState) if qualifiedStates == nil { - return false, types.NewValidationFailedError( - fmt.Errorf("no qualified states defined for new state: %s", event.NewState), - ) + return false, fmt.Errorf("no qualified states defined for new state: %s", event.NewState) } // Check if the current state is qualified for the transition @@ -298,31 +255,21 @@ func (s *Service) validateBTCDelegationInclusionProofReceivedEvent(ctx context.C return true, nil } -func (s *Service) validateBTCDelegationUnbondedEarlyEvent(ctx context.Context, event *bstypes.EventBTCDelgationUnbondedEarly) (bool, *types.Error) { +func (s *Service) validateBTCDelegationUnbondedEarlyEvent(ctx context.Context, event *bstypes.EventBTCDelgationUnbondedEarly) (bool, error) { // Check if the staking tx hash is present if event.StakingTxHash == "" { - return false, types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - "unbonded early event missing staking tx hash", - ) + return false, fmt.Errorf("unbonded early event missing staking tx hash") } // Validate the event state if event.NewState != bstypes.BTCDelegationStatus_UNBONDED.String() { - return false, types.NewValidationFailedError( - fmt.Errorf("invalid delegation state from Babylon when processing EventBTCDelgationUnbondedEarly: expected UNBONDED, got %s", event.NewState), - ) + return false, fmt.Errorf("invalid delegation state from Babylon when processing EventBTCDelgationUnbondedEarly: expected UNBONDED, got %s", event.NewState) } // Fetch the current delegation state from the database delegation, dbErr := s.db.GetBTCDelegationByStakingTxHash(ctx, event.StakingTxHash) if dbErr != nil { - return false, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr), - ) + return false, fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr) } // Check if the current state is qualified for the transition @@ -337,31 +284,21 @@ func (s *Service) validateBTCDelegationUnbondedEarlyEvent(ctx context.Context, e return true, nil } -func (s *Service) validateBTCDelegationExpiredEvent(ctx context.Context, event *bstypes.EventBTCDelegationExpired) (bool, *types.Error) { +func (s *Service) validateBTCDelegationExpiredEvent(ctx context.Context, event *bstypes.EventBTCDelegationExpired) (bool, error) { // Check if the staking tx hash is present if event.StakingTxHash == "" { - return false, types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - "expired event missing staking tx hash", - ) + return false, fmt.Errorf("expired event missing staking tx hash") } // Validate the event state if event.NewState != bstypes.BTCDelegationStatus_EXPIRED.String() { - return false, types.NewValidationFailedError( - fmt.Errorf("invalid delegation state from Babylon when processing EventBTCDelegationExpired: expected EXPIRED, got %s", event.NewState), - ) + return false, fmt.Errorf("invalid delegation state from Babylon when processing EventBTCDelegationExpired: expected EXPIRED, got %s", event.NewState) } // Fetch the current delegation state from the database delegation, dbErr := s.db.GetBTCDelegationByStakingTxHash(ctx, event.StakingTxHash) if dbErr != nil { - return false, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr), - ) + return false, fmt.Errorf("failed to get BTC delegation by staking tx hash: %w", dbErr) } // Check if the current state is qualified for the transition @@ -376,22 +313,14 @@ func (s *Service) validateBTCDelegationExpiredEvent(ctx context.Context, event * return true, nil } -func (s *Service) validateSlashedFinalityProviderEvent(ctx context.Context, event *ftypes.EventSlashedFinalityProvider) (bool, *types.Error) { +func (s *Service) validateSlashedFinalityProviderEvent(ctx context.Context, event *ftypes.EventSlashedFinalityProvider) (bool, error) { if event.Evidence == nil { - return false, types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - "slashed finality provider event missing evidence", - ) + return false, fmt.Errorf("slashed finality provider event missing evidence") } _, err := event.Evidence.ExtractBTCSK() if err != nil { - return false, types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to extract BTC SK of the slashed finality provider: %w", err), - ) + return false, fmt.Errorf("failed to extract BTC SK of the slashed finality provider: %w", err) } return true, nil diff --git a/internal/services/finality_provider.go b/internal/services/finality_provider.go index 426bcf1..4fba7c5 100644 --- a/internal/services/finality_provider.go +++ b/internal/services/finality_provider.go @@ -3,11 +3,8 @@ package services import ( "context" "fmt" - "net/http" - "github.com/babylonlabs-io/babylon-staking-indexer/internal/db" "github.com/babylonlabs-io/babylon-staking-indexer/internal/db/model" - "github.com/babylonlabs-io/babylon-staking-indexer/internal/types" bbntypes "github.com/babylonlabs-io/babylon/x/btcstaking/types" abcitypes "github.com/cometbft/cometbft/abci/types" "github.com/rs/zerolog/log" @@ -21,7 +18,7 @@ const ( func (s *Service) processNewFinalityProviderEvent( ctx context.Context, event abcitypes.Event, -) *types.Error { +) error { newFinalityProvider, err := parseEvent[*bbntypes.EventFinalityProviderCreated]( EventFinalityProviderCreatedType, event, ) @@ -43,11 +40,7 @@ func (s *Service) processNewFinalityProviderEvent( Msg("Ignoring EventFinalityProviderCreated because finality provider already exists") return nil } - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to save new finality provider: %w", dbErr), - ) + return fmt.Errorf("failed to save new finality provider: %w", dbErr) } return nil @@ -55,7 +48,7 @@ func (s *Service) processNewFinalityProviderEvent( func (s *Service) processFinalityProviderEditedEvent( ctx context.Context, event abcitypes.Event, -) *types.Error { +) error { finalityProviderEdited, err := parseEvent[*bbntypes.EventFinalityProviderEdited]( EventFinalityProviderEditedType, event, ) @@ -70,11 +63,7 @@ func (s *Service) processFinalityProviderEditedEvent( if dbErr := s.db.UpdateFinalityProviderDetailsFromEvent( ctx, model.FromEventFinalityProviderEdited(finalityProviderEdited), ); dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to update finality provider details: %w", dbErr), - ) + return fmt.Errorf("failed to update finality provider details: %w", dbErr) } return nil @@ -82,7 +71,7 @@ func (s *Service) processFinalityProviderEditedEvent( func (s *Service) processFinalityProviderStateChangeEvent( ctx context.Context, event abcitypes.Event, -) *types.Error { +) error { finalityProviderStateChange, err := parseEvent[*bbntypes.EventFinalityProviderStatusChange]( EventFinalityProviderStatusChange, event, ) @@ -98,11 +87,7 @@ func (s *Service) processFinalityProviderStateChangeEvent( if dbErr := s.db.UpdateFinalityProviderState( ctx, finalityProviderStateChange.BtcPk, finalityProviderStateChange.NewState, ); dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to update finality provider state: %w", dbErr), - ) + return fmt.Errorf("failed to update finality provider state: %w", dbErr) } return nil } @@ -111,13 +96,9 @@ func (s *Service) processFinalityProviderStateChangeEvent( // the new finality provider event and returns an error if the event is invalid. func (s *Service) validateFinalityProviderCreatedEvent( fpCreated *bbntypes.EventFinalityProviderCreated, -) *types.Error { +) error { if fpCreated.BtcPkHex == "" { - return types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - "finality provider created event missing btc public key", - ) + return fmt.Errorf("finality provider created event missing btc public key") } return nil } @@ -126,13 +107,9 @@ func (s *Service) validateFinalityProviderCreatedEvent( // the finality provider edited event and returns an error if the event is invalid. func (s *Service) validateFinalityProviderEditedEvent( fpEdited *bbntypes.EventFinalityProviderEdited, -) *types.Error { +) error { if fpEdited.BtcPkHex == "" { - return types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - "finality provider edited event missing btc public key", - ) + return fmt.Errorf("finality provider edited event missing btc public key") } // TODO: Implement validation logic return nil @@ -141,30 +118,18 @@ func (s *Service) validateFinalityProviderEditedEvent( func (s *Service) validateFinalityProviderStateChangeEvent( ctx context.Context, fpStateChange *bbntypes.EventFinalityProviderStatusChange, -) *types.Error { +) error { // Check FP exists _, dbErr := s.db.GetFinalityProviderByBtcPk(ctx, fpStateChange.BtcPk) if dbErr != nil { - return types.NewError( - http.StatusInternalServerError, - types.InternalServiceError, - fmt.Errorf("failed to get finality provider by btc public key: %w", dbErr), - ) + return fmt.Errorf("failed to get finality provider by btc public key: %w", dbErr) } if fpStateChange.BtcPk == "" { - return types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - "finality provider State change event missing btc public key", - ) + return fmt.Errorf("finality provider State change event missing btc public key") } if fpStateChange.NewState == "" { - return types.NewErrorWithMsg( - http.StatusInternalServerError, - types.InternalServiceError, - "finality provider State change event missing State", - ) + return fmt.Errorf("finality provider State change event missing State") } return nil From fcdb02a2d4391186c4d17aec4ad92f5fb819082d Mon Sep 17 00:00:00 2001 From: Kirill Date: Thu, 16 Jan 2025 13:10:14 +0400 Subject: [PATCH 2/3] Remove unused constants, functions. Make NewError private function (#122) --- internal/types/error.go | 28 +++------------------------- 1 file changed, 3 insertions(+), 25 deletions(-) diff --git a/internal/types/error.go b/internal/types/error.go index bb0185c..cb8d145 100644 --- a/internal/types/error.go +++ b/internal/types/error.go @@ -14,13 +14,8 @@ func (e ErrorCode) String() string { const ( // 5XX InternalServiceError ErrorCode = "INTERNAL_SERVICE_ERROR" - ValidationError ErrorCode = "VALIDATION_ERROR" - NotFound ErrorCode = "NOT_FOUND" BadRequest ErrorCode = "BAD_REQUEST" - Forbidden ErrorCode = "FORBIDDEN" - UnprocessableEntity ErrorCode = "UNPROCESSABLE_ENTITY" RequestTimeout ErrorCode = "REQUEST_TIMEOUT" - ClientRequestError ErrorCode = "CLIENT_REQUEST_ERROR" ) // ApiError represents an error with an HTTP status code and an application-specific error code. @@ -36,10 +31,10 @@ func (e *Error) Error() string { return e.Err.Error() } -// NewError creates a new ApiError with the provided status code, error code, and underlying error. +// newError creates a new ApiError with the provided status code, error code, and underlying error. // If the status code is not provided (0), it defaults to http.StatusInternalServerError(500). // If the error code is empty, it defaults to INTERNAL_SERVICE_ERROR. -func NewError(statusCode int, errorCode ErrorCode, err error) *Error { +func newError(statusCode int, errorCode ErrorCode, err error) *Error { if statusCode == UninitializedStatusCode { statusCode = http.StatusInternalServerError } @@ -54,7 +49,7 @@ func NewError(statusCode int, errorCode ErrorCode, err error) *Error { } func NewErrorWithMsg(statusCode int, errorCode ErrorCode, msg string) *Error { - return NewError(statusCode, errorCode, errors.New(msg)) + return newError(statusCode, errorCode, errors.New(msg)) } func NewInternalServiceError(err error) *Error { @@ -65,24 +60,7 @@ func NewInternalServiceError(err error) *Error { } } -func NewValidationFailedError(err error) *Error { - return &Error{ - StatusCode: http.StatusBadRequest, - ErrorCode: ValidationError, - Err: err, - } -} - var ( // ErrInvalidUnbondingTx the transaction spends the unbonding path but is invalid ErrInvalidUnbondingTx = errors.New("invalid unbonding tx") - - // ErrInvalidStakingTx the stake transaction is invalid as it does not follow the global parameters - ErrInvalidStakingTx = errors.New("invalid staking tx") - - // ErrInvalidWithdrawalTx the withdrawal transaction is invalid as it does not unlock the expected time lock path - ErrInvalidWithdrawalTx = errors.New("invalid withdrawal tx") - - // ErrInvalidSlashingTx the slashing transaction is invalid as it does not unlock the expected slashing path - ErrInvalidSlashingTx = errors.New("invalid slashing tx") ) From c77775713b53bdb879c7b7721b90c85eb1a17338 Mon Sep 17 00:00:00 2001 From: Kirill Date: Thu, 16 Jan 2025 15:06:22 +0400 Subject: [PATCH 3/3] Add .collection() private helper method to db.Database --- internal/db/dbclient.go | 4 ++++ internal/db/delegation.go | 30 ++++++++++------------------ internal/db/finality_provider.go | 11 ++++------ internal/db/last_processed_height.go | 7 ++----- internal/db/params.go | 7 +++---- internal/db/timelock.go | 8 +++----- 6 files changed, 26 insertions(+), 41 deletions(-) diff --git a/internal/db/dbclient.go b/internal/db/dbclient.go index 4325198..c99964c 100644 --- a/internal/db/dbclient.go +++ b/internal/db/dbclient.go @@ -38,3 +38,7 @@ func (db *Database) Ping(ctx context.Context) error { } return nil } + +func (db *Database) collection(name string) *mongo.Collection { + return db.client.Database(db.dbName).Collection(name) +} diff --git a/internal/db/delegation.go b/internal/db/delegation.go index 6fd0eab..1c23d22 100644 --- a/internal/db/delegation.go +++ b/internal/db/delegation.go @@ -46,8 +46,7 @@ func WithBtcHeight(height int64) UpdateOption { func (db *Database) SaveNewBTCDelegation( ctx context.Context, delegationDoc *model.BTCDelegationDetails, ) error { - _, err := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + _, err := db.collection(model.BTCDelegationDetailsCollection). InsertOne(ctx, delegationDoc) if err != nil { var writeErr mongo.WriteException @@ -120,8 +119,7 @@ func (db *Database) UpdateBTCDelegationState( }, } - res := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + res := db.collection(model.BTCDelegationDetailsCollection). FindOneAndUpdate(ctx, filter, update) if res.Err() != nil { @@ -181,8 +179,7 @@ func (db *Database) UpdateBTCDelegationDetails( update["$push"] = bson.M{"state_history": stateRecord} } - res, err := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + res, err := db.collection(model.BTCDelegationDetailsCollection). UpdateOne(ctx, filter, update) if err != nil { @@ -211,8 +208,7 @@ func (db *Database) SaveBTCDelegationUnbondingCovenantSignature( }, }, } - _, err := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + _, err := db.collection(model.BTCDelegationDetailsCollection). UpdateOne(ctx, filter, update) return err @@ -223,8 +219,7 @@ func (db *Database) GetBTCDelegationByStakingTxHash( ) (*model.BTCDelegationDetails, error) { filter := bson.M{"_id": stakingTxHash} - res := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + res := db.collection(model.BTCDelegationDetailsCollection). FindOne(ctx, filter) var delegationDoc model.BTCDelegationDetails @@ -266,8 +261,7 @@ func (db *Database) UpdateDelegationsStateByFinalityProvider( }, } - result, err := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + result, err := db.collection(model.BTCDelegationDetailsCollection). UpdateMany(ctx, filter, update) if err != nil { return fmt.Errorf("failed to update delegations: %w", err) @@ -289,8 +283,7 @@ func (db *Database) GetDelegationsByFinalityProvider( "finality_provider_btc_pks_hex": fpBTCPKHex, } - cursor, err := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + cursor, err := db.collection(model.BTCDelegationDetailsCollection). Find(ctx, filter) if err != nil { return nil, fmt.Errorf("failed to find delegations: %w", err) @@ -322,8 +315,7 @@ func (db *Database) SaveBTCDelegationSlashingTxHex( "slashing_tx.spending_height": spendingHeight, }, } - result, err := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + result, err := db.collection(model.BTCDelegationDetailsCollection). UpdateOne(ctx, filter, update) if err != nil { return err @@ -352,8 +344,7 @@ func (db *Database) SaveBTCDelegationUnbondingSlashingTxHex( "slashing_tx.spending_height": spendingHeight, }, } - result, err := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + result, err := db.collection(model.BTCDelegationDetailsCollection). UpdateOne(ctx, filter, update) if err != nil { return err @@ -381,8 +372,7 @@ func (db *Database) GetBTCDelegationsByStates( filter := bson.M{"state": bson.M{"$in": stateStrings}} - cursor, err := db.client.Database(db.dbName). - Collection(model.BTCDelegationDetailsCollection). + cursor, err := db.collection(model.BTCDelegationDetailsCollection). Find(ctx, filter) if err != nil { return nil, err diff --git a/internal/db/finality_provider.go b/internal/db/finality_provider.go index d3f9531..5440e87 100644 --- a/internal/db/finality_provider.go +++ b/internal/db/finality_provider.go @@ -12,8 +12,7 @@ import ( func (db *Database) SaveNewFinalityProvider( ctx context.Context, fpDoc *model.FinalityProviderDetails, ) error { - _, err := db.client.Database(db.dbName). - Collection(model.FinalityProviderDetailsCollection). + _, err := db.collection(model.FinalityProviderDetailsCollection). InsertOne(ctx, fpDoc) if err != nil { var writeErr mongo.WriteException @@ -59,8 +58,7 @@ func (db *Database) UpdateFinalityProviderDetailsFromEvent( // Perform the update only if there are fields to update if len(updateFields) > 0 { - res, err := db.client.Database(db.dbName). - Collection(model.FinalityProviderDetailsCollection). + res, err := db.collection(model.FinalityProviderDetailsCollection). UpdateOne( ctx, bson.M{"_id": detailsToUpdate.BtcPk}, bson.M{"$set": updateFields}, ) @@ -87,7 +85,7 @@ func (db *Database) UpdateFinalityProviderState( update := map[string]interface{}{"$set": map[string]string{"state": newState}} // Perform the find and update - res := db.client.Database(db.dbName).Collection(model.FinalityProviderDetailsCollection). + res := db.collection(model.FinalityProviderDetailsCollection). FindOneAndUpdate(ctx, filter, update) // Check if the document was found @@ -108,8 +106,7 @@ func (db *Database) GetFinalityProviderByBtcPk( ctx context.Context, btcPk string, ) (*model.FinalityProviderDetails, error) { filter := map[string]interface{}{"_id": btcPk} - res := db.client.Database(db.dbName). - Collection(model.FinalityProviderDetailsCollection). + res := db.collection(model.FinalityProviderDetailsCollection). FindOne(ctx, filter) var fpDoc model.FinalityProviderDetails diff --git a/internal/db/last_processed_height.go b/internal/db/last_processed_height.go index 8442d97..82bd5ed 100644 --- a/internal/db/last_processed_height.go +++ b/internal/db/last_processed_height.go @@ -11,8 +11,7 @@ import ( func (db *Database) GetLastProcessedBbnHeight(ctx context.Context) (uint64, error) { var result model.LastProcessedHeight - err := db.client.Database(db.dbName). - Collection(model.LastProcessedHeightCollection). + err := db.collection(model.LastProcessedHeightCollection). FindOne(ctx, bson.M{}).Decode(&result) if err == mongo.ErrNoDocuments { // If no document exists, return 0 @@ -27,8 +26,6 @@ func (db *Database) GetLastProcessedBbnHeight(ctx context.Context) (uint64, erro func (db *Database) UpdateLastProcessedBbnHeight(ctx context.Context, height uint64) error { update := bson.M{"$set": bson.M{"height": height}} opts := options.Update().SetUpsert(true) - _, err := db.client.Database(db.dbName). - Collection(model.LastProcessedHeightCollection). - UpdateOne(ctx, bson.M{}, update, opts) + _, err := db.collection(model.LastProcessedHeightCollection).UpdateOne(ctx, bson.M{}, update, opts) return err } diff --git a/internal/db/params.go b/internal/db/params.go index 2e636ef..17f4eed 100644 --- a/internal/db/params.go +++ b/internal/db/params.go @@ -23,7 +23,7 @@ const ( func (db *Database) SaveStakingParams( ctx context.Context, version uint32, params *bbnclient.StakingParams, ) error { - collection := db.client.Database(db.dbName).Collection(model.GlobalParamsCollection) + collection := db.collection(model.GlobalParamsCollection) doc := &model.StakingParamsDocument{ BaseParamsDocument: model.BaseParamsDocument{ @@ -46,7 +46,7 @@ func (db *Database) SaveStakingParams( func (db *Database) SaveCheckpointParams( ctx context.Context, params *bbnclient.CheckpointParams, ) error { - collection := db.client.Database(db.dbName).Collection(model.GlobalParamsCollection) + collection := db.collection(model.GlobalParamsCollection) doc := &model.CheckpointParamsDocument{ BaseParamsDocument: model.BaseParamsDocument{ @@ -67,8 +67,7 @@ func (db *Database) SaveCheckpointParams( } func (db *Database) GetStakingParams(ctx context.Context, version uint32) (*bbnclient.StakingParams, error) { - collection := db.client.Database(db.dbName). - Collection(model.GlobalParamsCollection) + collection := db.collection(model.GlobalParamsCollection) filter := bson.M{ "type": STAKING_PARAMS_TYPE, diff --git a/internal/db/timelock.go b/internal/db/timelock.go index 1420b8b..2da82b5 100644 --- a/internal/db/timelock.go +++ b/internal/db/timelock.go @@ -17,14 +17,12 @@ func (db *Database) SaveNewTimeLockExpire( subState types.DelegationSubState, ) error { tlDoc := model.NewTimeLockDocument(stakingTxHashHex, expireHeight, subState) - _, err := db.client.Database(db.dbName). - Collection(model.TimeLockCollection). - InsertOne(ctx, tlDoc) + _, err := db.collection(model.TimeLockCollection).InsertOne(ctx, tlDoc) return err } func (db *Database) FindExpiredDelegations(ctx context.Context, btcTipHeight, limit uint64) ([]model.TimeLockDocument, error) { - client := db.client.Database(db.dbName).Collection(model.TimeLockCollection) + client := db.collection(model.TimeLockCollection) filter := bson.M{"expire_height": bson.M{"$lte": btcTipHeight}} opts := options.Find().SetLimit(int64(limit)) @@ -43,7 +41,7 @@ func (db *Database) FindExpiredDelegations(ctx context.Context, btcTipHeight, li } func (db *Database) DeleteExpiredDelegation(ctx context.Context, stakingTxHashHex string) error { - client := db.client.Database(db.dbName).Collection(model.TimeLockCollection) + client := db.collection(model.TimeLockCollection) filter := bson.M{"staking_tx_hash_hex": stakingTxHashHex} result, err := client.DeleteOne(ctx, filter)