After trying to recuparate money from cold wallet14
This commit is contained in:
parent
c76d69f330
commit
a39d1a89ab
@ -130,3 +130,44 @@ export async function countPositive(): Promise<number> {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when completed deposits to this HD (minus completed sweeps) already cover on-chain USDT.
|
||||
* Used to skip expensive unpaid getLogs when funds only await cold sweep.
|
||||
*/
|
||||
export async function isAddressLedgerCaughtUp(
|
||||
address: string,
|
||||
onChainAmount: bigint,
|
||||
custodyDecimals: number
|
||||
): Promise<boolean> {
|
||||
if (onChainAmount <= 0n) return true;
|
||||
const rows = await query<Array<{ net: string }>>(
|
||||
`SELECT (
|
||||
COALESCE((
|
||||
SELECT SUM(
|
||||
COALESCE(
|
||||
NULLIF(t.metadata->>'chain_amount', '')::numeric,
|
||||
CASE
|
||||
WHEN $2::int = 18 THEN t.amount::numeric * 1000000000000
|
||||
ELSE t.amount::numeric
|
||||
END
|
||||
)
|
||||
)
|
||||
FROM transactions t
|
||||
WHERE t.type = 'deposit'
|
||||
AND t.status = 'completed'
|
||||
AND lower(t.to_address) = lower($1)
|
||||
), 0)
|
||||
-
|
||||
COALESCE((
|
||||
SELECT SUM(ds.amount::numeric)
|
||||
FROM deposit_sweeps ds
|
||||
WHERE ds.status = 'completed'
|
||||
AND lower(ds.from_address) = lower($1)
|
||||
), 0)
|
||||
)::text AS net`,
|
||||
[address, custodyDecimals]
|
||||
);
|
||||
const net = BigInt(rows[0]?.net?.split('.')[0] ?? '0');
|
||||
return net >= onChainAmount;
|
||||
}
|
||||
|
||||
@ -209,7 +209,7 @@ export async function getUsdtTransfersToAddress(
|
||||
const url = urls[i]!;
|
||||
try {
|
||||
const hits = await queryUsdtTransfersOnRpc(url, toAddress, contractAddress, fromBlock, endCap);
|
||||
if (url !== config.blockchain.bsc.rpcUrl.trim()) {
|
||||
if (url !== config.blockchain.bsc.rpcUrl.trim() && hits.length > 0) {
|
||||
console.warn(
|
||||
`[bsc] eth_getLogs ok via ${url} for ${toAddress} hits=${hits.length} blocks=${fromBlock}-${endCap}`
|
||||
);
|
||||
|
||||
@ -185,8 +185,12 @@ export async function processBscDeposits(): Promise<void> {
|
||||
});
|
||||
|
||||
const contract = bscService.resolveUsdtContract(custodyType.contract_address);
|
||||
const custodyDecimals = custodyType.decimals ?? BEP20_USDT_DECIMALS;
|
||||
|
||||
const unpaidAddresses = new Set<string>();
|
||||
/** HD still holding USDT that is not yet covered by ledger deposits (needs credit recover). */
|
||||
const uncreditedHd = new Set<string>();
|
||||
/** HD with any on-chain USDT (ops log / sweep path). */
|
||||
let hdHoldingCount = 0;
|
||||
for (const { address, user_id } of userWallets) {
|
||||
try {
|
||||
const bal = await bscService.getUsdtBalanceRaw(address, contract);
|
||||
@ -196,15 +200,25 @@ export async function processBscDeposits(): Promise<void> {
|
||||
address,
|
||||
onChainAmount: bal,
|
||||
});
|
||||
if (bal > 0n) unpaidAddresses.add(address.toLowerCase());
|
||||
if (bal <= 0n) continue;
|
||||
hdHoldingCount += 1;
|
||||
const caughtUp = await depositHdSnapshotRepository.isAddressLedgerCaughtUp(
|
||||
address,
|
||||
bal,
|
||||
custodyDecimals
|
||||
);
|
||||
if (!caughtUp) uncreditedHd.add(address.toLowerCase());
|
||||
} catch (e) {
|
||||
console.error(`[deposit] USDT_BEP20: balance check failed for ${address}:`, e);
|
||||
}
|
||||
}
|
||||
|
||||
if (unpaidAddresses.size > 0) {
|
||||
if (hdHoldingCount > 0) {
|
||||
console.warn(
|
||||
`[deposit] USDT_BEP20: ${unpaidAddresses.size} HD address(es) still hold USDT — will recover via logs + explorer`
|
||||
`[deposit] USDT_BEP20: ${hdHoldingCount} HD address(es) still hold USDT` +
|
||||
(uncreditedHd.size > 0
|
||||
? ` — ${uncreditedHd.size} not yet credited (recover)`
|
||||
: ' — all already credited (awaiting sweep)')
|
||||
);
|
||||
}
|
||||
|
||||
@ -260,7 +274,7 @@ export async function processBscDeposits(): Promise<void> {
|
||||
config.blockchain.bsc.depositInitialLookbackBlocks
|
||||
);
|
||||
for (const { address } of userWallets) {
|
||||
if (!unpaidAddresses.has(address.toLowerCase())) continue;
|
||||
if (!uncreditedHd.has(address.toLowerCase())) continue;
|
||||
try {
|
||||
const still = await bscService.getUsdtBalanceRaw(address, contract);
|
||||
if (still <= 0n) continue;
|
||||
@ -311,6 +325,8 @@ export async function processBscDeposits(): Promise<void> {
|
||||
const result = await creditBscDepositByTxHash(txHash);
|
||||
if (result.credited) {
|
||||
console.log(`[deposit] USDT_BEP20 recovered unpaid via tx=${txHash} user=${result.userId}`);
|
||||
} else if (result.alreadyCredited) {
|
||||
// idempotent — expected when re-scanning
|
||||
} else if (result.reason && !/already|idempotent/i.test(result.reason)) {
|
||||
console.warn(`[deposit] USDT_BEP20 unpaid recover skipped tx=${txHash}: ${result.reason}`);
|
||||
}
|
||||
@ -330,6 +346,7 @@ export async function processBscDeposits(): Promise<void> {
|
||||
*/
|
||||
export async function creditBscDepositByTxHash(txHash: string): Promise<{
|
||||
credited: boolean;
|
||||
alreadyCredited?: boolean;
|
||||
userId?: string;
|
||||
ledgerAmount?: string;
|
||||
reason?: string;
|
||||
@ -388,7 +405,7 @@ export async function creditBscDepositByTxHash(txHash: string): Promise<{
|
||||
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({
|
||||
const inserted = await creditDeposit({
|
||||
userId: wallet.user_id,
|
||||
ledgerWalletTypeId: ledgerType.id,
|
||||
custodyWalletTypeId: custodyType.id,
|
||||
@ -403,6 +420,16 @@ export async function creditBscDepositByTxHash(txHash: string): Promise<{
|
||||
requiredConfirmations: BSC_CONFIRMATIONS,
|
||||
});
|
||||
|
||||
if (!inserted) {
|
||||
return {
|
||||
credited: false,
|
||||
alreadyCredited: true,
|
||||
userId: wallet.user_id,
|
||||
ledgerAmount: ledgerAmount.toString(),
|
||||
reason: 'already credited (idempotent)',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
credited: true,
|
||||
userId: wallet.user_id,
|
||||
@ -423,7 +450,7 @@ async function creditDeposit(opts: {
|
||||
toAddress: string;
|
||||
confirmations: number;
|
||||
requiredConfirmations: number;
|
||||
}): Promise<void> {
|
||||
}): Promise<boolean> {
|
||||
const account = await ledgerRepository.getOrCreateAccount(
|
||||
opts.userId,
|
||||
opts.ledgerWalletTypeId,
|
||||
@ -451,7 +478,7 @@ async function creditDeposit(opts: {
|
||||
});
|
||||
if (!tx) {
|
||||
await client.query('COMMIT');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
await ledgerRepository.creditUsingClient(
|
||||
client,
|
||||
@ -478,7 +505,7 @@ async function creditDeposit(opts: {
|
||||
client.release();
|
||||
}
|
||||
|
||||
if (!tx) return;
|
||||
if (!tx) return false;
|
||||
|
||||
await referralService.processFirstDepositReferralCommissions({
|
||||
userId: opts.userId,
|
||||
@ -507,4 +534,5 @@ async function creditDeposit(opts: {
|
||||
tx.id
|
||||
);
|
||||
queueUserAdminStatsRefresh(opts.userId);
|
||||
return true;
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user