From 244a58420493b6770897e25a11baf9c2a21504ba Mon Sep 17 00:00:00 2001 From: jwinterm Date: Wed, 24 Dec 2025 12:30:14 -0500 Subject: [PATCH] feat: add payout retry tracking and HOSTED_BY footer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Payout retry system: - Add migration 007 with retry_count, last_error, last_retry_at columns - Payouts now retry up to PAYOUT_MAX_RETRIES times before permanent failure - Each failure logs the attempt number and error message - Console shows ⚠️ for retryable failures, 💀 for permanent failures - Added SQL examples in .env.example for querying/resetting failed payouts HOSTED_BY feature: - Add HOSTED_BY and HOSTED_BY_NAME env vars - /api/game-modes endpoint returns hostedBy info - Footer displays 'Hosted by: ' when configured Also improved .env.example: - Better documentation for credit packages with reasonable defaults - Clearer explanation of retry behavior --- html/index.html | 17 +- src/.env.example | 419 +++++++++++++++------- src/index.js | 20 +- src/migrations/007_payout_retry_count.sql | 18 + src/payments/moneroPayService.js | 49 ++- 5 files changed, 386 insertions(+), 137 deletions(-) create mode 100644 src/migrations/007_payout_retry_count.sql diff --git a/html/index.html b/html/index.html index 4ed4aa6..2997e30 100644 --- a/html/index.html +++ b/html/index.html @@ -33,6 +33,20 @@ const warn = document.getElementById('sessionWarning'); if (warn) warn.style.display = 'inline'; } + // Fetch server config and populate hosted-by footer + fetch('/api/game-modes') + .then(function(res) { return res.json(); }) + .then(function(data) { + if (data.hostedBy && data.hostedBy.url) { + var container = document.getElementById('hosted-by-container'); + if (container) { + container.innerHTML = ' | Hosted by: ' + + (data.hostedBy.name || data.hostedBy.url) + ''; + } + } + }) + .catch(function() { /* ignore errors */ }); }); })(); @@ -202,7 +216,8 @@ diff --git a/src/.env.example b/src/.env.example index 52d5c1f..dda1ea5 100644 --- a/src/.env.example +++ b/src/.env.example @@ -3,147 +3,314 @@ # ============================================================================= # Copy this file to .env and customize for your environment. # The server validates these settings at startup and warns about misconfigurations. +# +# QUICK START CONFIGURATIONS: +# --------------------------- +# 1. FREE MODE (no payments, just play): +# PAYMENTS_ENABLED=false +# +# 2. PAID MODE (1 WOW per game, 2x payout on win): +# PAYMENTS_ENABLED=true +# PAYMENT_MODES=direct +# + Configure wallet RPC and database +# +# 3. CREDITS MODE (buy bundles, play multiple games): +# PAYMENTS_ENABLED=true +# PAYMENT_MODES=credits +# + Configure wallet RPC and database +# +# 4. BOTH MODES (let users choose): +# PAYMENTS_ENABLED=true +# PAYMENT_MODES=direct,credits -# ----------------------------------------------------------------------------- -# Network Selection -# ----------------------------------------------------------------------------- -# For Wownero: Only mainnet exists (this setting is ignored) -# For Monero: mainnet | stagenet | testnet -# ⚠️ STAGENET WARNING: Stagenet XMR has no real value! Only for testing. +# ============================================================================= +# UNDERSTANDING ATOMIC UNITS +# ============================================================================= +# Wownero (like Monero) uses "atomic units" - the smallest indivisible unit. +# +# 1 WOW = 100,000,000,000 atomic units (10^11, or 100 billion) +# +# Examples: +# 1 WOW = 100000000000 +# 0.5 WOW = 50000000000 +# 0.1 WOW = 10000000000 +# 5 WOW = 500000000000 +# 10 WOW = 1000000000000 +# +# Why? Floating point math is imprecise. Atomic units ensure exact calculations. + +# ============================================================================= +# SECTION 1: BASIC SERVER SETTINGS +# ============================================================================= + +# Server port (default: 3000) +PORT=3000 + +# Environment: production | development | debug +# - production: minimal logging, real blockchain +# - development: verbose logging, can use simulated blocks +# - debug: maximum logging, debug hotkeys enabled +NODE_ENV=production + +# Network selection (only matters for Monero - Wownero only has mainnet) MONERO_NETWORK=mainnet -# ----------------------------------------------------------------------------- -# Difficulty Presets -# ----------------------------------------------------------------------------- -# Presets: easy | normal | hard | casino -# easy - Small dungeon, slow monster (~70% player win rate) -# normal - Balanced difficulty (~45% player win rate) -# hard - Large dungeon, aggressive monster (~35% player win rate) -# casino - Maximum house edge (~30% player win rate) - DEFAULT for paid modes -# Leave unset to auto-select based on payment mode. -# DIFFICULTY_PRESET=casino +# Optional: Display "Hosted by" link in footer (leave empty to hide) +# Example: https://yoursite.com or https://github.com/yourname +# HOSTED_BY=https://example.com +# HOSTED_BY_NAME=Example Host -# ----------------------------------------------------------------------------- -# Payment System -# ----------------------------------------------------------------------------- -# Master switch for payments. Set false for FREE mode (no payments required). -PAYMENTS_ENABLED=true +# ============================================================================= +# SECTION 2: DATABASE (PostgreSQL) - REQUIRED +# ============================================================================= +# The game stores user sessions, payment history, and credits in PostgreSQL. +# You must create the database and user first (see README). -# Payment modes: direct | credits | direct,credits (comma-separated) -# direct - Pay per game, eligible for payouts on win -# credits - Buy credit packages, spend 1 credit per game -# Enabling both allows users to choose; users with credits use them first. -PAYMENT_MODES=direct,credits - -# ----------------------------------------------------------------------------- -# Direct Mode (pay-per-game) -# ----------------------------------------------------------------------------- -DIRECT_PAYMENT_ENABLED=true -DIRECT_GAME_PRICE=100000000000 # Price in atomic units (1 WOW = 1e11) -DIRECT_REQUIRES_ADDRESS=true # Require payout address before playing -DIRECT_ALLOW_GUEST_PLAY=false # Allow play without payout address - -# Direct mode payouts -# ⚠️ Requires PRIMARY_WALLET_ENDPOINT to be configured! -DIRECT_PAYOUTS_ENABLED=true -DIRECT_PAYOUT_ESCAPE=2.0 # Multiplier for escaping the dungeon -DIRECT_PAYOUT_TREASURE=3.0 # Multiplier for finding treasure - -# ----------------------------------------------------------------------------- -# Credits Mode (buy packages, spend per game) -# ----------------------------------------------------------------------------- -CREDITS_ENABLED=true -CREDITS_PER_GAME=1 # Credits consumed per game -CREDITS_REQUIRES_ADDRESS=true # Require payout address for credits mode -ALLOW_MIXED_MODE=true # Allow both direct and credits options -PREFER_CREDITS_FIRST=true # Auto-use credits if available - -# Credits mode payouts (usually disabled - credits are a bulk discount) -# ⚠️ If enabled, requires PRIMARY_WALLET_ENDPOINT! -CREDITS_PAYOUTS_ENABLED=false -CREDITS_PAYOUT_BASE=50000000000 # Base payout per credit win -CREDITS_PAYOUT_ESCAPE=1.5 -CREDITS_PAYOUT_TREASURE=2.0 - -# Credit packages (JSON array) -# Each package: { id, credits, price (atomic units string), bonus (extra free credits) } -# ⚠️ Must be valid JSON! Server validates at startup. -CREDITS_PACKAGES='[{"id":"small","credits":10,"price":"500000000000","bonus":0},{"id":"medium","credits":25,"price":"1000000000000","bonus":2},{"id":"large","credits":100,"price":"3500000000000","bonus":15}]' - -# ----------------------------------------------------------------------------- -# Global Payout Settings -# ----------------------------------------------------------------------------- -PAYOUTS_ENABLED=true -PAYOUT_MIN_AMOUNT=10000000000 # 0.1 WOW minimum payout -PAYOUT_MAX_PER_GAME=10000000000000 # Max payout per single game -PAYOUT_BATCH_INTERVAL=300 # Seconds between payout batches (5 min) -PAYOUT_MAX_RETRIES=3 # Retry failed payouts -MAX_PAYOUT_BATCH_SIZE=50 # Max payouts per batch - -# ----------------------------------------------------------------------------- -# Anti-Abuse Limits -# ----------------------------------------------------------------------------- -MAX_GAMES_PER_HOUR=60 -MAX_PAYOUTS_PER_DAY=100 -MAX_CREDIT_PURCHASE_PER_DAY=100000000000000 -GAME_COOLDOWN_SECONDS=5 - -# ----------------------------------------------------------------------------- -# Wallet RPC (required for paid modes) -# ----------------------------------------------------------------------------- -# Run wownero-wallet-rpc or monero-wallet-rpc with --rpc-bind-port -# ⚠️ Without this, payments and payouts will fail! -PRIMARY_WALLET_ENDPOINT=http://127.0.0.1:34570 -# WALLET_RPC_USER=user -# WALLET_RPC_PASSWORD=password - -# ----------------------------------------------------------------------------- -# Blockchain RPC (daemon) -# ----------------------------------------------------------------------------- -PRIMARY_RPC_ENDPOINT=http://127.0.0.1:34568 -FALLBACK_RPC_ENDPOINT=http://127.0.0.1:34568 -RPC_POLL_INTERVAL=2000 # Milliseconds between block polls - -# ----------------------------------------------------------------------------- -# Database (PostgreSQL) -# ----------------------------------------------------------------------------- DB_HOST=localhost DB_PORT=5432 DB_NAME=wownerogue -DB_USER=your_db_user -DB_PASSWORD=your_db_password +DB_USER=wownerogue +DB_PASSWORD=your_secure_password_here -# ----------------------------------------------------------------------------- -# Server -# ----------------------------------------------------------------------------- -PORT=3000 -NODE_ENV=production +# ============================================================================= +# SECTION 3: GAME DIFFICULTY +# ============================================================================= +# Controls dungeon size, monster behavior, and effective house edge. +# +# Preset | Dungeon | Monster Speed | Player Win Rate | Best For +# ------------|----------|---------------|-----------------|------------------ +# easy | 30x15 | Slow | ~70% | Free play, demos +# normal | 45x22 | Medium | ~45% | Balanced gameplay +# hard | 55x28 | Fast | ~35% | Challenge mode +# casino | 60x30 | Very Fast | ~30% | Paid modes (default) +# +# If unset, defaults to 'casino' for paid modes, 'normal' for free mode. +# DIFFICULTY_PRESET=casino -# ----------------------------------------------------------------------------- -# Admin API -# ----------------------------------------------------------------------------- -# Required for admin endpoints: /api/admin/refund/payment, /api/admin/credits/adjust, etc. -# Generate a secure key: openssl rand -hex 32 -# Pass as X-Admin-Key header when calling admin endpoints. -# ADMIN_API_KEY=your-secure-random-key-here +# ============================================================================= +# SECTION 4: PAYMENT SYSTEM OVERVIEW +# ============================================================================= +# +# PAYMENTS_ENABLED is the master switch: +# false = FREE mode, anyone can play, no crypto involved +# true = Paid mode, requires wallet RPC configuration +# +# PAYMENT_MODES determines HOW users pay (when payments enabled): +# +# ┌─────────────────────────────────────────────────────────────────────────┐ +# │ MODE: direct │ +# ├─────────────────────────────────────────────────────────────────────────┤ +# │ • User pays X WOW per game │ +# │ • If they WIN (escape dungeon): get PAYOUT_ESCAPE × X back (e.g., 2x) │ +# │ • If they WIN with treasure: get PAYOUT_TREASURE × X back (e.g., 3x) │ +# │ • If they LOSE (die): house keeps the payment │ +# │ │ +# │ Example: Pay 1 WOW, win = get 2 WOW. Die = lose 1 WOW. │ +# └─────────────────────────────────────────────────────────────────────────┘ +# +# ┌─────────────────────────────────────────────────────────────────────────┐ +# │ MODE: credits │ +# ├─────────────────────────────────────────────────────────────────────────┤ +# │ • User buys a PACKAGE of credits upfront (e.g., 10 credits for 5 WOW) │ +# │ • Each game costs 1 credit (or CREDITS_PER_GAME) │ +# │ • Packages can include bonus credits (bulk discount) │ +# │ • Payouts are optional - credits are usually just for playing │ +# │ │ +# │ Example: Buy 10 credits for 5 WOW = 0.5 WOW/game (50% discount!) │ +# └─────────────────────────────────────────────────────────────────────────┘ +# +# ┌─────────────────────────────────────────────────────────────────────────┐ +# │ MODE: direct,credits (both enabled) │ +# ├─────────────────────────────────────────────────────────────────────────┤ +# │ • Users can choose which mode to use │ +# │ • If PREFER_CREDITS_FIRST=true, credits are auto-used when available │ +# │ • Good for giving users flexibility │ +# └─────────────────────────────────────────────────────────────────────────┘ -# ----------------------------------------------------------------------------- -# Block Simulation (Development Only) -# ----------------------------------------------------------------------------- -# BLOCK_SOURCE: daemon (real blockchain) | simulated (fake blocks for testing) -# In paid modes, defaults to daemon. In FREE mode, defaults to simulated. +# Master switch: Set to false for completely free play (no wallet needed) +PAYMENTS_ENABLED=true + +# Which payment modes to enable (comma-separated) +PAYMENT_MODES=direct,credits + +# ============================================================================= +# SECTION 5: DIRECT MODE CONFIGURATION +# ============================================================================= +# Only relevant if PAYMENT_MODES includes "direct" + +# Enable/disable direct payments +DIRECT_PAYMENT_ENABLED=true + +# Price per game in atomic units (100000000000 = 1 WOW) +DIRECT_GAME_PRICE=100000000000 + +# Must user provide a payout address before playing? +# true = User must set address first (ensures they can receive winnings) +# false = User can play without address (but can't receive payouts!) +DIRECT_REQUIRES_ADDRESS=true + +# Allow guest play without any address? (Usually false for paid modes) +DIRECT_ALLOW_GUEST_PLAY=false + +# Payout multipliers for direct mode wins: +# If user pays 1 WOW and ESCAPE multiplier is 2.0, they get 2 WOW on escape. +DIRECT_PAYOUTS_ENABLED=true +DIRECT_PAYOUT_ESCAPE=2.0 # Escape dungeon = 2x payment +DIRECT_PAYOUT_TREASURE=3.0 # Escape WITH treasure = 3x payment + +# ============================================================================= +# SECTION 6: CREDITS MODE CONFIGURATION +# ============================================================================= +# Only relevant if PAYMENT_MODES includes "credits" + +# Enable/disable credits system +CREDITS_ENABLED=true + +# How many credits does one game cost? +CREDITS_PER_GAME=1 + +# Must user provide address for credits mode? +CREDITS_REQUIRES_ADDRESS=true + +# When both modes enabled: +ALLOW_MIXED_MODE=true # Show both options to user +PREFER_CREDITS_FIRST=true # Auto-deduct credits if user has them + +# Credits payouts (usually DISABLED - credits are a bulk discount, not gambling) +CREDITS_PAYOUTS_ENABLED=false +CREDITS_PAYOUT_BASE=50000000000 # Base amount for credit wins +CREDITS_PAYOUT_ESCAPE=2.0 # Same as direct mode +CREDITS_PAYOUT_TREASURE=3.0 # Same as direct mode + +# Credit packages - JSON array of available bundles +# Fields: +# id - Unique identifier (shown in UI) +# credits - Number of game credits included +# price - Cost in atomic units (as STRING to avoid JS number precision issues) +# bonus - Extra free credits (0 for no bonus) +# +# Default packages (small discounts to encourage bulk purchase): +# small: 10 credits for 9 WOW (~10% discount vs 1 WOW/game direct) +# medium: 20 credits for 17 WOW (~15% discount) +# large: 50 credits for 40 WOW (~20% discount) +# +# Tip: Format JSON with newlines for readability, then minify for .env: +# [ +# {"id":"small", "credits":10, "price":"900000000000", "bonus":0}, +# {"id":"medium", "credits":20, "price":"1700000000000", "bonus":0}, +# {"id":"large", "credits":50, "price":"4000000000000", "bonus":0} +# ] +# +CREDITS_PACKAGES='[{"id":"small","credits":10,"price":"900000000000","bonus":0},{"id":"medium","credits":20,"price":"1700000000000","bonus":0},{"id":"large","credits":50,"price":"4000000000000","bonus":0}]' + +# ============================================================================= +# SECTION 7: PAYOUT SETTINGS +# ============================================================================= +# Controls how winnings are sent back to players. +# Payouts are batched for efficiency and to reduce transaction fees. + +# Master payout switch (disable to accept payments but never pay out - EVIL!) +PAYOUTS_ENABLED=true + +# Minimum payout amount (atomic units). Prevents dust transactions. +# 10000000000 = 0.1 WOW +PAYOUT_MIN_AMOUNT=10000000000 + +# Maximum payout per single game (safety limit) +# 10000000000000 = 100 WOW +PAYOUT_MAX_PER_GAME=10000000000000 + +# How often to process payout queue (seconds). 300 = every 5 minutes. +PAYOUT_BATCH_INTERVAL=300 + +# Retry failed payouts this many times before marking as permanently failed. +# Failed payouts are logged with error details. Check logs or query: +# SELECT * FROM payouts WHERE status = 'failed'; +# To retry a permanently failed payout, reset it with: +# UPDATE payouts SET status = 'pending', retry_count = 0 WHERE id = ; +PAYOUT_MAX_RETRIES=3 + +# Max payouts to send in one batch (wallet RPC can timeout on large batches) +MAX_PAYOUT_BATCH_SIZE=50 + +# ============================================================================= +# SECTION 8: ANTI-ABUSE LIMITS +# ============================================================================= +# Protect against bots and abuse + +MAX_GAMES_PER_HOUR=60 # Max games one user can play per hour +MAX_PAYOUTS_PER_DAY=100 # Max payout transactions per user per day +MAX_CREDIT_PURCHASE_PER_DAY=100000000000000 # Max credit purchase (1000 WOW) +GAME_COOLDOWN_SECONDS=5 # Minimum seconds between games + +# ============================================================================= +# SECTION 9: WALLET RPC - REQUIRED FOR PAID MODES +# ============================================================================= +# The wallet RPC handles: +# 1. Generating unique payment addresses for each user +# 2. Checking for incoming payments +# 3. Sending payouts to winners +# +# You must run wownero-wallet-rpc (or monero-wallet-rpc) separately: +# +# wownero-wallet-rpc \ +# --wallet-file /path/to/wallet \ +# --password "wallet-password" \ +# --rpc-bind-port 34570 \ +# --rpc-login user:password \ +# --disable-rpc-login # OR use rpc-login for security +# +# The wallet must be synced with a daemon to see incoming transactions. + +PRIMARY_WALLET_ENDPOINT=http://127.0.0.1:34570 + +# If your wallet-rpc uses --rpc-login, set credentials here: +# WALLET_RPC_USER=user +# WALLET_RPC_PASSWORD=password + +# ============================================================================= +# SECTION 10: BLOCKCHAIN DAEMON RPC +# ============================================================================= +# Used to get current block height for game synchronization. +# This is the daemon (wownerod/monerod), NOT the wallet. +# +# The game syncs to block timing - each block triggers game state checks. + +PRIMARY_RPC_ENDPOINT=http://127.0.0.1:34568 +FALLBACK_RPC_ENDPOINT=http://127.0.0.1:34568 + +# How often to poll for new blocks (milliseconds) +RPC_POLL_INTERVAL=2000 + +# ============================================================================= +# SECTION 11: ADMIN API +# ============================================================================= +# Secure endpoints for refunds, credit adjustments, and user management. +# Generate a strong random key and keep it secret! + +# Generate with: openssl rand -hex 32 +# ADMIN_API_KEY=your-64-character-hex-key-here + +# Use in requests: +# curl -H "X-Admin-Key: your-key" http://localhost:3000/api/admin/... + +# ============================================================================= +# SECTION 12: DEVELOPMENT/DEBUG OPTIONS +# ============================================================================= +# These are for testing only. Don't use in production with real money! + +# Block source: daemon (real blockchain) | simulated (fake blocks for testing) +# Paid modes always use daemon unless FORCE_SIMULATED_BLOCKS=true BLOCK_SOURCE=daemon -# SIMULATED_BLOCKS=false + +# Force simulated blocks even in paid mode (DANGEROUS - for testing only!) # FORCE_SIMULATED_BLOCKS=false -# ----------------------------------------------------------------------------- -# Legacy Configuration (deprecated, kept for compatibility) -# ----------------------------------------------------------------------------- +# ============================================================================= +# LEGACY OPTIONS (deprecated - use PAYMENT_MODES instead) +# ============================================================================= # GAME_MODE: FREE | PAID_SINGLE | PAID_CREDITS -# If set, overrides PAYMENT_MODES. Prefer using PAYMENT_MODES instead. +# Kept for backward compatibility. New setups should use PAYMENT_MODES. # GAME_MODE= -# Legacy prices (used if PAYMENT_MODES not set) CRYPTO_TYPE=WOW -# SINGLE_GAME_PRICE=1e11 -# CREDITS_PACKAGE_PRICE=5e11 diff --git a/src/index.js b/src/index.js index 2c3cecc..3ef2975 100644 --- a/src/index.js +++ b/src/index.js @@ -682,6 +682,23 @@ app.get('/api/game-modes', (req, res) => { const directMode = config.modes.direct; const creditsMode = config.modes.credits; + // Include hosted by info if configured + let hostedBy = null; + if (process.env.HOSTED_BY) { + let hostname = process.env.HOSTED_BY_NAME; + if (!hostname) { + try { + hostname = new URL(process.env.HOSTED_BY).hostname; + } catch (e) { + hostname = process.env.HOSTED_BY; // Use raw value if URL parsing fails + } + } + hostedBy = { + url: process.env.HOSTED_BY, + name: hostname + }; + } + res.json({ FREE: { name: 'Free Play', @@ -703,7 +720,8 @@ app.get('/api/game-modes', (req, res) => { payoutMultiplier: creditsMode.enabled && config.payouts.rules.credits.enabled ? config.payouts.rules.credits.multipliers : 0 - } + }, + hostedBy }); }); diff --git a/src/migrations/007_payout_retry_count.sql b/src/migrations/007_payout_retry_count.sql new file mode 100644 index 0000000..eed4337 --- /dev/null +++ b/src/migrations/007_payout_retry_count.sql @@ -0,0 +1,18 @@ +-- Migration 007: Add retry tracking for failed payouts +-- Allows payouts to be retried up to PAYOUT_MAX_RETRIES times before permanent failure + +-- Add retry_count column to track attempts +ALTER TABLE payouts ADD COLUMN IF NOT EXISTS retry_count INTEGER DEFAULT 0; + +-- Add last_error column to store the most recent failure reason +ALTER TABLE payouts ADD COLUMN IF NOT EXISTS last_error TEXT; + +-- Add last_retry_at to track when the last retry happened +ALTER TABLE payouts ADD COLUMN IF NOT EXISTS last_retry_at TIMESTAMP; + +-- Create index for finding payouts that need retry +CREATE INDEX IF NOT EXISTS idx_payouts_retry ON payouts(status, retry_count) WHERE status = 'pending'; + +-- Update any existing failed payouts to have retry_count = max (so they stay failed) +-- This prevents old failures from being retried unexpectedly +UPDATE payouts SET retry_count = 999 WHERE status = 'failed' AND retry_count = 0; diff --git a/src/payments/moneroPayService.js b/src/payments/moneroPayService.js index aacec10..96c7f1f 100644 --- a/src/payments/moneroPayService.js +++ b/src/payments/moneroPayService.js @@ -196,16 +196,18 @@ class MoneroPayService { * Process pending payouts in batches */ async processPendingPayouts() { + const maxRetries = parseInt(process.env.PAYOUT_MAX_RETRIES) || 3; + try { const maxBatchSize = parseInt(process.env.MAX_PAYOUT_BATCH_SIZE) || 50; - // Get pending payouts + // Get pending payouts that haven't exceeded retry limit const payouts = await this.db.query(` SELECT * FROM payouts - WHERE status = 'pending' + WHERE status = 'pending' AND (retry_count IS NULL OR retry_count < $1) ORDER BY created_at ASC - LIMIT $1 - `, [maxBatchSize]); + LIMIT $2 + `, [maxRetries, maxBatchSize]); if (payouts.rows.length === 0) { return { processed: 0, message: 'No pending payouts' }; @@ -264,12 +266,41 @@ class MoneroPayService { } catch (error) { console.error('❌ Failed to process payouts:', error.message); - // Mark failed payouts - await this.db.query(` - UPDATE payouts - SET status = 'failed' - WHERE status = 'pending' AND created_at < NOW() - INTERVAL '1 hour' + // Increment retry count for pending payouts, mark as failed if max retries exceeded + const pendingPayouts = await this.db.query(` + SELECT id, retry_count FROM payouts + WHERE status = 'pending' `); + + for (const payout of pendingPayouts.rows) { + const newRetryCount = (payout.retry_count || 0) + 1; + const errorMessage = error.message || 'Unknown error'; + + if (newRetryCount >= maxRetries) { + // Max retries exceeded - mark as permanently failed + await this.db.query(` + UPDATE payouts + SET status = 'failed', + retry_count = $1, + last_error = $2, + last_retry_at = NOW() + WHERE id = $3 + `, [newRetryCount, errorMessage, payout.id]); + + console.error(`💀 Payout ${payout.id} permanently failed after ${newRetryCount} attempts: ${errorMessage}`); + } else { + // Increment retry count, will try again next batch + await this.db.query(` + UPDATE payouts + SET retry_count = $1, + last_error = $2, + last_retry_at = NOW() + WHERE id = $3 + `, [newRetryCount, errorMessage, payout.id]); + + console.warn(`⚠️ Payout ${payout.id} failed (attempt ${newRetryCount}/${maxRetries}): ${errorMessage}`); + } + } throw error; }