mirror of
https://github.com/Such-Software/wownerogue.git
synced 2026-11-26 00:53:53 +01:00
add address modal and try to fix payout
This commit is contained in:
@@ -3,6 +3,10 @@
|
||||
* Handles detection, pending confirmation, validation, and persistence of payout addresses.
|
||||
* Keeps socketHandlers slimmer by encapsulating this concern.
|
||||
*/
|
||||
const { AppError, normalizeError } = require('../utils/errors');
|
||||
|
||||
const ADDRESS_REGEX = /((?:4|8)[1-9A-HJ-NP-Za-km-z]{90,110}|(?:Wo|WO|ww|WW)[0-9A-Za-z]{88,112}|W[0-9A-Za-z]{90,112})/;
|
||||
|
||||
class AddressManager {
|
||||
constructor({ gameModeManager, broadcastManager, io, debugManager, onConfirmed = null }) {
|
||||
this.gameModeManager = gameModeManager;
|
||||
@@ -15,11 +19,18 @@ class AddressManager {
|
||||
|
||||
detectInText(text) {
|
||||
if (!text || typeof text !== 'string') return null;
|
||||
const re = /((?:4|8)[0-9A-Za-z]{90,110}|Wo[0-9A-Za-z]{88,110})/; // Monero / Wownero style
|
||||
const m = text.match(re);
|
||||
if (!m) return null;
|
||||
if (m[1].length < 80) return null;
|
||||
return m[1];
|
||||
const match = text.match(ADDRESS_REGEX);
|
||||
if (!match) return null;
|
||||
const candidate = match[1];
|
||||
return this.isValidAddress(candidate) ? candidate : null;
|
||||
}
|
||||
|
||||
isValidAddress(address) {
|
||||
const value = typeof address === 'string' ? address.trim() : '';
|
||||
if (!value) return false;
|
||||
if (!ADDRESS_REGEX.test(value)) return false;
|
||||
// Basic length guard for sanity (allowing integrated addresses)
|
||||
return value.length >= 80 && value.length <= 120;
|
||||
}
|
||||
|
||||
async handleDetection(socketId, address) {
|
||||
@@ -27,7 +38,9 @@ class AddressManager {
|
||||
if (this.gameModeManager) {
|
||||
const userRow = await this.gameModeManager.getOrCreateUser(socketId);
|
||||
if (userRow && userRow.payout_address === address) {
|
||||
this.io.to(socketId).emit('address_confirmed', { address, message: 'Payout address already set.' });
|
||||
const shortAddr = address.slice(0, 10) + '…' + address.slice(-6);
|
||||
this.io.to(socketId).emit('address_confirmed', { address, message: `Payout address already set to ${shortAddr}. You can update it via the address manager.` });
|
||||
this.broadcastManager?.sendStatusUpdate(socketId, 'info', 'Address already on file. Use the address button/command to replace it.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -40,6 +53,29 @@ class AddressManager {
|
||||
this.broadcastManager?.sendStatusUpdate(socketId, 'info', 'Address detected. Type confirm or cancel.');
|
||||
}
|
||||
|
||||
async saveAddress(socketId, address, { autoConfirm = true } = {}) {
|
||||
const trimmed = typeof address === 'string' ? address.trim() : '';
|
||||
if (!trimmed) {
|
||||
throw new AppError('No payout address supplied', {
|
||||
safeMessage: 'Please enter a payout address.'
|
||||
});
|
||||
}
|
||||
|
||||
if (!this.isValidAddress(trimmed)) {
|
||||
throw new AppError('Invalid payout address format', {
|
||||
safeMessage: 'That does not look like a valid XMR/WOW address.'
|
||||
});
|
||||
}
|
||||
|
||||
this.pending.set(socketId, trimmed);
|
||||
|
||||
if (autoConfirm) {
|
||||
await this.confirm(socketId, true);
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
async confirm(socketId, accept) {
|
||||
const pending = this.pending.get(socketId);
|
||||
if (!pending) {
|
||||
@@ -61,7 +97,8 @@ class AddressManager {
|
||||
this.broadcastManager?.sendStatusUpdate(socketId, 'success', 'Payout address saved.');
|
||||
this.io.to(socketId).emit('address_confirmed', { address: pending, message: 'Payout address saved.' });
|
||||
} catch (e) {
|
||||
this.broadcastManager?.sendStatusUpdate(socketId, 'error', 'Failed to save address. Try again.');
|
||||
const normalized = normalizeError?.(e, 'Failed to save address') || e;
|
||||
this.broadcastManager?.sendStatusUpdate(socketId, 'error', normalized.safeMessage || 'Failed to save address. Try again.');
|
||||
return;
|
||||
} finally {
|
||||
this.pending.delete(socketId);
|
||||
|
||||
@@ -102,6 +102,10 @@ class ChatHandler {
|
||||
|
||||
// Private helper methods
|
||||
|
||||
async promptAddress(socket) {
|
||||
await this._promptAddress(socket);
|
||||
}
|
||||
|
||||
async _handleAddressDetection(socket, detected) {
|
||||
// Rate limiting for address setting
|
||||
const rateLimitResult = await this.rateLimiter.checkLimit(socket.id, 'address:set');
|
||||
@@ -150,8 +154,7 @@ class ChatHandler {
|
||||
|
||||
case 'address':
|
||||
case 'payout':
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'info',
|
||||
'Please paste your XMR/WOW address directly in chat. The system will automatically detect and confirm it.');
|
||||
await this._promptAddress(socket);
|
||||
return true;
|
||||
|
||||
case 'payment':
|
||||
@@ -217,6 +220,31 @@ class ChatHandler {
|
||||
console.log(`🧹 ChatHandler cleanup: removed ${cleanedCount} old timestamps`);
|
||||
}
|
||||
}
|
||||
|
||||
async _promptAddress(socket) {
|
||||
let existing = null;
|
||||
try {
|
||||
if (this.gameModeManager) {
|
||||
const userRow = await this.gameModeManager.getOrCreateUser(socket.id);
|
||||
existing = userRow?.payout_address || null;
|
||||
}
|
||||
} catch (e) {
|
||||
if (this.debugManager?.CONSOLE_LOGGING) {
|
||||
console.warn('Address prompt lookup failed:', e.message);
|
||||
}
|
||||
}
|
||||
|
||||
socket.emit('address_prompt', {
|
||||
existingAddress: existing,
|
||||
canUpdate: true
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'info', 'Update your payout address using the address manager.');
|
||||
} else {
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'info', 'Add your payout address to receive rewards.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ChatHandler;
|
||||
@@ -15,6 +15,7 @@ const ConnectionHandler = require('./connectionHandler');
|
||||
const ChatHandler = require('./chatHandler');
|
||||
const QueueHandler = require('./queueHandler');
|
||||
const MemoryManager = require('../utils/memoryManager');
|
||||
const { normalizeError } = require('../utils/errors');
|
||||
|
||||
class SocketHandlers {
|
||||
constructor(io, activeGames, broadcastManager, debugManager, gameModeManager = null, walletService = null) {
|
||||
@@ -149,7 +150,7 @@ class SocketHandlers {
|
||||
io: this.io,
|
||||
debugManager: this.debugManager,
|
||||
moveCooldown: this.MOVE_COOLDOWN,
|
||||
postMoveHook: ({ socketId, game }) => this.afterPlayerMove(socketId, game)
|
||||
postMoveHook: ({ socketId, game, moveResult }) => this.afterPlayerMove(socketId, game, moveResult)
|
||||
});
|
||||
|
||||
// Register memory cleanup functions
|
||||
@@ -245,6 +246,10 @@ class SocketHandlers {
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof game.moveMonster === 'function') {
|
||||
game.moveMonster();
|
||||
}
|
||||
|
||||
// Build updated state
|
||||
let state;
|
||||
if (typeof game.getState === 'function') {
|
||||
@@ -269,24 +274,35 @@ class SocketHandlers {
|
||||
* Called after a successful player move (before update is emitted) via MovementManager postMoveHook.
|
||||
* Handles monster chasing logic and immediate game over if monster catches player.
|
||||
*/
|
||||
afterPlayerMove(socketId, game) {
|
||||
afterPlayerMove(socketId, game, moveResult) {
|
||||
let monsterResult = null;
|
||||
|
||||
// Move monster one step toward player each player action
|
||||
if (game && typeof game.moveMonster === 'function') {
|
||||
try {
|
||||
game.moveMonster();
|
||||
monsterResult = game.moveMonster();
|
||||
} catch (e) {
|
||||
console.error('Monster move error:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if monster catches player
|
||||
try {
|
||||
if (game && game.monster && game.player && game.monster.x === game.player.x && game.monster.y === game.player.y) {
|
||||
const fakeSocket = { id: socketId };
|
||||
this.handleGameOver(fakeSocket, game, 'lost', 'monster', 'You were caught by the monster!', 0);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Monster catch check error:', e);
|
||||
// If the monster caught the player, end the game immediately
|
||||
if (monsterResult && monsterResult.event === 'monster_caught') {
|
||||
const fakeSocket = { id: socketId };
|
||||
this.handleGameOver(fakeSocket, game, 'lost', 'monster', 'You were caught by the monster!', 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// If player escaped or triggered another event, handle via game manager
|
||||
if (moveResult && moveResult.event === 'escaped') {
|
||||
const fakeSocket = { id: socketId };
|
||||
this.handleGameOver(fakeSocket, game, 'won', 'escaped', 'You escaped the dungeon!', 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-emit state if treasure collected without auto game_update (fallback)
|
||||
if (moveResult && moveResult.event === 'treasure_found') {
|
||||
this.movementManager.emitGameUpdate(socketId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,16 +319,18 @@ class SocketHandlers {
|
||||
handleCancelEntry: (socket) => this.queueHandler.handleCancelEntry(socket),
|
||||
handleStatsRequest: (socket) => this.handleStatsRequest(socket)
|
||||
}));
|
||||
socket.on('player_move', (moveData) => this.movementManager.handleMove(socket.id, moveData));
|
||||
socket.on('player_move', (moveData) => this.movementManager.handleMove(socket.id, moveData));
|
||||
socket.on('disconnect', () => this.handleDisconnect(socket));
|
||||
socket.on('debug_ping', (data) => this.handleDebugPing(socket, data));
|
||||
socket.on('register_client', (data) => this.connectionHandler.handleRegisterClient(socket, data));
|
||||
socket.on('auto_start', () => this.handleAutoStart(socket)); // New handler for start button
|
||||
socket.on('address:prompt', () => this.handleAddressPrompt(socket));
|
||||
|
||||
// Payment system handlers
|
||||
socket.on('request_payment', (data) => this.paymentHandlers.handlePaymentRequest(socket, data));
|
||||
socket.on('check_payment_status', (data) => this.handleCheckPaymentStatus(socket, data));
|
||||
socket.on('get_user_credits', () => this.handleGetUserCredits(socket));
|
||||
socket.on('address:update', (data) => this.handleAddressUpdate(socket, data));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -408,6 +426,62 @@ class SocketHandlers {
|
||||
}
|
||||
}
|
||||
|
||||
async handleAddressPrompt(socket) {
|
||||
try {
|
||||
if (this.chatHandler && typeof this.chatHandler.promptAddress === 'function') {
|
||||
await this.chatHandler.promptAddress(socket);
|
||||
return;
|
||||
}
|
||||
|
||||
let existingAddress = null;
|
||||
if (this.gameModeManager) {
|
||||
try {
|
||||
const userRow = await this.gameModeManager.getOrCreateUser(socket.id);
|
||||
existingAddress = userRow?.payout_address || null;
|
||||
} catch (err) {
|
||||
if (this.debugManager?.CONSOLE_LOGGING) {
|
||||
console.warn('Address prompt lookup failed:', err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.io.to(socket.id).emit('address_prompt', {
|
||||
existingAddress,
|
||||
message: existingAddress ? 'Update your payout address anytime.' : 'Add a payout address to receive rewards.'
|
||||
});
|
||||
} catch (error) {
|
||||
const normalized = normalizeError(error, 'Unable to open address manager');
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'error', normalized.safeMessage || 'Address manager unavailable.');
|
||||
}
|
||||
}
|
||||
|
||||
async handleAddressUpdate(socket, data) {
|
||||
try {
|
||||
const address = typeof data?.address === 'string' ? data.address.trim() : '';
|
||||
if (!address) {
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'warning', 'Please enter a payout address before saving.');
|
||||
this.io.to(socket.id).emit('address_update_error', { message: 'Please enter a payout address before saving.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const rateLimitResult = await this.rateLimiter.checkLimit(socket.id, 'address:set');
|
||||
if (!rateLimitResult.allowed) {
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'warning',
|
||||
`Address changes are rate limited. Try again in ${Math.ceil(rateLimitResult.retryAfter / 1000)} seconds.`);
|
||||
this.io.to(socket.id).emit('address_update_error', { message: 'Address changes are temporarily rate limited.' });
|
||||
return;
|
||||
}
|
||||
|
||||
await this.rateLimiter.recordAttempt(socket.id, 'address:set');
|
||||
|
||||
await this.addressManager.saveAddress(socket.id, address);
|
||||
} catch (err) {
|
||||
const normalized = normalizeError?.(err, 'Failed to update payout address') || err;
|
||||
this.broadcastManager.sendStatusUpdate(socket.id, 'error', normalized.safeMessage || 'Failed to update payout address.');
|
||||
this.io.to(socket.id).emit('address_update_error', { message: normalized.safeMessage || 'Failed to update payout address.' });
|
||||
}
|
||||
}
|
||||
|
||||
/** Return the active socket instance by id (io.sockets.sockets Map) */
|
||||
_getLiveSocket(socketId) {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user