After trying to recuparate money from cold wallet

This commit is contained in:
Your Name 2026-08-27 12:21:11 +02:00
parent 4de1fa8188
commit 97f04acf21
3 changed files with 244 additions and 2 deletions

View File

@ -114,3 +114,14 @@ export async function findUserByDepositAddress(address: string): Promise<{ user_
);
return rows[0] || null;
}
/** Full user_wallets row for an on-chain deposit address (case-insensitive). */
export async function findUserWalletByAddress(address: string): Promise<UserWallet | null> {
const rows = await query<UserWallet[]>(
`SELECT id, user_id, wallet_type_id, address, derivation_index
FROM user_wallets WHERE LOWER(address) = LOWER($1)
LIMIT 1`,
[address]
);
return rows[0] || null;
}

View File

@ -0,0 +1,214 @@
/**
* Recover USDT from a platform HD deposit address to the active 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).
*
* VPS:
* sudo docker compose run --rm --no-deps --build backend \
* node dist/scripts/recoverHdUsdtToHot.js \
* --from=0xe682... \
* --confirm=YES
*
* Optional:
* --amount=6 human USDT (default: full on-chain balance)
* --to=0x... override destination (default: active hot for that rail)
*/
import './loadEnv';
import * as bip39 from 'bip39';
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;
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 main(): Promise<void> {
const fromArg = arg('from');
const confirm = arg('confirm');
const amountHuman = arg('amount');
const toOverride = arg('to');
if (!fromArg) {
console.error(`Usage:
node dist/scripts/recoverHdUsdtToHot.js --from=<HD_address> --confirm=YES [--amount=6] [--to=0x...]`);
process.exit(1);
}
if (confirm !== 'YES') {
console.error('Refusing to run without --confirm=YES (moves real on-chain USDT).');
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;
if (walletType.network === 'BSC' || walletType.code === USDT_BEP20_CODE) {
const derived = deriveEvmFromMnemonic(mnemonic, userWallet.derivation_index);
privateKey = derived.privateKey;
derivedAddress = derived.address;
} else if (walletType.network === 'TRON' || walletType.code === USDT_TRC20_CODE) {
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 balance: bigint;
let amount: bigint;
let gasTopUpTx: string | null = null;
let transferTx: string;
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);
}
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);
}
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);
}
console.log(
JSON.stringify(
{
ok: true,
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)',
gasTopUpTx,
transferTx,
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',
],
},
null,
2
)
);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});

View File

@ -478,11 +478,28 @@ sudo docker compose run --rm --no-deps --build backend \
Le transfert on-chain est **manuel** (clé cold hors plateforme) ; Prediqo enregistre la demande + la confirmation.
1. Treasury → **Cold → Hot funding** : wallet type ID **2** (USDT_BEP20 en général), montant en **unités brutes 18 déc.** (ex. `1000000000000000000` = 1 USDT), notes optionnelles → **Request funding** → Approvals.
2. Après approbation : transferrer manuellement USDT BEP20 **cold → hot** (`0x2950…` ou l’adresse hot affichée).
> **Important :** le cold doit être une adresse **externe** (MetaMask / hardware), **pas** une adresse Receive d’un user Prediqo (HD). Sinon vous ne pourrez pas signer le Cold → Hot.
1. Treasury → **Cold → Hot funding** : réseau **USDT (BEP20)**, montant en **USDT** (ex. `2`) → **Request funding** → Approvals.
2. Après approbation : transferrer manuellement USDT BEP20 **cold → hot** (adresse hot affichée / Copier).
3. Treasury → **Confirm tx** avec le hash BscScan.
4. Vérifier le solde USDT hot on-chain (Treasury / explorateur).
##### Récupérer des USDT bloqués sur une « fausse » cold (adresse HD user)
Si une adresse Receive Prediqo a été enregistrée comme cold par erreur :
```bash
sudo docker compose run --rm --no-deps --build backend \
node dist/scripts/recoverHdUsdtToHot.js \
--from=0xADRESSE_HD_FAUSSE_COLD \
--confirm=YES
```
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.
#### C. Cycle complet
1. Dépôt user BEP20 → crédit ledger.