games_app/backend/src/services/walletService.ts
2026-08-25 17:59:10 +02:00

203 lines
6.8 KiB
TypeScript

/**
* 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.
*/
import * as bip39 from 'bip39';
import { deriveEvmFromMnemonic, deriveTronFromMnemonic } from './hdWallet';
import { query } from '../db/connection';
import * as walletRepository from '../repositories/walletRepository';
import * as transactionRepository from '../repositories/transactionRepository';
import * as networkInventoryRepository from '../repositories/networkInventoryRepository';
import { Transaction } from '../models';
import {
assertUsdtWalletType,
enrichWalletType,
enrichWalletTypeAsync,
USDT_BEP20_CODE,
USDT_TRC20_CODE,
type WalletTypeCapabilities,
} from './walletCapabilities';
const PLATFORM_MNEMONIC = process.env.PLATFORM_MNEMONIC || '';
function getMnemonic(): string {
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).
*/
export async function getOrCreateDepositAddress(
userId: string,
walletTypeCode: string
): Promise<{ address: string; walletType: WalletTypeCapabilities }> {
assertUsdtWalletType(walletTypeCode);
const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode);
if (!walletType) throw new Error(`Wallet type ${walletTypeCode} is not configured`);
const caps = await 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 === USDT_BEP20_CODE
? deriveEvmFromMnemonic(mnemonic, maxIndex)
: 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: number): Promise<number> {
const rows = await query<{ max: number | null }[]>(
'SELECT MAX(derivation_index) as max FROM user_wallets WHERE wallet_type_id = $1',
[walletTypeId]
);
const max = rows[0]?.max ?? -1;
return max + 1;
}
export async function getWalletTypes(): Promise<WalletTypeCapabilities[]> {
const types = await walletRepository.getWalletTypes();
const { getSettings } = await import('../repositories/settingsRepository');
const settings = await getSettings();
return types.map((wt) => enrichWalletType(wt, settings));
}
export type NetworkBalanceInfo = {
code: string;
network: string;
depositEnabled: boolean;
withdrawEnabled: boolean;
/** Cumulative deposits credited on this network (ops / reporting; not a withdrawal cap). */
inventory: string;
/** Max withdrawable on this rail when enabled = full spendable available (ledger units). */
withdrawable: string;
};
export type UserBalancesResponse = {
/** Unified spendable USDT ledger (USDT_TRC20, 6 decimals). */
spendable: {
walletType: WalletTypeCapabilities;
available: string;
locked: string;
bonusAvailable: string;
testAvailable: string;
};
inventory: { TRON: string; BSC: string };
networks: NetworkBalanceInfo[];
/**
* @deprecated Prefer `spendable` + `networks`. Kept for older clients:
* single spendable row only (no separate BEP20 ledger balance).
*/
balances: Array<{
walletType: WalletTypeCapabilities;
available: string;
locked: string;
bonusAvailable: string;
testAvailable: string;
}>;
};
export async function getUserBalances(userId: string): Promise<UserBalancesResponse> {
const { getOrCreateAccount, getAccount } = await import('../repositories/ledgerRepository');
const { getSettings } = await import('../repositories/settingsRepository');
const settings = await getSettings();
const ledgerType = await walletRepository.getWalletTypeByCode(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: 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: NetworkBalanceInfo[] = [];
for (const wt of types) {
if (wt.code !== USDT_TRC20_CODE && wt.code !== USDT_BEP20_CODE) continue;
const caps = 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],
};
}
export async function listUserTransactions(
userId: string,
limit: number,
offset: number,
category?: transactionRepository.TransactionActivityCategory
): Promise<Transaction[]> {
const items = await transactionRepository.listByUserId(userId, limit, offset, category);
return transactionRepository.enrichGameStakeBetStatus(items);
}
export async function listUserTransactionsPaginated(
userId: string,
limit: number,
offset: number,
category?: transactionRepository.TransactionActivityCategory
): Promise<{ items: Transaction[]; total: number; limit: number; offset: number }> {
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,
};
}