games_app/backend/src/scripts/recoverHdUsdtToHot.ts

316 lines
11 KiB
TypeScript

/**
* Recover USDT and/or native gas from a platform HD deposit address to the hot wallet.
*
* Use when a user Receive address was mistakenly saved as Treasury "cold".
*
* USDT (default if neither --native-only nor empty USDT balance with --sweep-native):
* sudo docker compose run --rm --no-deps --build backend \
* node dist/scripts/recoverHdUsdtToHot.js \
* --from=0xe682... \
* --confirm=YES
*
* Leftover BNB/TRX only (after USDT already recovered):
* sudo docker compose run --rm --no-deps --build backend \
* node dist/scripts/recoverHdUsdtToHot.js \
* --from=0xe682... \
* --native-only=YES \
* --confirm=YES
*
* Optional:
* --amount=6 human USDT (default: full on-chain USDT balance)
* --to=0x... override destination (default: active hot)
* --sweep-native=YES also send leftover native gas after USDT transfer
*/
import './loadEnv';
import * as bip39 from 'bip39';
import { ethers } from 'ethers';
import { config } from '../config';
import { deriveEvmFromMnemonic, deriveTronFromMnemonic, decryptPrivateKey } from '../services/hdWallet';
import * as walletRepository from '../repositories/walletRepository';
import * as hotWalletRepository from '../repositories/hotWalletRepository';
import * as bscService from '../services/blockchain/bscService';
import * as tronService from '../services/blockchain/tronService';
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from '../services/walletCapabilities';
const MIN_BNB_WEI = 50_000_000_000_000n; // 0.00005 BNB
const MIN_TRX_SUN = 3_000_000n;
/** Leave a small buffer so the native transfer itself can pay gas. */
const BSC_NATIVE_TRANSFER_GAS = 21_000n;
function arg(name: string): string | undefined {
return process.argv.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3).trim();
}
function humanToRaw(human: string, decimals: number): bigint {
const cleaned = human.replace(/,/g, '').trim();
if (!cleaned || !/^\d+(\.\d+)?$/.test(cleaned)) {
throw new Error(`Invalid --amount=${human}`);
}
const [whole, frac = ''] = cleaned.split('.');
if (frac.length > decimals) throw new Error(`Too many decimals for ${decimals}-dec asset`);
const fracPadded = frac.padEnd(decimals, '0');
return BigInt(whole || '0') * 10n ** BigInt(decimals) + BigInt(fracPadded || '0');
}
function getMnemonic(): string {
const raw = (process.env.PLATFORM_MNEMONIC || '').trim();
if (!raw || !bip39.validateMnemonic(raw)) {
throw new Error('PLATFORM_MNEMONIC is missing or invalid in this environment');
}
return raw;
}
async function sweepBnbToHot(privateKey: string, fromAddress: string, toAddress: string): Promise<{
nativeTx: string | null;
nativeSentWei: string;
nativeLeftWei: string;
}> {
const balance = await bscService.getNativeBalanceWei(fromAddress);
const req = new ethers.FetchRequest(config.blockchain.bsc.rpcUrl);
req.timeout = 60_000;
const provider = new ethers.JsonRpcProvider(req, 56);
const feeData = await provider.getFeeData();
const gasPrice = feeData.gasPrice ?? 100_000_000n; // 0.1 gwei fallback (BSC is cheap)
const fee = gasPrice * BSC_NATIVE_TRANSFER_GAS;
if (balance <= fee) {
return {
nativeTx: null,
nativeSentWei: '0',
nativeLeftWei: balance.toString(),
};
}
const sendAmount = balance - fee;
const nativeTx = await bscService.sendBnb(privateKey, toAddress, sendAmount);
const left = await bscService.getNativeBalanceWei(fromAddress);
return {
nativeTx,
nativeSentWei: sendAmount.toString(),
nativeLeftWei: left.toString(),
};
}
async function sweepTrxToHot(privateKey: string, fromAddress: string, toAddress: string): Promise<{
nativeTx: string | null;
nativeSentSun: string;
nativeLeftSun: string;
}> {
const balance = await tronService.getTrxBalanceSun(fromAddress);
/** Keep ~1 TRX for bandwidth/energy buffer; send the rest. */
const keep = 1_000_000n;
if (balance <= keep) {
return {
nativeTx: null,
nativeSentSun: '0',
nativeLeftSun: balance.toString(),
};
}
const sendAmount = balance - keep;
const nativeTx = await tronService.sendTrx(privateKey, toAddress, sendAmount);
const left = await tronService.getTrxBalanceSun(fromAddress);
return {
nativeTx,
nativeSentSun: sendAmount.toString(),
nativeLeftSun: left.toString(),
};
}
async function main(): Promise<void> {
const fromArg = arg('from');
const confirm = arg('confirm');
const amountHuman = arg('amount');
const toOverride = arg('to');
const nativeOnly = arg('native-only') === 'YES';
const sweepNative = arg('sweep-native') === 'YES' || nativeOnly;
if (!fromArg) {
console.error(`Usage:
node dist/scripts/recoverHdUsdtToHot.js --from=<HD_address> --confirm=YES [--amount=6] [--to=0x...]
node dist/scripts/recoverHdUsdtToHot.js --from=<HD_address> --native-only=YES --confirm=YES`);
process.exit(1);
}
if (confirm !== 'YES') {
console.error('Refusing to run without --confirm=YES (moves real on-chain funds).');
process.exit(2);
}
const userWallet = await walletRepository.findUserWalletByAddress(fromArg);
if (!userWallet) {
console.error(`Address not found in user_wallets: ${fromArg}`);
process.exit(3);
}
const walletType = await walletRepository.getWalletTypeById(userWallet.wallet_type_id);
if (!walletType) {
console.error(`Unknown wallet_type_id=${userWallet.wallet_type_id}`);
process.exit(3);
}
const hot = await hotWalletRepository.getActiveHotWallet(walletType.id);
if (!hot) {
console.error(`No active hot wallet for ${walletType.code}`);
process.exit(4);
}
const toAddress = (toOverride || hot.address).trim();
if (toAddress.toLowerCase() === userWallet.address.toLowerCase()) {
console.error('Destination cannot be the same as --from');
process.exit(5);
}
const mnemonic = getMnemonic();
let privateKey: string;
let derivedAddress: string;
const isBsc = walletType.network === 'BSC' || walletType.code === USDT_BEP20_CODE;
const isTron = walletType.network === 'TRON' || walletType.code === USDT_TRC20_CODE;
if (isBsc) {
const derived = deriveEvmFromMnemonic(mnemonic, userWallet.derivation_index);
privateKey = derived.privateKey;
derivedAddress = derived.address;
} else if (isTron) {
const derived = deriveTronFromMnemonic(mnemonic, userWallet.derivation_index);
privateKey = derived.privateKey;
derivedAddress = derived.address;
} else {
console.error(`Unsupported network/code: ${walletType.network} / ${walletType.code}`);
process.exit(6);
}
if (derivedAddress.toLowerCase() !== userWallet.address.toLowerCase()) {
console.error(
JSON.stringify(
{
error: 'HD derivation mismatch — refuse to send',
dbAddress: userWallet.address,
derivedAddress,
derivationIndex: userWallet.derivation_index,
},
null,
2
)
);
process.exit(7);
}
let usdtBalance: string | null = null;
let usdtSent: string | null = null;
let gasTopUpTx: string | null = null;
let transferTx: string | null = null;
let nativeResult: Record<string, string | null> | null = null;
if (!nativeOnly) {
if (isBsc) {
const contract = bscService.resolveUsdtContract(walletType.contract_address);
const balance = await bscService.getUsdtBalanceRaw(userWallet.address, contract);
const amount = amountHuman ? humanToRaw(amountHuman, walletType.decimals) : balance;
usdtBalance = balance.toString();
if (amount <= 0n) {
console.error('No USDT to send. Use --native-only=YES to recover leftover BNB.');
process.exit(8);
}
if (amount > balance) {
console.error(`Requested ${amount} > on-chain balance ${balance}`);
process.exit(8);
}
const bnb = await bscService.getNativeBalanceWei(userWallet.address);
if (bnb < MIN_BNB_WEI) {
const hotKey = decryptPrivateKey(hot.encrypted_private_key);
const topUp = BigInt(config.blockchain.bsc.gasTopUpWei);
gasTopUpTx = await bscService.sendBnb(hotKey, userWallet.address, topUp);
console.log(JSON.stringify({ gasTopUpTx, topUpWei: topUp.toString() }));
}
transferTx = await bscService.sendUsdt(privateKey, contract, toAddress, amount);
usdtSent = amount.toString();
} else {
const contract =
walletType.code === USDT_TRC20_CODE && config.blockchain.tron.usdtTrc20Contract
? config.blockchain.tron.usdtTrc20Contract
: walletType.contract_address;
if (!contract) {
console.error('No TRC20 contract configured');
process.exit(6);
}
const balance = await tronService.getTrc20BalanceRaw(userWallet.address, contract);
const amount = amountHuman ? humanToRaw(amountHuman, walletType.decimals) : balance;
usdtBalance = balance.toString();
if (amount <= 0n) {
console.error('No USDT to send. Use --native-only=YES to recover leftover TRX.');
process.exit(8);
}
if (amount > balance) {
console.error(`Requested ${amount} > on-chain balance ${balance}`);
process.exit(8);
}
const trx = await tronService.getTrxBalanceSun(userWallet.address);
if (trx < MIN_TRX_SUN) {
const hotKey = decryptPrivateKey(hot.encrypted_private_key);
const topUp = BigInt(config.treasury.tronGasTopUpSun);
gasTopUpTx = await tronService.sendTrx(hotKey, userWallet.address, topUp);
console.log(JSON.stringify({ gasTopUpTx, topUpSun: topUp.toString() }));
}
transferTx = await tronService.sendTrc20(privateKey, contract, toAddress, amount);
usdtSent = amount.toString();
}
}
if (sweepNative) {
if (isBsc) {
const r = await sweepBnbToHot(privateKey, userWallet.address, toAddress);
nativeResult = {
nativeTx: r.nativeTx,
nativeSentWei: r.nativeSentWei,
nativeLeftWei: r.nativeLeftWei,
};
if (!r.nativeTx) {
console.error('BNB balance too low to cover transfer fee — nothing sent.');
}
} else {
const r = await sweepTrxToHot(privateKey, userWallet.address, toAddress);
nativeResult = {
nativeTx: r.nativeTx,
nativeSentSun: r.nativeSentSun,
nativeLeftSun: r.nativeLeftSun,
};
if (!r.nativeTx) {
console.error('TRX balance too low after keep buffer — nothing sent.');
}
}
}
console.log(
JSON.stringify(
{
ok: true,
mode: nativeOnly ? 'native-only' : sweepNative ? 'usdt+native' : 'usdt',
walletType: walletType.code,
from: userWallet.address,
to: toAddress,
userId: userWallet.user_id,
derivationIndex: userWallet.derivation_index,
usdtBalanceBefore: usdtBalance,
usdtSent,
gasTopUpTx,
transferTx,
native: nativeResult,
nextSteps: [
'Confirm hot BNB ≥ ~0.001 for withdrawals (Treasury chip)',
'Save cold to a real MetaMask / hardware address',
'Cancel or ignore pending Cold→Hot funding for the fake cold',
],
},
null,
2
)
);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});