mpcium icon indicating copy to clipboard operation
mpcium copied to clipboard

Issue: Transactions Stuck in PENDING/COMPLETED Status Without Timeout

Open anhthii opened this issue 10 months ago • 0 comments

Problem Statement

Transactions that fail to get receipts or cannot be finalized remain stuck in PENDING or COMPLETED status indefinitely. There is no mechanism to automatically mark these transactions as FAILED after a reasonable timeout period.

Current Behavior

Retry Mechanism

File: internal/eventconsumer/retry_finalize_tx_event.go

  • Retry limit: 3 attempts within 5 minutes (TTL)
  • When max retries exceeded: Only logs a warning and stops retrying
  • Does NOT update transaction status to FAILED
const (
    maxFinalizeRetries      = 3
    finalizeRetryCounterTTL = 5 * time.Minute
)

if retryCount > maxFinalizeRetries {
    logger.Warn("Reached max finalize retries, skip scheduling new attempt", ...)
    return  // Just stops retrying, doesn't update status
}

Scheduled Job Fallback

File: internal/scheduler/job_finalize_tx.go

  • Runs every 3 minutes
  • Picks up transactions with:
    • Status: PENDING or COMPLETED
    • Created > 3 minutes ago
    • Updated within last 7 days
  • After 7 days, transactions are no longer picked up but remain in PENDING/COMPLETED status

Transaction Finality Check

File: pkg/blockchain/rpccontainer/evm_container.go:154-170

When receipt is not available:

receipt, err := httpClient.TransactionReceipt(ctx, common.HexToHash(txHash))
if err != nil {
    return false, fmt.Errorf("failed to get tx receipt for %s: %w", txHash, err)
}
if receipt == nil {
    logger.Info("Transaction found but receipt not yet available", "txHash", txHash)
    return false, nil  // Not finalized, no error - will retry
}

Impact

  1. Stuck Transactions: Transactions remain in PENDING/COMPLETED status forever
  2. Database Pollution: Accumulation of failed transactions that never get cleaned up
  3. User Confusion: Users don't know if their transaction failed or is still processing
  4. Asset Holds: If transaction has asset_hold_id, the hold is never released
  5. Webhook Never Sent: Users waiting for confirmation webhooks never receive failure notifications

Root Cause Analysis

Scenario 1: Transaction Never Broadcasted

  • Signing failed silently
  • Network error during broadcast
  • Invalid transaction parameters

Scenario 2: Transaction Dropped from Mempool

  • Bitcoin: Mempool drops after 72 hours to 14 days (node-dependent)
  • EVM: Usually dropped after a few hours with wrong nonce or low gas
  • RPC provider issues

Scenario 3: Receipt Fetch Failures

  • RPC provider temporarily down
  • Network connectivity issues
  • Transaction hash invalid

Existing TODO Comment

File: internal/scheduler/job_finalize_tx.go:48

// TODO: if finalzing a transaction failed 3 times in a row -> Set to failed

This confirms the feature is missing and was intended to be implemented.

Proposed Solution

Network-Specific Timeouts

Different blockchains have different confirmation characteristics:

Blockchain Type Normal Confirmation Congested Network Recommended Timeout
Bitcoin < 1 hour Up to 48 hours 72 hours (3 days)
EVM Chains < 5 minutes < 30 minutes 12 hours
Solana < 1 minute < 5 minutes 6 hours
Other Varies Varies 24 hours

Timeout Types

  1. No Receipt Timeout (transaction not mined)

    • Bitcoin: 72 hours
    • EVM: 12 hours
    • Solana: 6 hours
    • Aptos: 12 hours
    • Tron: 12 hours
  2. Absolute Maximum Timeout (any stuck transaction)

    • Keep existing: 7 days
    • Catches edge cases and ensures nothing is stuck forever

Why These Numbers Are Safe

Bitcoin (72 hours):

  • Normal confirmation: < 1 hour
  • Extreme congestion with low fee: up to 48 hours
  • Most nodes drop mempool transactions after 72 hours if unconfirmed
  • 72 hours provides safety margin without being overly conservative

EVM (12 hours):

  • Normal receipt availability: < 5 minutes after mining
  • 12 hours is extremely conservative
  • Covers RPC provider outages and network issues
  • If no receipt after 12 hours, transaction is almost certainly failed

Solana (6 hours):

  • Block time: ~400ms
  • Normal confirmation: < 1 minute
  • 6 hours is very generous for a fast chain

Implementation Plan

1. Add Network Configuration

File: pkg/model/network.go or similar

type Network struct {
    // ... existing fields
    NoReceiptTimeoutSeconds int64 `gorm:"column:no_receipt_timeout_seconds"`
}

func (n *Network) GetNoReceiptTimeout() time.Duration {
    if n.NoReceiptTimeoutSeconds > 0 {
        return time.Duration(n.NoReceiptTimeoutSeconds) * time.Second
    }

    // Default timeouts based on blockchain type
    if n.IsEvm {
        return 12 * time.Hour
    } else if strings.HasPrefix(n.InternalCode, "BTC") {
        return 72 * time.Hour
    } else if strings.HasPrefix(n.InternalCode, "SOL") {
        return 6 * time.Hour
    }

    return 24 * time.Hour // Default
}

2. Update Transaction Finalizer

File: pkg/blockchain/txfinalizer/finalizer.go

Add timeout checking logic:

