After deposing the correct money from binance but failed
This commit is contained in:
parent
d8f94f8650
commit
7b3abf59a3
@ -105,6 +105,19 @@ export const config = {
|
||||
usdtBep20Contract: process.env.USDT_BEP20_CONTRACT || null,
|
||||
confirmations: parseInt(process.env.BSC_CONFIRMATIONS || '15', 10),
|
||||
getLogsBlockRange: parseInt(process.env.BSC_GETLOGS_BLOCK_RANGE || '2000', 10),
|
||||
/**
|
||||
* First-scan / balance catch-up lookback (~3s/block → 200k ≈ 7 days).
|
||||
* Missed deposits older than this need manual creditByTx.
|
||||
*/
|
||||
depositInitialLookbackBlocks: parseInt(
|
||||
process.env.BSC_DEPOSIT_INITIAL_LOOKBACK_BLOCKS || '200000',
|
||||
10
|
||||
),
|
||||
/** Re-scan overlap each poll to survive empty eth_getLogs / late indexing. */
|
||||
depositOverlapLookbackBlocks: parseInt(
|
||||
process.env.BSC_DEPOSIT_OVERLAP_LOOKBACK_BLOCKS || '5000',
|
||||
10
|
||||
),
|
||||
/** Native BNB top-up for sweeps (wei); default 0.001 BNB */
|
||||
gasTopUpWei: process.env.SWEEP_BSC_GAS_TOPUP_WEI || '1000000000000000',
|
||||
},
|
||||
|
||||
27
backend/src/scripts/creditBscDepositByTx.ts
Normal file
27
backend/src/scripts/creditBscDepositByTx.ts
Normal file
@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Credit a missed BSC USDT (BEP20) deposit by transaction hash.
|
||||
*
|
||||
* VPS (one line — no space after backslash):
|
||||
* sudo docker compose run --rm --no-deps --build backend \
|
||||
* node dist/scripts/creditBscDepositByTx.js --tx=0x...
|
||||
*/
|
||||
|
||||
import './loadEnv';
|
||||
import { creditBscDepositByTxHash } from '../services/depositMonitorService';
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const txArg = process.argv.find((a) => a.startsWith('--tx='))?.slice('--tx='.length).trim();
|
||||
if (!txArg || !/^0x[0-9a-fA-F]{64}$/.test(txArg)) {
|
||||
console.error('Usage: node dist/scripts/creditBscDepositByTx.js --tx=0x<64 hex chars>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const result = await creditBscDepositByTxHash(txArg);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
if (!result.credited) process.exit(2);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -46,6 +46,47 @@ export async function getCurrentBlock(): Promise<number> {
|
||||
return getProvider().getBlockNumber();
|
||||
}
|
||||
|
||||
const TRANSFER_TOPIC = ethers.id('Transfer(address,address,uint256)');
|
||||
|
||||
export type ParsedErc20Transfer = {
|
||||
contract: string;
|
||||
from: string;
|
||||
to: string;
|
||||
value: bigint;
|
||||
};
|
||||
|
||||
export type TxReceiptSummary = {
|
||||
status: number;
|
||||
blockNumber: number;
|
||||
transfers: ParsedErc20Transfer[];
|
||||
};
|
||||
|
||||
/** Fetches a tx receipt and parses ERC-20 Transfer logs (for deposit recovery). */
|
||||
export async function getTransactionReceipt(txHash: string): Promise<TxReceiptSummary | null> {
|
||||
const p = getProvider();
|
||||
const receipt = await p.getTransactionReceipt(txHash);
|
||||
if (!receipt) return null;
|
||||
const transfers: ParsedErc20Transfer[] = [];
|
||||
for (const log of receipt.logs) {
|
||||
if (log.topics[0] !== TRANSFER_TOPIC || log.topics.length < 3) continue;
|
||||
try {
|
||||
transfers.push({
|
||||
contract: ethers.getAddress(log.address),
|
||||
from: ethers.getAddress(ethers.dataSlice(log.topics[1], 12)),
|
||||
to: ethers.getAddress(ethers.dataSlice(log.topics[2], 12)),
|
||||
value: BigInt(log.data),
|
||||
});
|
||||
} catch {
|
||||
// ignore malformed topics
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: receipt.status === null ? 0 : Number(receipt.status),
|
||||
blockNumber: receipt.blockNumber,
|
||||
transfers,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getUsdtTransfersToAddress(
|
||||
toAddress: string,
|
||||
contractAddress: string,
|
||||
|
||||
@ -25,6 +25,10 @@ import {
|
||||
scaleChainToLedger,
|
||||
type CustodyNetwork,
|
||||
} from '../utils/usdtUnits';
|
||||
import {
|
||||
computeBscCommittedScannerBlock,
|
||||
computeBscScanFromBlock,
|
||||
} from '../utils/bscDepositScan';
|
||||
|
||||
const TRON_CONFIRMATIONS = config.blockchain.tron.confirmations;
|
||||
const BSC_CONFIRMATIONS = config.blockchain.bsc.confirmations;
|
||||
@ -128,38 +132,68 @@ export async function processTronDeposits(): Promise<void> {
|
||||
/** Scans BSC for new USDT BEP20 deposits; credits unified ledger (6 dec) + BSC inventory. */
|
||||
export async function processBscDeposits(): Promise<void> {
|
||||
const settings = await settingsRepository.getSettings();
|
||||
if (!settings.network_usdt_bep20_deposit_enabled) return;
|
||||
if (!settings.network_usdt_bep20_deposit_enabled) {
|
||||
console.warn('[deposit] USDT_BEP20: deposit flag disabled — skipping scan');
|
||||
return;
|
||||
}
|
||||
|
||||
const custodyType = await walletRepository.getWalletTypeByCode(USDT_BEP20_CODE);
|
||||
const ledgerType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
|
||||
if (!custodyType || !ledgerType) return;
|
||||
if (!custodyType || !ledgerType) {
|
||||
console.warn('[deposit] USDT_BEP20: wallet type(s) missing — skipping scan');
|
||||
return;
|
||||
}
|
||||
|
||||
const currentBlock = await bscService.getCurrentBlock();
|
||||
const state = await depositScannerRepository.getState(custodyType.id);
|
||||
let fromBlock = state ? Number(state.last_block) + 1 : 0;
|
||||
if (fromBlock > currentBlock) fromBlock = 0;
|
||||
const lastBlock = state ? Number(state.last_block) : null;
|
||||
|
||||
const userWallets = await query<Array<{ address: string; user_id: string; created_at: Date }>>(
|
||||
'SELECT address, user_id, created_at FROM user_wallets WHERE wallet_type_id = $1',
|
||||
[custodyType.id]
|
||||
);
|
||||
|
||||
// Never advance the cursor with zero wallets — that permanently skips history
|
||||
// once the first deposit address is created after a tip checkpoint.
|
||||
if (userWallets.length === 0) {
|
||||
await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock));
|
||||
console.warn('[deposit] USDT_BEP20: no deposit wallets yet — scanner idle');
|
||||
return;
|
||||
}
|
||||
|
||||
if (fromBlock === 0) {
|
||||
fromBlock = Math.max(0, currentBlock - 5_000);
|
||||
}
|
||||
const initialLookback = config.blockchain.bsc.depositInitialLookbackBlocks;
|
||||
const overlapLookback = config.blockchain.bsc.depositOverlapLookbackBlocks;
|
||||
let fromBlock = computeBscScanFromBlock({
|
||||
lastBlock,
|
||||
currentBlock,
|
||||
initialLookback,
|
||||
overlapLookback,
|
||||
});
|
||||
|
||||
const contract = bscService.resolveUsdtContract(custodyType.contract_address);
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log(
|
||||
`[deposit] USDT_BEP20 (id=${custodyType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`
|
||||
);
|
||||
|
||||
// Catch-up: any address still holding USDT likely missed a credit — deepen lookback.
|
||||
for (const { address } of userWallets) {
|
||||
try {
|
||||
const bal = await bscService.getUsdtBalanceRaw(address, contract);
|
||||
if (bal > 0n) {
|
||||
const deepFrom = Math.max(0, currentBlock - initialLookback);
|
||||
if (deepFrom < fromBlock) {
|
||||
console.warn(
|
||||
`[deposit] USDT_BEP20: unpaid on-chain balance on ${address} — deep rescan from ${deepFrom}`
|
||||
);
|
||||
fromBlock = deepFrom;
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`[deposit] USDT_BEP20: balance check failed for ${address}:`, e);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[deposit] USDT_BEP20 (id=${custodyType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}, tip=${currentBlock}`
|
||||
);
|
||||
|
||||
for (const { address, user_id } of userWallets) {
|
||||
const transfers = await bscService.getUsdtTransfersToAddress(
|
||||
address,
|
||||
@ -167,6 +201,9 @@ export async function processBscDeposits(): Promise<void> {
|
||||
fromBlock,
|
||||
currentBlock
|
||||
);
|
||||
if (transfers.length > 0) {
|
||||
console.log(`[deposit] USDT_BEP20 ${address}: ${transfers.length} transfer(s) in window`);
|
||||
}
|
||||
for (const t of transfers) {
|
||||
const confirmations = currentBlock - t.blockNumber + 1;
|
||||
if (confirmations < BSC_CONFIRMATIONS) continue;
|
||||
@ -193,7 +230,86 @@ export async function processBscDeposits(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock));
|
||||
const committed = computeBscCommittedScannerBlock(currentBlock, BSC_CONFIRMATIONS);
|
||||
await depositScannerRepository.updateState(custodyType.id, BigInt(committed));
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually credit a confirmed BSC USDT transfer by tx hash (ops recovery).
|
||||
* Safe to re-run: insertDepositIfNew is idempotent on blockchain_tx_id.
|
||||
*/
|
||||
export async function creditBscDepositByTxHash(txHash: string): Promise<{
|
||||
credited: boolean;
|
||||
userId?: string;
|
||||
ledgerAmount?: string;
|
||||
reason?: string;
|
||||
}> {
|
||||
const settings = await settingsRepository.getSettings();
|
||||
if (!settings.network_usdt_bep20_deposit_enabled) {
|
||||
return { credited: false, reason: 'network_usdt_bep20_deposit_enabled is false' };
|
||||
}
|
||||
|
||||
const custodyType = await walletRepository.getWalletTypeByCode(USDT_BEP20_CODE);
|
||||
const ledgerType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
|
||||
if (!custodyType || !ledgerType) {
|
||||
return { credited: false, reason: 'wallet types missing' };
|
||||
}
|
||||
|
||||
const receipt = await bscService.getTransactionReceipt(txHash);
|
||||
if (!receipt) return { credited: false, reason: 'transaction not found' };
|
||||
if (receipt.status !== 1) return { credited: false, reason: 'transaction failed on-chain' };
|
||||
|
||||
const contract = bscService.resolveUsdtContract(custodyType.contract_address).toLowerCase();
|
||||
const transfer = receipt.transfers.find((t) => t.contract.toLowerCase() === contract);
|
||||
if (!transfer) {
|
||||
return { credited: false, reason: 'no USDT Transfer log for configured BEP20 contract' };
|
||||
}
|
||||
|
||||
const rows = await query<Array<{ address: string; user_id: string }>>(
|
||||
`SELECT address, user_id FROM user_wallets
|
||||
WHERE wallet_type_id = $1 AND lower(address) = lower($2)`,
|
||||
[custodyType.id, transfer.to]
|
||||
);
|
||||
const wallet = rows[0];
|
||||
if (!wallet) {
|
||||
return {
|
||||
credited: false,
|
||||
reason: `no USDT_BEP20 user_wallet for to=${transfer.to}`,
|
||||
};
|
||||
}
|
||||
|
||||
const currentBlock = await bscService.getCurrentBlock();
|
||||
const confirmations = currentBlock - receipt.blockNumber + 1;
|
||||
if (confirmations < BSC_CONFIRMATIONS) {
|
||||
return {
|
||||
credited: false,
|
||||
reason: `need ${BSC_CONFIRMATIONS} confirmations, have ${confirmations}`,
|
||||
};
|
||||
}
|
||||
|
||||
const ledgerAmount = scaleChainToLedger(transfer.value, BEP20_USDT_DECIMALS, LEDGER_USDT_DECIMALS);
|
||||
if (ledgerAmount <= 0n) return { credited: false, reason: 'amount too small after scale' };
|
||||
|
||||
await creditDeposit({
|
||||
userId: wallet.user_id,
|
||||
ledgerWalletTypeId: ledgerType.id,
|
||||
custodyWalletTypeId: custodyType.id,
|
||||
network: 'BSC',
|
||||
sourceWalletCode: USDT_BEP20_CODE,
|
||||
ledgerAmount,
|
||||
chainAmount: transfer.value,
|
||||
blockchainTxId: txHash,
|
||||
fromAddress: transfer.from,
|
||||
toAddress: wallet.address,
|
||||
confirmations,
|
||||
requiredConfirmations: BSC_CONFIRMATIONS,
|
||||
});
|
||||
|
||||
return {
|
||||
credited: true,
|
||||
userId: wallet.user_id,
|
||||
ledgerAmount: ledgerAmount.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
async function creditDeposit(opts: {
|
||||
@ -254,7 +370,9 @@ async function creditDeposit(opts: {
|
||||
opts.ledgerAmount
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
console.log(
|
||||
`[deposit] credited ${opts.sourceWalletCode} user=${opts.userId} ledger=${opts.ledgerAmount.toString()} tx=${opts.blockchainTxId}`
|
||||
); } catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
throw e;
|
||||
} finally {
|
||||
|
||||
48
backend/src/tests/bscDepositScan.test.ts
Normal file
48
backend/src/tests/bscDepositScan.test.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
computeBscCommittedScannerBlock,
|
||||
computeBscScanFromBlock,
|
||||
} from '../utils/bscDepositScan';
|
||||
|
||||
describe('computeBscScanFromBlock', () => {
|
||||
test('first scan uses initial lookback', () => {
|
||||
assert.equal(
|
||||
computeBscScanFromBlock({
|
||||
lastBlock: null,
|
||||
currentBlock: 100_000,
|
||||
initialLookback: 200_000,
|
||||
overlapLookback: 5_000,
|
||||
}),
|
||||
0
|
||||
);
|
||||
assert.equal(
|
||||
computeBscScanFromBlock({
|
||||
lastBlock: null,
|
||||
currentBlock: 300_000,
|
||||
initialLookback: 200_000,
|
||||
overlapLookback: 5_000,
|
||||
}),
|
||||
100_000
|
||||
);
|
||||
});
|
||||
|
||||
test('subsequent scans overlap to avoid skipped deposits', () => {
|
||||
assert.equal(
|
||||
computeBscScanFromBlock({
|
||||
lastBlock: 50_000,
|
||||
currentBlock: 60_000,
|
||||
initialLookback: 200_000,
|
||||
overlapLookback: 5_000,
|
||||
}),
|
||||
45_001
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeBscCommittedScannerBlock', () => {
|
||||
test('lags tip by confirmations', () => {
|
||||
assert.equal(computeBscCommittedScannerBlock(1000, 15), 985);
|
||||
assert.equal(computeBscCommittedScannerBlock(10, 15), 0);
|
||||
});
|
||||
});
|
||||
22
backend/src/utils/bscDepositScan.ts
Normal file
22
backend/src/utils/bscDepositScan.ts
Normal file
@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Pure helpers for BSC deposit scanner block windows.
|
||||
*/
|
||||
|
||||
export function computeBscScanFromBlock(opts: {
|
||||
lastBlock: number | null;
|
||||
currentBlock: number;
|
||||
initialLookback: number;
|
||||
overlapLookback: number;
|
||||
}): number {
|
||||
const { lastBlock, currentBlock, initialLookback, overlapLookback } = opts;
|
||||
if (lastBlock == null || lastBlock < 0) {
|
||||
return Math.max(0, currentBlock - Math.max(0, initialLookback));
|
||||
}
|
||||
const next = lastBlock + 1;
|
||||
return Math.max(0, next - Math.max(0, overlapLookback));
|
||||
}
|
||||
|
||||
/** Persist scanner tip behind head by confirmations so late logs can still be seen. */
|
||||
export function computeBscCommittedScannerBlock(currentBlock: number, confirmations: number): number {
|
||||
return Math.max(0, currentBlock - Math.max(0, confirmations));
|
||||
}
|
||||
@ -72,6 +72,8 @@ nano .env # ou vim
|
||||
| `USDT_TRC20_CONTRACT` | Laisser **vide** en mainnet (contrat Tether par défaut en DB) |
|
||||
| `BSC_RPC_URL` | Mainnet : `https://bsc-dataseed.binance.org` (ou RPC fiable) |
|
||||
| `BSC_CONFIRMATIONS` | Ex. `15` |
|
||||
| `BSC_DEPOSIT_INITIAL_LOOKBACK_BLOCKS` | Lookback 1er scan / catch-up balance (défaut `200000` ≈ 7 j) |
|
||||
| `BSC_DEPOSIT_OVERLAP_LOOKBACK_BLOCKS` | Re-scan chevauchant chaque poll (défaut `5000`) |
|
||||
| `USDT_BEP20_CONTRACT` | Laisser **vide** en mainnet (USDT officiel BSC en DB) |
|
||||
| `ALLOW_WITHDRAWALS` | `false` jusqu’à validation des dépôts (le kill-switch admin Settings prime aussi) |
|
||||
| `APP_PUBLIC_URL` | Ex. HTTP test : `http://prediqo.redirectme.net:9080` · HTTPS : `https://…:9443` |
|
||||
@ -407,6 +409,20 @@ Cette section regroupe les commandes lorsque PostgreSQL est **vide** (base cré
|
||||
|
||||
> **Ledger unifié + float hot :** dépôts TRC20 et BEP20 alimentent le même solde jouable (`USDT_TRC20` en DB, 6 décimales). Le réseau de retrait n’a **pas** à correspondre au dépôt ; l’API refuse un retrait si le hot du rail choisi n’a pas assez d’USDT ou de gas (`HOT_WALLET_INSUFFICIENT_LIQUIDITY`). L’inventaire par réseau reste un compteur ops (dépôts), pas un plafond joueur.
|
||||
|
||||
#### Dépôt BEP20 confirmé on-chain mais pas crédité
|
||||
|
||||
1. Vérifier sur BscScan que l’USDT est bien sur l’adresse Receive BEP20 du user (contrat `0x55d39832…7955`).
|
||||
2. Admin → Settings → dépôt **BEP20** activé.
|
||||
3. Après déploiement du fix scanner : le monitor détecte un solde unpaid et re-scanne (~7 j). Sinon crédit manuel :
|
||||
|
||||
```bash
|
||||
sudo docker compose run --rm --no-deps --build backend \
|
||||
node dist/scripts/creditBscDepositByTx.js \
|
||||
--tx=0xVOTRE_TX_HASH
|
||||
```
|
||||
|
||||
4. Logs backend : `[deposit] USDT_BEP20` / `[deposit] credited USDT_BEP20`.
|
||||
|
||||
### Prérequis communs
|
||||
|
||||
| Étape | Détail |
|
||||
|
||||
Loading…
Reference in New Issue
Block a user