games_app/backend/dist-test-faq/services/walletService.js

164 lines
7.5 KiB
JavaScript

"use strict";
/**
* User wallet and deposit address service.
* Derives TRON (TRC20) and BSC (BEP20) deposit addresses for USDT.
* Spendable ledger is always USDT_TRC20 (6 decimals). Inventory is deposit-sourced
* ops telemetry per network; withdrawals are capped by ledger + hot float, not inventory.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOrCreateDepositAddress = getOrCreateDepositAddress;
exports.getWalletTypes = getWalletTypes;
exports.getUserBalances = getUserBalances;
exports.listUserTransactions = listUserTransactions;
exports.listUserTransactionsPaginated = listUserTransactionsPaginated;
const bip39 = __importStar(require("bip39"));
const hdWallet_1 = require("./hdWallet");
const connection_1 = require("../db/connection");
const walletRepository = __importStar(require("../repositories/walletRepository"));
const transactionRepository = __importStar(require("../repositories/transactionRepository"));
const networkInventoryRepository = __importStar(require("../repositories/networkInventoryRepository"));
const walletCapabilities_1 = require("./walletCapabilities");
const PLATFORM_MNEMONIC = process.env.PLATFORM_MNEMONIC || '';
function getMnemonic() {
const raw = PLATFORM_MNEMONIC.trim();
if (!raw || raw.split(/\s+/).length < 12) {
throw new Error('PLATFORM_MNEMONIC is not set or too short. Set a valid BIP39 mnemonic (12 or 24 words) in .env.');
}
if (!bip39.validateMnemonic(raw)) {
throw new Error('PLATFORM_MNEMONIC is not a valid BIP39 mnemonic.');
}
return raw;
}
/**
* Gets or creates a USDT deposit address for a user (TRC20 or BEP20 custody rail).
*/
async function getOrCreateDepositAddress(userId, walletTypeCode) {
(0, walletCapabilities_1.assertUsdtWalletType)(walletTypeCode);
const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode);
if (!walletType)
throw new Error(`Wallet type ${walletTypeCode} is not configured`);
const caps = await (0, walletCapabilities_1.enrichWalletTypeAsync)(walletType);
if (!caps.depositEnabled) {
throw new Error(`Deposits are disabled for ${walletTypeCode}`);
}
const existing = await walletRepository.getUserWallet(userId, walletType.id);
if (existing) {
return { address: existing.address, walletType: caps };
}
const maxIndex = await getNextDerivationIndex(walletType.id);
const mnemonic = getMnemonic();
const derived = walletTypeCode === walletCapabilities_1.USDT_BEP20_CODE
? (0, hdWallet_1.deriveEvmFromMnemonic)(mnemonic, maxIndex)
: (0, hdWallet_1.deriveTronFromMnemonic)(mnemonic, maxIndex);
await walletRepository.createUserWallet({
userId,
walletTypeId: walletType.id,
address: derived.address,
derivationIndex: maxIndex,
});
return { address: derived.address, walletType: caps };
}
async function getNextDerivationIndex(walletTypeId) {
const rows = await (0, connection_1.query)('SELECT MAX(derivation_index) as max FROM user_wallets WHERE wallet_type_id = $1', [walletTypeId]);
const max = rows[0]?.max ?? -1;
return max + 1;
}
async function getWalletTypes() {
const types = await walletRepository.getWalletTypes();
const { getSettings } = await Promise.resolve().then(() => __importStar(require('../repositories/settingsRepository')));
const settings = await getSettings();
return types.map((wt) => (0, walletCapabilities_1.enrichWalletType)(wt, settings));
}
async function getUserBalances(userId) {
const { getOrCreateAccount, getAccount } = await Promise.resolve().then(() => __importStar(require('../repositories/ledgerRepository')));
const { getSettings } = await Promise.resolve().then(() => __importStar(require('../repositories/settingsRepository')));
const settings = await getSettings();
const ledgerType = await walletRepository.getWalletTypeByCode(walletCapabilities_1.USDT_TRC20_CODE);
if (!ledgerType)
throw new Error('USDT_TRC20 wallet type not configured');
const account = await getOrCreateAccount(userId, ledgerType.id, 'main');
const bonus = await getAccount(userId, ledgerType.id, 'bonus');
const test = await getAccount(userId, ledgerType.id, 'test');
const available = BigInt(account.available_balance);
const inv = await networkInventoryRepository.getAllForUser(userId);
const spendable = {
walletType: (0, walletCapabilities_1.enrichWalletType)(ledgerType, settings),
available: account.available_balance,
locked: account.locked_balance,
bonusAvailable: bonus?.available_balance ?? '0',
testAvailable: test?.available_balance ?? '0',
};
const types = await walletRepository.getWalletTypes();
const networks = [];
for (const wt of types) {
if (wt.code !== walletCapabilities_1.USDT_TRC20_CODE && wt.code !== walletCapabilities_1.USDT_BEP20_CODE)
continue;
const caps = (0, walletCapabilities_1.enrichWalletType)(wt, settings);
const networkInv = wt.network === 'BSC' ? inv.BSC : inv.TRON;
const withdrawable = caps.withdrawEnabled ? available : 0n;
networks.push({
code: wt.code,
network: wt.network,
depositEnabled: caps.depositEnabled,
withdrawEnabled: caps.withdrawEnabled,
inventory: networkInv.toString(),
withdrawable: withdrawable.toString(),
});
}
return {
spendable,
inventory: { TRON: inv.TRON.toString(), BSC: inv.BSC.toString() },
networks,
balances: [spendable],
};
}
async function listUserTransactions(userId, limit, offset, category) {
const items = await transactionRepository.listByUserId(userId, limit, offset, category);
return transactionRepository.enrichGameStakeBetStatus(items);
}
async function listUserTransactionsPaginated(userId, limit, offset, category) {
const [items, total] = await Promise.all([
transactionRepository.listByUserId(userId, limit, offset, category),
transactionRepository.countByUserId(userId, category),
]);
return {
items: await transactionRepository.enrichGameStakeBetStatus(items),
total,
limit,
offset,
};
}
//# sourceMappingURL=walletService.js.map