func (t *txFinalizer) finalizeTx(txID string) (shouldRetry bool, network *model.Network) {
    // ... existing code to fetch tx and network

    // Check if transaction has exceeded timeout
    noReceiptTimeout := network.GetNoReceiptTimeout()
    absoluteTimeout := 7 * 24 * time.Hour

    txAge := time.Since(tx.CreatedAt)

    // Check absolute timeout first
    if txAge > absoluteTimeout {
        logger.Error("Transaction exceeded absolute timeout, marking as failed",
            "txID", txID,
            "age", txAge,
            "timeout", absoluteTimeout)
        t.markTransactionAsFailed(tx, "Transaction timeout: exceeded 7 days")
        return false, nil
    }

    isFinalized, err := txFinalityChecker.IsTxFinalized(network.InternalCode, *tx.TxHash, tx.BlockNumber)
    if err != nil {
        if errors.Is(err, rpccontainer.ErrTxFailed) {
            logger.Info("Tx failed", "txID", txID)
            t.markTransactionAsFailed(tx, "Transaction execution failed")
            return false, nil
        }

        // Check no-receipt timeout only for "receipt not available" errors
        if strings.Contains(err.Error(), "failed to get tx receipt") {
            if txAge > noReceiptTimeout {
                logger.Error("Transaction exceeded no-receipt timeout, marking as failed",
                    "txID", txID,
                    "age", txAge,
                    "timeout", noReceiptTimeout,
                    "network", network.InternalCode)
                t.markTransactionAsFailed(tx, "Transaction timeout: no receipt available")
                return false, nil
            }
        }

        logger.Error("Failed to check tx finality", err, "txID", txID)
        return true, network
    }

    if !isFinalized {
        logger.Info("Tx not finalized", "txID", txID)
        return true, network
    }

    // ... rest of existing finalization logic
}

func (t *txFinalizer) markTransactionAsFailed(tx *model.Transaction, reason string) error {
    ctx := context.Background()

    updateTx := model.Transaction{
        Status: enum.TxStatusFailed,
        ErrorReason: &reason,
    }

    transaction, err := t.TxsRepository.UpdateByID(ctx, tx.ID, updateTx)
    if err != nil {
        logger.Error("Failed to update tx status to failed", err, "txID", tx.ID)
        return err
    }

    // Clear asset hold if exists
    if transaction.AssetHoldID != nil {
        err = t.AssetHoldRepository.ClearHold(ctx, *transaction.AssetHoldID)
        if err != nil {
            logger.Error("Failed to clear asset hold", err, "txID", tx.ID)
        }
    }

    // Send failure notification
    if tx.Direction == enum.TxDirectionOut && tx.Type == enum.TxTypeWithdrawal {
        t.sendWithdrawalFailureNotification(transaction, reason)
        t.publishWithdrawalFailedWebhook(transaction, reason)
    }

    return nil
}

3. Add Transaction Model Field

File: pkg/model/transaction.go

type Transaction struct {
    // ... existing fields
    ErrorReason *string `gorm:"column:error_reason;type:text"`
}

4. Database Migration

ALTER TABLE transactions ADD COLUMN error_reason TEXT;
ALTER TABLE networks ADD COLUMN no_receipt_timeout_seconds BIGINT;

-- Set default timeouts for existing networks
UPDATE networks SET no_receipt_timeout_seconds = 259200 WHERE internal_code LIKE 'BTC%'; -- 72 hours
UPDATE networks SET no_receipt_timeout_seconds = 43200 WHERE is_evm = true; -- 12 hours
UPDATE networks SET no_receipt_timeout_seconds = 21600 WHERE internal_code LIKE 'SOL%'; -- 6 hours

5. Update Retry Logic

File: internal/eventconsumer/retry_finalize_tx_event.go

Consider adjusting retry logic:

  • Current: 3 retries within 5 minutes (too aggressive)
  • Better: Use network-specific retry schedule based on block times
const (
    maxFinalizeRetries = 10  // Increase retry count
    finalizeRetryCounterTTL = 24 * time.Hour  // Longer TTL
)

Testing Plan

  1. Unit Tests:

    • Test timeout calculations for different network types
    • Test markTransactionAsFailed logic
    • Test asset hold clearing
  2. Integration Tests:

    • Create transactions with old timestamps
    • Verify they get marked as failed after timeout
    • Verify webhooks are sent
  3. Manual Testing:

    • Test with actual RPC failures
    • Test with dropped transactions
    • Verify notifications are sent

Backward Compatibility

  • Existing transactions: Will start being checked with new timeout logic
  • No breaking API changes
  • Database migration is additive only

Success Metrics

  1. No transactions older than configured timeout remain in PENDING/COMPLETED
  2. Asset holds are properly released for failed transactions
  3. Users receive failure notifications/webhooks
  4. Database query performance remains acceptable

Related Files

  • pkg/blockchain/txfinalizer/finalizer.go - Main finalization logic
  • pkg/blockchain/rpccontainer/evm_container.go - Receipt checking
  • internal/eventconsumer/retry_finalize_tx_event.go - Retry logic
  • internal/scheduler/job_finalize_tx.go - Scheduled job
  • pkg/common/enum/transaction.go - Transaction status enums
  • pkg/model/transaction.go - Transaction model
  • pkg/model/network.go - Network configuration

Priority

HIGH - This prevents transactions from being stuck indefinitely and impacts user experience and system reliability.

anhthii avatar Jan 11 '26 10:01 anhthii