mirror of
https://github.com/Such-Software/wownerogue.git
synced 2026-11-21 06:34:08 +01:00
add error handling and more tests
This commit is contained in:
+7
-11
@@ -1,16 +1,16 @@
|
||||
# Wowgue Game Configuration
|
||||
# Wowngeon Server Configuration
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Unified Payment System (recommended configuration)
|
||||
# -----------------------------------------------------------------------------
|
||||
PAYMENTS_ENABLED=true
|
||||
|
||||
# Enable one or both modes (comma separated list: direct,credits)
|
||||
# Enable one or both monetized modes (comma separated list: direct,credits)
|
||||
PAYMENT_MODES=direct,credits
|
||||
|
||||
# Direct mode settings
|
||||
# Direct (per-run) mode settings
|
||||
DIRECT_PAYMENT_ENABLED=true
|
||||
DIRECT_GAME_PRICE=100000000000 # 1 WOW in atomic units
|
||||
DIRECT_GAME_PRICE=100000000000 # 1 WOW in atomic units (1e11)
|
||||
DIRECT_REQUIRES_ADDRESS=true
|
||||
DIRECT_ALLOW_GUEST_PLAY=false
|
||||
DIRECT_PAYOUTS_ENABLED=true
|
||||
@@ -27,11 +27,7 @@ CREDITS_PAYOUTS_ENABLED=false
|
||||
CREDITS_PAYOUT_BASE=50000000000 # 0.5 WOW per credit payout baseline
|
||||
CREDITS_PAYOUT_ESCAPE=1.5
|
||||
CREDITS_PAYOUT_TREASURE=2.0
|
||||
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}
|
||||
]'
|
||||
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 payouts / limits
|
||||
PAYOUTS_ENABLED=true
|
||||
@@ -62,12 +58,12 @@ CREDITS_PACKAGE_PRICE=5e11 # 5 WOW (atomic units)
|
||||
# SINGLE_GAME_PRICE=5e9 # 0.005 XMR (5000000000)
|
||||
# CREDITS_PACKAGE_PRICE=5e10 # 0.05 XMR (50000000000)
|
||||
|
||||
# Wallet RPC Configuration
|
||||
# Wallet RPC Configuration (required for paid modes)
|
||||
PRIMARY_WALLET_ENDPOINT=http://127.0.0.1:34570
|
||||
# WALLET_RPC_USER=user
|
||||
# WALLET_RPC_PASSWORD=password
|
||||
|
||||
# Blockchain RPC Configuration
|
||||
# Blockchain RPC Configuration (daemon URLs)
|
||||
PRIMARY_RPC_ENDPOINT=http://127.0.0.1:34568
|
||||
FALLBACK_RPC_ENDPOINT=http://127.0.0.1:34568
|
||||
RPC_POLL_INTERVAL=2000
|
||||
|
||||
+49
-64
@@ -3,26 +3,18 @@
|
||||
* Handles different game modes (FREE, PAID_SINGLE, PAID_CREDITS)
|
||||
*/
|
||||
|
||||
const {
|
||||
DEFAULT_DECIMALS,
|
||||
parseAtomicEnvValue,
|
||||
inferCurrencyDecimals: inferCurrencyDecimalsForSymbol,
|
||||
formatAtomic,
|
||||
formatAtomicHuman,
|
||||
getDecimalDivisor
|
||||
} = require('./helpers/gameModeUtils');
|
||||
const { ValidationError, normalizeError } = require('../utils/errors');
|
||||
|
||||
const DEFAULT_SINGLE_GAME_PRICE = 5000000000; // 0.005 XMR or 0.05 WOW depending on currency decimals
|
||||
const DEFAULT_CREDITS_PACKAGE_PRICE = 50000000000;
|
||||
const DEFAULT_DECIMALS = 12;
|
||||
|
||||
const parseAtomicEnvValue = (val, fallback) => {
|
||||
if (val === undefined || val === null || val === '') return fallback;
|
||||
if (typeof val !== 'string') {
|
||||
const numVal = Number(val);
|
||||
return Number.isFinite(numVal) ? Math.trunc(numVal) : fallback;
|
||||
}
|
||||
const cleaned = val.replace(/_/g, '').trim();
|
||||
if (!cleaned) {
|
||||
return fallback;
|
||||
}
|
||||
const num = Number(cleaned);
|
||||
if (!Number.isFinite(num) || num < 0) {
|
||||
return fallback;
|
||||
}
|
||||
return Math.trunc(num);
|
||||
};
|
||||
|
||||
class GameModeManager {
|
||||
constructor(databaseManager, walletRPCService, debugManager, paymentConfigManager = null) {
|
||||
@@ -65,11 +57,7 @@ class GameModeManager {
|
||||
}
|
||||
|
||||
inferCurrencyDecimals(symbol) {
|
||||
if (!symbol) return DEFAULT_DECIMALS;
|
||||
const normalized = symbol.toUpperCase();
|
||||
if (normalized === 'WOW') return 11;
|
||||
if (normalized === 'XMR') return 12;
|
||||
return DEFAULT_DECIMALS;
|
||||
return inferCurrencyDecimalsForSymbol(symbol);
|
||||
}
|
||||
|
||||
applyLegacyEnvConfig() {
|
||||
@@ -207,32 +195,22 @@ class GameModeManager {
|
||||
}
|
||||
|
||||
formatAtomic(value) {
|
||||
if (value === undefined || value === null) {
|
||||
return '0';
|
||||
}
|
||||
const decimals = Number.isFinite(this.currencyDecimals) ? this.currencyDecimals : DEFAULT_DECIMALS;
|
||||
const divisor = Math.pow(10, decimals);
|
||||
const quotient = Number(value) / divisor;
|
||||
return Number.isFinite(quotient)
|
||||
? quotient.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')
|
||||
: value.toString();
|
||||
return formatAtomic({
|
||||
value,
|
||||
decimals: Number.isFinite(this.currencyDecimals) ? this.currencyDecimals : DEFAULT_DECIMALS
|
||||
});
|
||||
}
|
||||
|
||||
getDecimalDivisor() {
|
||||
const decimals = Number.isFinite(this.currencyDecimals) ? this.currencyDecimals : DEFAULT_DECIMALS;
|
||||
return Math.pow(10, decimals);
|
||||
return getDecimalDivisor(Number.isFinite(this.currencyDecimals) ? this.currencyDecimals : DEFAULT_DECIMALS);
|
||||
}
|
||||
|
||||
formatAtomicHuman(value, digits = 3) {
|
||||
if (value === undefined || value === null) {
|
||||
return '0';
|
||||
}
|
||||
const divisor = this.getDecimalDivisor();
|
||||
const quotient = Number(value) / divisor;
|
||||
if (!Number.isFinite(quotient)) {
|
||||
return value.toString();
|
||||
}
|
||||
return quotient.toFixed(digits);
|
||||
return formatAtomicHuman({
|
||||
value,
|
||||
decimals: Number.isFinite(this.currencyDecimals) ? this.currencyDecimals : DEFAULT_DECIMALS,
|
||||
digits
|
||||
});
|
||||
}
|
||||
|
||||
getPrimaryCreditPackage() {
|
||||
@@ -334,8 +312,9 @@ class GameModeManager {
|
||||
return { allowed: false, reason: 'Invalid game mode' };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error checking user game eligibility:', error.message);
|
||||
return { allowed: false, reason: 'Database error' };
|
||||
const normalized = normalizeError(error, 'Unable to verify game eligibility');
|
||||
console.error('❌ Error checking user game eligibility:', normalized.message);
|
||||
return { allowed: false, reason: normalized.safeMessage };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -406,8 +385,9 @@ class GameModeManager {
|
||||
return { success: false, reason: 'Invalid game mode' };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('❌ Error processing game start:', error.message);
|
||||
return { success: false, reason: 'Database error' };
|
||||
const normalized = normalizeError(error, 'Failed to process game start');
|
||||
console.error('❌ Error processing game start:', normalized.message);
|
||||
return { success: false, reason: normalized.safeMessage };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -474,8 +454,9 @@ class GameModeManager {
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error processing game completion:', error.message);
|
||||
return { success: false, reason: 'Database error' };
|
||||
const normalized = normalizeError(error, 'Failed to process game completion');
|
||||
console.error('❌ Error processing game completion:', normalized.message);
|
||||
return { success: false, reason: normalized.safeMessage };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,7 +487,9 @@ class GameModeManager {
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error('Invalid payment type');
|
||||
throw new ValidationError(`Invalid payment type requested: ${paymentType}`, {
|
||||
safeMessage: 'Unsupported payment type requested.'
|
||||
});
|
||||
}
|
||||
|
||||
// Create payment request using wallet RPC with correct parameters
|
||||
@@ -517,10 +500,6 @@ class GameModeManager {
|
||||
socketId
|
||||
);
|
||||
|
||||
if (!paymentResult.success) {
|
||||
throw new Error(paymentResult.error || 'Failed to create payment address');
|
||||
}
|
||||
|
||||
// Store payment info in database
|
||||
await this.db.query(`
|
||||
INSERT INTO payments (user_id, socket_id, subaddress, expected_amount, payment_type, status, created_at)
|
||||
@@ -538,8 +517,9 @@ class GameModeManager {
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error creating payment request:', error.message);
|
||||
throw error;
|
||||
const normalized = normalizeError(error, 'Failed to create payment request');
|
||||
console.error('❌ Error creating payment request:', normalized.message);
|
||||
throw normalized;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -575,8 +555,9 @@ class GameModeManager {
|
||||
return userResult.rows[0];
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error getting/creating user:', error.message);
|
||||
throw error;
|
||||
const normalized = normalizeError(error, 'Failed to load user');
|
||||
console.error('❌ Error getting/creating user:', normalized.message);
|
||||
throw normalized;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -598,7 +579,8 @@ class GameModeManager {
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error setting payout address:', error.message);
|
||||
const normalized = normalizeError(error, 'Failed to update payout address');
|
||||
console.error('❌ Error setting payout address:', normalized.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -627,7 +609,8 @@ class GameModeManager {
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error getting user stats:', error.message);
|
||||
const normalized = normalizeError(error, 'Failed to load user stats');
|
||||
console.error('❌ Error getting user stats:', normalized.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -708,8 +691,9 @@ class GameModeManager {
|
||||
}
|
||||
};
|
||||
} catch (payoutErr) {
|
||||
console.error('❌ Error creating payout:', payoutErr.message);
|
||||
return { success: true, mode: this.gameMode, payout: null, payoutError: payoutErr.message };
|
||||
const normalizedPayout = normalizeError(payoutErr, 'Failed to send payout');
|
||||
console.error('❌ Error creating payout:', normalizedPayout.message);
|
||||
return { success: true, mode: this.gameMode, payout: null, payoutError: normalizedPayout.safeMessage };
|
||||
}
|
||||
}
|
||||
return { success: true, mode: this.gameMode, payout: null, reason: 'No payout address' };
|
||||
@@ -718,8 +702,9 @@ class GameModeManager {
|
||||
// Credits mode: decrement nothing here (already handled start). Optionally could award stats.
|
||||
return { success: true, mode: this.gameMode, payout: null };
|
||||
} catch (err) {
|
||||
console.error('❌ completeGame error:', err.message);
|
||||
return { success: false, error: err.message };
|
||||
const normalized = normalizeError(err, 'Failed to complete game');
|
||||
console.error('❌ completeGame error:', normalized.message);
|
||||
return { success: false, error: normalized.safeMessage };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
const DEFAULT_DECIMALS = 12;
|
||||
|
||||
const parseAtomicEnvValue = (val, fallback) => {
|
||||
if (val === undefined || val === null || val === '') return fallback;
|
||||
if (typeof val !== 'string') {
|
||||
const numVal = Number(val);
|
||||
return Number.isFinite(numVal) ? Math.trunc(numVal) : fallback;
|
||||
}
|
||||
const cleaned = val.replace(/_/g, '').trim();
|
||||
if (!cleaned) {
|
||||
return fallback;
|
||||
}
|
||||
const num = Number(cleaned);
|
||||
if (!Number.isFinite(num) || num < 0) {
|
||||
return fallback;
|
||||
}
|
||||
return Math.trunc(num);
|
||||
};
|
||||
|
||||
const inferCurrencyDecimals = (symbol) => {
|
||||
if (!symbol) return DEFAULT_DECIMALS;
|
||||
const normalized = symbol.toUpperCase();
|
||||
if (normalized === 'WOW') return 11;
|
||||
if (normalized === 'XMR') return 12;
|
||||
return DEFAULT_DECIMALS;
|
||||
};
|
||||
|
||||
const getDecimalDivisor = (decimals = DEFAULT_DECIMALS) => {
|
||||
const normalized = Number.isFinite(decimals) ? decimals : DEFAULT_DECIMALS;
|
||||
return Math.pow(10, normalized);
|
||||
};
|
||||
|
||||
const formatAtomic = ({ value, decimals, digits = 6 }) => {
|
||||
if (value === undefined || value === null) {
|
||||
return '0';
|
||||
}
|
||||
const divisor = getDecimalDivisor(decimals);
|
||||
const quotient = Number(value) / divisor;
|
||||
if (!Number.isFinite(quotient)) {
|
||||
return value.toString();
|
||||
}
|
||||
return quotient.toFixed(digits).replace(/0+$/, '').replace(/\.$/, '');
|
||||
};
|
||||
|
||||
const formatAtomicHuman = ({ value, decimals, digits = 3 }) => {
|
||||
if (value === undefined || value === null) {
|
||||
return '0';
|
||||
}
|
||||
const divisor = getDecimalDivisor(decimals);
|
||||
const quotient = Number(value) / divisor;
|
||||
if (!Number.isFinite(quotient)) {
|
||||
return value.toString();
|
||||
}
|
||||
return quotient.toFixed(digits);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_DECIMALS,
|
||||
parseAtomicEnvValue,
|
||||
inferCurrencyDecimals,
|
||||
getDecimalDivisor,
|
||||
formatAtomic,
|
||||
formatAtomicHuman
|
||||
};
|
||||
+59
-59
@@ -15,6 +15,9 @@ const GameModeManager = require('./game/gameModeManager');
|
||||
const RpcService = require('./rpc/rpcService');
|
||||
const PaymentConfigManager = require('./config/paymentConfig');
|
||||
const EnvironmentValidator = require('./config/environmentValidator');
|
||||
const asyncHandler = require('./middleware/asyncHandler');
|
||||
const createErrorMiddleware = require('./middleware/errorHandler');
|
||||
const { AppError, ValidationError, NotFoundError } = require('./utils/errors');
|
||||
|
||||
// Import modular components
|
||||
const BroadcastManager = require('./network/broadcastManager');
|
||||
@@ -61,50 +64,38 @@ app.post('/debug', (req, res) => {
|
||||
});
|
||||
|
||||
// Payment system API endpoints
|
||||
app.post('/api/payment/create', async (req, res) => {
|
||||
try {
|
||||
const { userId, gameMode } = req.body;
|
||||
if (!userId || !gameMode) {
|
||||
return res.status(400).json({ error: 'Missing userId or gameMode' });
|
||||
}
|
||||
|
||||
const payment = await walletRPCService.createPaymentRequest(userId, gameMode);
|
||||
res.json(payment);
|
||||
} catch (error) {
|
||||
console.error('Error creating payment:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
app.post('/api/payment/create', asyncHandler(async (req, res) => {
|
||||
const { userId, gameMode } = req.body || {};
|
||||
if (!userId || !gameMode) {
|
||||
throw new ValidationError('Missing userId or gameMode', {
|
||||
safeMessage: 'userId and gameMode are required to create a payment.'
|
||||
});
|
||||
}
|
||||
|
||||
throw new AppError('REST payment creation endpoint is not implemented for unified payments', {
|
||||
statusCode: 501,
|
||||
code: 'NOT_IMPLEMENTED',
|
||||
safeMessage: 'Payment creation via REST API is not available. Please use the in-game flow.'
|
||||
});
|
||||
}));
|
||||
|
||||
const restNotImplemented = () => new AppError('Endpoint not available in unified payment system', {
|
||||
statusCode: 501,
|
||||
code: 'NOT_IMPLEMENTED',
|
||||
safeMessage: 'This API endpoint is not available. Please use the supported in-game flow.'
|
||||
});
|
||||
|
||||
app.post('/api/payment/callback', async (req, res) => {
|
||||
try {
|
||||
const result = await walletRPCService.processCallback(req.body);
|
||||
res.json({ status: 'success', result });
|
||||
} catch (error) {
|
||||
console.error('Error processing callback:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
app.post('/api/payment/callback', asyncHandler(async (req, res) => {
|
||||
throw restNotImplemented();
|
||||
}));
|
||||
|
||||
app.get('/api/payment/status/:paymentId', async (req, res) => {
|
||||
try {
|
||||
const status = await walletRPCService.checkPaymentStatus(req.params.paymentId);
|
||||
res.json(status);
|
||||
} catch (error) {
|
||||
console.error('Error checking payment status:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
app.get('/api/payment/status/:paymentId', asyncHandler(async (req, res) => {
|
||||
throw restNotImplemented();
|
||||
}));
|
||||
|
||||
app.get('/api/user/:userId/credits', async (req, res) => {
|
||||
try {
|
||||
const credits = await gameModeManager.getUserCredits(req.params.userId);
|
||||
res.json({ credits });
|
||||
} catch (error) {
|
||||
console.error('Error getting user credits:', error);
|
||||
res.status(500).json({ error: error.message });
|
||||
}
|
||||
});
|
||||
app.get('/api/user/:userId/credits', asyncHandler(async (req, res) => {
|
||||
throw restNotImplemented();
|
||||
}));
|
||||
|
||||
app.get('/api/game-modes', (req, res) => {
|
||||
const config = paymentConfigManager.getConfig();
|
||||
@@ -222,35 +213,35 @@ async function startServer() {
|
||||
console.log('🚀 Wowngeon server listening on *:3000');
|
||||
console.log(`🐛 Debug mode: ${debugManager.getDebugStatus().debugMode ? 'ENABLED' : 'DISABLED'}`);
|
||||
console.log(`💰 Payment system: ${paymentSystemReady ? 'ENABLED' : 'FREE MODE ONLY'}`);
|
||||
const summary = paymentConfigManager.summarize();
|
||||
const enabledModes = [];
|
||||
if (!summary.paymentsEnabled || !paymentSystemReady) {
|
||||
enabledModes.push('FREE');
|
||||
}
|
||||
if (summary.directEnabled && paymentSystemReady) {
|
||||
enabledModes.push('PAID_SINGLE');
|
||||
}
|
||||
if (summary.creditsEnabled && paymentSystemReady) {
|
||||
enabledModes.push('PAID_CREDITS');
|
||||
}
|
||||
if (enabledModes.length === 0) {
|
||||
enabledModes.push(summary.legacyMode || 'FREE');
|
||||
}
|
||||
console.log(`🎮 Available game modes: ${enabledModes.join(', ')}`);
|
||||
const summary = paymentConfigManager.summarize();
|
||||
const enabledModes = [];
|
||||
if (!summary.paymentsEnabled || !paymentSystemReady) {
|
||||
enabledModes.push('FREE');
|
||||
}
|
||||
if (summary.directEnabled && paymentSystemReady) {
|
||||
enabledModes.push('PAID_SINGLE');
|
||||
}
|
||||
if (summary.creditsEnabled && paymentSystemReady) {
|
||||
enabledModes.push('PAID_CREDITS');
|
||||
}
|
||||
if (enabledModes.length === 0) {
|
||||
enabledModes.push(summary.legacyMode || 'FREE');
|
||||
}
|
||||
console.log(`🎮 Available game modes: ${enabledModes.join(', ')}`);
|
||||
});
|
||||
|
||||
// Start batch payout processing if payment system is ready
|
||||
if (paymentSystemReady) {
|
||||
const payoutConfig = paymentConfigManager.getConfig().payouts?.processing || {};
|
||||
const payoutIntervalSeconds = Math.max(1, Number(payoutConfig.batchInterval || 300));
|
||||
const payoutIntervalMs = payoutIntervalSeconds * 1000;
|
||||
if (paymentSystemReady) {
|
||||
const payoutConfig = paymentConfigManager.getConfig().payouts?.processing || {};
|
||||
const payoutIntervalSeconds = Math.max(1, Number(payoutConfig.batchInterval || 300));
|
||||
const payoutIntervalMs = payoutIntervalSeconds * 1000;
|
||||
setInterval(async () => {
|
||||
try {
|
||||
await walletRPCService.processBatchPayouts();
|
||||
} catch (error) {
|
||||
console.error('Error in batch payout processing:', error);
|
||||
}
|
||||
}, payoutIntervalMs);
|
||||
}, payoutIntervalMs);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -259,4 +250,13 @@ async function startServer() {
|
||||
}
|
||||
}
|
||||
|
||||
// Attach 404 and error handlers last
|
||||
app.use((req, res, next) => {
|
||||
next(new NotFoundError(`Route not found: ${req.method} ${req.originalUrl}`, {
|
||||
safeMessage: 'The requested resource was not found.'
|
||||
}));
|
||||
});
|
||||
|
||||
app.use(createErrorMiddleware({ logger: console }));
|
||||
|
||||
startServer();
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
module.exports = function asyncHandler(handler) {
|
||||
return function wrappedHandler(req, res, next) {
|
||||
Promise.resolve(handler(req, res, next)).catch(next);
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
const { normalizeError, isTrustedError } = require('../utils/errors');
|
||||
|
||||
module.exports = function createErrorMiddleware({ logger = console } = {}) {
|
||||
return function errorMiddleware(err, req, res, next) { // eslint-disable-line no-unused-vars
|
||||
const normalized = normalizeError(err);
|
||||
const status = normalized.statusCode || 500;
|
||||
const response = {
|
||||
error: normalized.code || 'INTERNAL_ERROR',
|
||||
message: normalized.safeMessage || 'An unexpected error occurred.'
|
||||
};
|
||||
|
||||
if (normalized.details) {
|
||||
response.details = normalized.details;
|
||||
}
|
||||
|
||||
if (logger && typeof logger.error === 'function') {
|
||||
const logPayload = {
|
||||
message: normalized.message,
|
||||
code: normalized.code,
|
||||
status,
|
||||
path: req.path,
|
||||
method: req.method,
|
||||
trusted: isTrustedError(normalized)
|
||||
};
|
||||
if (normalized.details) {
|
||||
logPayload.details = normalized.details;
|
||||
}
|
||||
if (normalized.cause) {
|
||||
logPayload.cause = normalized.cause?.message || normalized.cause;
|
||||
}
|
||||
logger.error('Request failed', logPayload);
|
||||
}
|
||||
|
||||
res.status(status).json(response);
|
||||
};
|
||||
};
|
||||
@@ -3,6 +3,9 @@
|
||||
* Encapsulates payment request creation, monitoring, mempool detection,
|
||||
* confirmation handling, and queue integration.
|
||||
*/
|
||||
|
||||
const { normalizeError } = require('../utils/errors');
|
||||
|
||||
class PaymentHandlers {
|
||||
constructor({ io, gameModeManager, walletService, debugManager, queueManager, broadcastManager }) {
|
||||
this.io = io;
|
||||
@@ -15,8 +18,8 @@ class PaymentHandlers {
|
||||
this.paymentMonitors = new Map();
|
||||
// Track active monitored address per socket so we can stop on disconnect/expiry
|
||||
this.socketAddressMap = new Map();
|
||||
// Track paymentIds already confirmed (avoid duplicate emits / queue actions)
|
||||
this.confirmedPayments = new Set();
|
||||
// Track paymentIds already confirmed (avoid duplicate emits / queue actions)
|
||||
this.confirmedPayments = new Set();
|
||||
// Periodic cleanup (confirmed payment IDs older than retention window)
|
||||
this._confirmedTimestamps = new Map();
|
||||
this._confirmedRetentionMs = 6 * 60 * 60 * 1000; // 6 hours
|
||||
@@ -57,8 +60,9 @@ class PaymentHandlers {
|
||||
});
|
||||
if (this.debugManager.CONSOLE_LOGGING) console.log(`💳 Payment request created for ${socket.id}: ${paymentRequest.amount}`);
|
||||
} catch (e) {
|
||||
console.error('Error creating payment request:', e);
|
||||
this.io.to(socket.id).emit('payment_error', { error: e.message });
|
||||
const err = normalizeError(e, 'Failed to create payment request');
|
||||
console.error('Error creating payment request:', err.message);
|
||||
this.io.to(socket.id).emit('payment_error', { error: err.safeMessage });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,8 +80,9 @@ class PaymentHandlers {
|
||||
// Do not proceed until address is set
|
||||
return;
|
||||
}
|
||||
} catch(e) {
|
||||
console.error('Address pre-check failed:', e.message);
|
||||
} catch (e) {
|
||||
const err = normalizeError(e, 'Failed to verify payout address');
|
||||
console.error('Address pre-check failed:', err.message);
|
||||
}
|
||||
}
|
||||
const currentUser = socket.id && this.queueManager.getUserBySocket ? this.queueManager.getUserBySocket(socket.id) : null;
|
||||
@@ -139,8 +144,9 @@ class PaymentHandlers {
|
||||
|
||||
this._monitorAddress(socket, paymentRequest, paymentRequest.amount, cryptoType, currentUser);
|
||||
} catch (e) {
|
||||
console.error('Error creating payment request:', e);
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'error', 'Failed to create payment request.');
|
||||
const err = normalizeError(e, 'Failed to create payment request');
|
||||
console.error('Error creating payment request:', err.message);
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'error', err.safeMessage);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const axios = require('axios');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const { ExternalServiceError, AppError } = require('../utils/errors');
|
||||
|
||||
class WalletRPCService {
|
||||
constructor(debugManager) {
|
||||
@@ -53,15 +54,26 @@ class WalletRPCService {
|
||||
});
|
||||
|
||||
if (response.data.error) {
|
||||
throw new Error(response.data.error.message);
|
||||
throw new ExternalServiceError(`Wallet RPC responded with error for method ${method}`, {
|
||||
safeMessage: 'Wallet RPC call failed.',
|
||||
details: response.data.error,
|
||||
cause: response.data.error
|
||||
});
|
||||
}
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
const wrapped = error instanceof ExternalServiceError
|
||||
? error
|
||||
: new ExternalServiceError(`Wallet RPC call failed (${method})`, {
|
||||
safeMessage: 'Wallet RPC call failed.',
|
||||
cause: error
|
||||
});
|
||||
|
||||
if (this.debugManager?.CONSOLE_LOGGING) {
|
||||
console.error(`❌ Wallet RPC call failed (${method}):`, error.message);
|
||||
console.error(`❌ Wallet RPC call failed (${method}):`, wrapped.message);
|
||||
}
|
||||
throw error;
|
||||
throw wrapped;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,8 +124,12 @@ class WalletRPCService {
|
||||
expiresAt: new Date(Date.now() + 30 * 60 * 1000) // 30 minutes
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to create payment address:', error);
|
||||
return { success: false, error: error.message };
|
||||
const wrapped = error instanceof AppError ? error : new ExternalServiceError('Failed to create payment address', {
|
||||
safeMessage: 'Unable to create a payment address at this time.',
|
||||
cause: error
|
||||
});
|
||||
console.error('❌ Failed to create payment address:', wrapped.message);
|
||||
throw wrapped;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,11 +310,12 @@ class WalletRPCService {
|
||||
fee: response.result.fee
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to process payout:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: error.message
|
||||
};
|
||||
const wrapped = error instanceof AppError ? error : new ExternalServiceError('Failed to process payout', {
|
||||
safeMessage: 'Unable to send payout at this time.',
|
||||
cause: error
|
||||
});
|
||||
console.error('❌ Failed to process payout:', wrapped.message);
|
||||
throw wrapped;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
class AppError extends Error {
|
||||
constructor(message, {
|
||||
statusCode = 500,
|
||||
code = 'INTERNAL_ERROR',
|
||||
safeMessage = 'An unexpected error occurred.',
|
||||
isOperational = true,
|
||||
details = null,
|
||||
cause = undefined
|
||||
} = {}) {
|
||||
super(message);
|
||||
this.name = this.constructor.name;
|
||||
this.statusCode = statusCode;
|
||||
this.code = code;
|
||||
this.safeMessage = safeMessage || 'An unexpected error occurred.';
|
||||
this.isOperational = isOperational;
|
||||
this.details = details;
|
||||
if (cause) {
|
||||
this.cause = cause;
|
||||
}
|
||||
Error.captureStackTrace?.(this, this.constructor);
|
||||
}
|
||||
}
|
||||
|
||||
class ValidationError extends AppError {
|
||||
constructor(message, options = {}) {
|
||||
super(message, {
|
||||
statusCode: 400,
|
||||
code: 'VALIDATION_ERROR',
|
||||
safeMessage: message,
|
||||
...options
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class NotFoundError extends AppError {
|
||||
constructor(message, options = {}) {
|
||||
super(message, {
|
||||
statusCode: 404,
|
||||
code: 'NOT_FOUND',
|
||||
safeMessage: options.safeMessage || message,
|
||||
...options
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class ExternalServiceError extends AppError {
|
||||
constructor(message, options = {}) {
|
||||
super(message, {
|
||||
statusCode: options.statusCode || 502,
|
||||
code: options.code || 'EXTERNAL_SERVICE_ERROR',
|
||||
safeMessage: options.safeMessage || 'Upstream service error. Please try again later.',
|
||||
...options
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const isTrustedError = (error) => {
|
||||
return error instanceof AppError && error.isOperational !== false;
|
||||
};
|
||||
|
||||
const normalizeError = (error, fallbackMessage = 'An unexpected error occurred.') => {
|
||||
if (!error) {
|
||||
return new AppError(fallbackMessage);
|
||||
}
|
||||
if (error instanceof AppError) {
|
||||
return error;
|
||||
}
|
||||
return new AppError(error.message || fallbackMessage, {
|
||||
safeMessage: fallbackMessage,
|
||||
cause: error,
|
||||
isOperational: false
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
AppError,
|
||||
ValidationError,
|
||||
NotFoundError,
|
||||
ExternalServiceError,
|
||||
isTrustedError,
|
||||
normalizeError
|
||||
};
|
||||
Reference in New Issue
Block a user