whallets upgrade function

This commit is contained in:
NW 2024-12-16 23:43:44 +00:00
parent d51bc9f0b9
commit 21465022b3
4 changed files with 108 additions and 92 deletions

View File

@ -1,7 +1,8 @@
import db from '../../config/database.js';
import WalletGenerator from '../../utils/walletGenerator.js';
import WalletService from '../../utils/walletService.js';
import WalletUtils from '../../utils/walletUtils.js';
import UserService from "../../services/userService.js";
import WalletService from "../../services/walletService.js";
import bot from "../../context/bot.js";
export default class UserWalletsHandler {
@ -10,91 +11,86 @@ export default class UserWalletsHandler {
const telegramId = msg.from.id;
try {
const user = await UserService.getUserByTelegramId(telegramId.toString());
if (!user) {
await bot.sendMessage(chatId, 'Profile not found. Please use /start to create one.');
return;
}
const user = await UserService.getUserByTelegramId(telegramId.toString());
// Get active crypto wallets only
const cryptoWallets = await db.allAsync(`
SELECT wallet_type, address
FROM crypto_wallets
WHERE user_id = ?
ORDER BY wallet_type
`, [user.id]);
let message = '💰 *Your Active Wallets:*\n\n';
if (cryptoWallets.length > 0) {
const walletService = new WalletService(
cryptoWallets.find(w => w.wallet_type === 'BTC')?.address,
cryptoWallets.find(w => w.wallet_type === 'LTC')?.address,
cryptoWallets.find(w => w.wallet_type === 'TRON')?.address,
cryptoWallets.find(w => w.wallet_type === 'ETH')?.address,
user.id,
Date.now() - 30 * 24 * 60 * 60 * 1000
);
const balances = await walletService.getAllBalances();
let totalUsdValue = 0;
// Show active wallets
for (const [type, balance] of Object.entries(balances)) {
const baseType = this.getBaseWalletType(type);
const wallet = cryptoWallets.find(w =>
w.wallet_type === baseType ||
(type.includes('TRC-20') && w.wallet_type === 'TRON') ||
(type.includes('ERC-20') && w.wallet_type === 'ETH')
);
if (wallet) {
message += `🔐 *${type}*\n`;
message += `├ Balance: ${balance.amount.toFixed(8)} ${type.split(' ')[0]}\n`;
message += `├ Value: $${balance.usdValue.toFixed(2)}\n`;
message += `└ Address: \`${wallet.address}\`\n\n`;
totalUsdValue += balance.usdValue;
}
if (!user) {
await bot.sendMessage(chatId, 'Profile not found. Please use /start to create one.');
return;
}
message += `📊 *Total Balance:* $${totalUsdValue.toFixed(2)}\n`;
} else {
message = 'You don\'t have any active wallets yet.';
}
// Get active crypto wallets only
const cryptoWallets = await db.allAsync(`
SELECT wallet_type, address
FROM crypto_wallets
WHERE user_id = ?
ORDER BY wallet_type
`, [user.id]);
// Check if user has archived wallets
const archivedCount = await db.getAsync(`
SELECT COUNT(*) as count
FROM crypto_wallets
WHERE user_id = ? AND wallet_type LIKE '%_%'
`, [user.id]);
let message = '💰 *Your Active Wallets:*\n\n';
const keyboard = {
inline_keyboard: [
[
{ text: ' Add Crypto Wallet', callback_data: 'add_wallet' },
{ text: '💸 Top Up', callback_data: 'top_up_wallet' }
],
[{ text: '🔄 Refresh Balance', callback_data: 'refresh_balance' }],
[{ text: '📊 Transaction History', callback_data: 'wallet_history' }]
]
};
if (cryptoWallets.length > 0) {
const walletUtilsInstance = new WalletUtils(
cryptoWallets.find(w => w.wallet_type === 'BTC')?.address,
cryptoWallets.find(w => w.wallet_type === 'LTC')?.address,
cryptoWallets.find(w => w.wallet_type === 'TRON')?.address,
cryptoWallets.find(w => w.wallet_type === 'ETH')?.address,
user.id,
Date.now() - 30 * 24 * 60 * 60 * 1000
);
// Add archived wallets button if any exist
if (archivedCount.count > 0) {
keyboard.inline_keyboard.splice(2, 0, [
{ text: `📁 Archived Wallets (${archivedCount.count})`, callback_data: 'view_archived_wallets' }
]);
}
const balances = await walletUtilsInstance.getAllBalances();
let totalUsdValue = 0;
await bot.sendMessage(chatId, message, {
reply_markup: keyboard,
parse_mode: 'Markdown'
});
// Show active wallets
for (const [type, balance] of Object.entries(balances)) {
const baseType = this.getBaseWalletType(type);
const wallet = cryptoWallets.find(w =>
w.wallet_type === baseType ||
(type.includes('TRC-20') && w.wallet_type === 'TRON') ||
(type.includes('ERC-20') && w.wallet_type === 'ETH')
);
if (wallet) {
message += `🔐 *${type}*\n`;
message += `├ Balance: ${balance.amount.toFixed(8)} ${type.split(' ')[0]}\n`;
message += `├ Value: $${balance.usdValue.toFixed(2)}\n`;
message += `└ Address: \`${wallet.address}\`\n\n`;
totalUsdValue += balance.usdValue;
}
}
message += `📊 *Total Balance:* $${totalUsdValue.toFixed(2)}\n`;
} else {
message = 'You don\'t have any active wallets yet.';
}
// Check if user has archived wallets
const archivedCount = await WalletService.getArchivedWalletsCount(user);
const keyboard = {
inline_keyboard: [
[
{ text: ' Add Crypto Wallet', callback_data: 'add_wallet' },
{ text: '💸 Top Up', callback_data: 'top_up_wallet' }
],
[{ text: '🔄 Refresh Balance', callback_data: 'refresh_balance' }]
]
};
// Add archived wallets button if any exist
if (archivedCount > 0) {
keyboard.inline_keyboard.splice(2, 0, [
{ text: `📁 Archived Wallets (${archivedCount})`, callback_data: 'view_archived_wallets' }
]);
}
await bot.sendMessage(chatId, message, {
reply_markup: keyboard,
parse_mode: 'Markdown'
});
} catch (error) {
console.error('Error in showBalance:', error);
await bot.sendMessage(chatId, 'Error loading balance. Please try again.');
console.error('Error in showBalance:', error);
await bot.sendMessage(chatId, 'Error loading balance. Please try again.');
}
}
@ -260,9 +256,9 @@ export default class UserWalletsHandler {
return;
}
let message = '💰 *Available Wallets:*\n\n';
let message = '💰 *Available wallets for replenishment, all you need to do is click on the wallet where you will replenish funds and it will be copied to the clipboard, then paste it on the crypto exchange as the recipient of funds.:*\n\n';
const walletService = new WalletService(
const walletUtilsInstance = new WalletUtils(
cryptoWallets.find(w => w.wallet_type === 'BTC')?.address,
cryptoWallets.find(w => w.wallet_type === 'LTC')?.address,
cryptoWallets.find(w => w.wallet_type === 'TRON')?.address,
@ -271,7 +267,7 @@ export default class UserWalletsHandler {
Date.now() - 30 * 24 * 60 * 60 * 1000
);
const balances = await walletService.getAllBalances();
const balances = await walletUtilsInstance.getAllBalances();
for (const [type, balance] of Object.entries(balances)) {
if (cryptoWallets.some(w => w.wallet_type === type.split(' ')[0] ||
@ -417,7 +413,7 @@ export default class UserWalletsHandler {
}
// Create wallet service instance
const walletService = new WalletService(
const walletUtilsInstance = new WalletUtils(
groupedWallets['BTC']?.[0]?.address,
groupedWallets['LTC']?.[0]?.address,
groupedWallets['TRON']?.[0]?.address,
@ -427,7 +423,7 @@ export default class UserWalletsHandler {
);
// Get all balances
const balances = await walletService.getAllBalances();
const balances = await walletUtilsInstance.getAllBalances();
let message = '📁 *Archived Wallets:*\n\n';

View File

@ -1,5 +1,5 @@
import db from "../config/database.js";
import WalletService from "../utils/walletService.js";
import WalletUtils from "../utils/walletUtils.js";
export default class Wallet {
static getBaseWalletType(walletType) {
@ -50,7 +50,7 @@ export default class Wallet {
static async getActiveWalletsBalance(userId) {
const activeWallets = await this.getActiveWallets(userId);
const walletService = new WalletService(
const walletUtilsInstance = new WalletUtils(
activeWallets.btc,
activeWallets.ltc,
activeWallets.tron,
@ -59,7 +59,7 @@ export default class Wallet {
Date.now() - 30 * 24 * 60 * 60 * 1000
);
const balances = await walletService.getAllBalances();
const balances = await walletUtilsInstance.getAllBalances();
let totalUsdBalance = 0;
@ -86,7 +86,7 @@ export default class Wallet {
static async getArchivedWalletsBalance(userId) {
const archiveWallets = await this.getArchivedWallets(userId);
const walletService = new WalletService(
const walletUtilsInstance = new WalletUtils(
archiveWallets.btc,
archiveWallets.ltc,
archiveWallets.tron,
@ -95,7 +95,7 @@ export default class Wallet {
Date.now() - 30 * 24 * 60 * 60 * 1000
);
const balances = await walletService.getAllBalances();
const balances = await walletUtilsInstance.getAllBalances();
let totalUsdBalance = 0;

View File

@ -1,3 +1,23 @@
class WalletService {
import db from "../config/database.js";
}
class WalletService {
static async getArchivedWalletsCount(user) {
try {
// Получаем количество архивных кошельков пользователя
const archivedWallets = await db.getAsync(
`SELECT COUNT(*) AS total
FROM crypto_wallets
WHERE user_id = ? AND wallet_type LIKE '%#_%' ESCAPE '#'`, // Считаем только архивные кошельки
[user.id]
);
console.log('[SERVICE] Fetching archived wallets for user:', user.id, 'with telegramId:', user.telegram_id, ' and tolal arhived wallet: ', archivedWallets.total);
// Возвращаем количество архивных кошельков
return archivedWallets.total;
} catch (error) {
console.error('Error fetching archived wallets count:', error);
throw new Error('Failed to fetch archived wallets count');
}
}
}
export default WalletService;

View File

@ -1,6 +1,6 @@
import axios from 'axios';
export default class WalletService {
export default class WalletUtils{
constructor(btcAddress, ltcAddress, trxAddress, ethAddress, userId, minTimestamp) {
this.btcAddress = btcAddress;
this.ltcAddress = ltcAddress;
@ -148,7 +148,7 @@ export default class WalletService {
this.getUsdcErc20Balance(),
this.getUsdtTrc20Balance(),
this.getUsddTrc20Balance(),
WalletService.getCryptoPrices()
WalletUtils.getCryptoPrices()
]);
return {