From 38d0bab26d36cba1e6ee1276cb4f6e8a7b845586 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 27 Aug 2026 12:42:53 +0200 Subject: [PATCH] After trying to recuparate money from cold wallet1 --- backend/src/scripts/recoverHdUsdtToHot.ts | 233 ++++++++++++++++------ docs/DEPLOY-VPS.md | 14 +- 2 files changed, 179 insertions(+), 68 deletions(-) diff --git a/backend/src/scripts/recoverHdUsdtToHot.ts b/backend/src/scripts/recoverHdUsdtToHot.ts index aa35c304..4ac799fd 100644 --- a/backend/src/scripts/recoverHdUsdtToHot.ts +++ b/backend/src/scripts/recoverHdUsdtToHot.ts @@ -1,22 +1,30 @@ /** - * Recover USDT from a platform HD deposit address to the active hot wallet. + * 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" - * (you cannot sign from MetaMask — the key is derived from PLATFORM_MNEMONIC). + * Use when a user Receive address was mistakenly saved as Treasury "cold". * - * VPS: + * 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 balance) - * --to=0x... override destination (default: active hot for that rail) + * --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'; @@ -27,6 +35,8 @@ 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(); @@ -51,19 +61,76 @@ function getMnemonic(): string { 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 { 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= --confirm=YES [--amount=6] [--to=0x...]`); + node dist/scripts/recoverHdUsdtToHot.js --from= --confirm=YES [--amount=6] [--to=0x...] + node dist/scripts/recoverHdUsdtToHot.js --from= --native-only=YES --confirm=YES`); process.exit(1); } if (confirm !== 'YES') { - console.error('Refusing to run without --confirm=YES (moves real on-chain USDT).'); + console.error('Refusing to run without --confirm=YES (moves real on-chain funds).'); process.exit(2); } @@ -94,12 +161,14 @@ async function main(): Promise { 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 (walletType.network === 'BSC' || walletType.code === USDT_BEP20_CODE) { + if (isBsc) { const derived = deriveEvmFromMnemonic(mnemonic, userWallet.derivation_index); privateKey = derived.privateKey; derivedAddress = derived.address; - } else if (walletType.network === 'TRON' || walletType.code === USDT_TRC20_CODE) { + } else if (isTron) { const derived = deriveTronFromMnemonic(mnemonic, userWallet.derivation_index); privateKey = derived.privateKey; derivedAddress = derived.address; @@ -124,82 +193,114 @@ async function main(): Promise { process.exit(7); } - let balance: bigint; - let amount: bigint; + let usdtBalance: string | null = null; + let usdtSent: string | null = null; let gasTopUpTx: string | null = null; - let transferTx: string; + let transferTx: string | null = null; + let nativeResult: Record | null = null; - if (walletType.network === 'BSC' || walletType.code === USDT_BEP20_CODE) { - const contract = bscService.resolveUsdtContract(walletType.contract_address); - balance = await bscService.getUsdtBalanceRaw(userWallet.address, contract); - amount = amountHuman ? humanToRaw(amountHuman, walletType.decimals) : balance; - if (amount <= 0n) { - console.error('Nothing to send (balance 0 or --amount 0)'); - process.exit(8); - } - if (amount > balance) { - console.error(`Requested ${amount} > on-chain balance ${balance}`); - process.exit(8); - } + 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() })); - } + 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); - } 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); - } - balance = await tronService.getTrc20BalanceRaw(userWallet.address, contract); - amount = amountHuman ? humanToRaw(amountHuman, walletType.decimals) : balance; - if (amount <= 0n) { - console.error('Nothing to send (balance 0 or --amount 0)'); - process.exit(8); - } - if (amount > balance) { - console.error(`Requested ${amount} > on-chain balance ${balance}`); - process.exit(8); - } + 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() })); - } + 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); + 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, - balanceBefore: balance.toString(), - amountSent: amount.toString(), - amountHuman: amountHuman ?? '(full balance)', + usdtBalanceBefore: usdtBalance, + usdtSent, gasTopUpTx, transferTx, + native: nativeResult, nextSteps: [ - 'Update Treasury cold address to a real MetaMask / hardware wallet you control', - 'Cancel or ignore any pending Cold→Hot funding that targeted the fake cold', - 'Future sweeps will go to the new cold; Cold→Hot must be signed from MetaMask', + '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, diff --git a/docs/DEPLOY-VPS.md b/docs/DEPLOY-VPS.md index 152e2264..099f47f7 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -497,9 +497,19 @@ sudo docker compose run --rm --no-deps --build backend \ ``` Optionnel : `--amount=6` (USDT humain ; défaut = solde on-chain entier). -Le script dérive la clé HD, top-up BNB depuis le hot si besoin, envoie l’USDT vers le hot actif, puis affiche le `transferTx`. -Ensuite : **Save cold** avec une vraie adresse MetaMask, puis reprendre le parcours Cold → Hot normal. +Le script dérive la clé HD, top-up BNB depuis le hot si besoin, envoie l’USDT vers le hot actif, puis affiche le `transferTx`. +Si du **BNB** (gas de top-up) reste sur l’ancienne HD après le transfert USDT : + +```bash +sudo docker compose run --rm --no-deps --build backend \ + node dist/scripts/recoverHdUsdtToHot.js \ + --from=0xADRESSE_HD_FAUSSE_COLD \ + --native-only=YES \ + --confirm=YES +``` + +Ensuite : **Save cold** avec une vraie adresse MetaMask, puis reprendre le parcours Cold → Hot normal. #### C. Cycle complet 1. Dépôt user BEP20 → crédit ledger.