After trying to recuparate money from cold wallet4

This commit is contained in:
Your Name 2026-08-28 14:59:30 +02:00
parent a0f84e46fc
commit 3dae5f5fd5
3 changed files with 78 additions and 18 deletions

View File

@ -4,6 +4,10 @@
import { query } from '../db/connection';
function isUndefinedTable(e: unknown): boolean {
return typeof e === 'object' && e !== null && 'code' in e && (e as { code?: string }).code === '42P01';
}
export type HdSnapshotRow = {
user_id: string;
wallet_type_id: number;
@ -27,19 +31,28 @@ export async function upsertSnapshot(input: {
address: string;
onChainAmount: bigint;
}): Promise<void> {
await query(
`INSERT INTO deposit_hd_snapshots (user_id, wallet_type_id, address, on_chain_amount, last_checked_at)
VALUES ($1, $2, $3, $4::numeric, NOW())
ON CONFLICT (user_id, wallet_type_id) DO UPDATE SET
address = EXCLUDED.address,
on_chain_amount = EXCLUDED.on_chain_amount,
last_checked_at = NOW()`,
[input.userId, input.walletTypeId, input.address, input.onChainAmount.toString()]
);
try {
await query(
`INSERT INTO deposit_hd_snapshots (user_id, wallet_type_id, address, on_chain_amount, last_checked_at)
VALUES ($1, $2, $3, $4::numeric, NOW())
ON CONFLICT (user_id, wallet_type_id) DO UPDATE SET
address = EXCLUDED.address,
on_chain_amount = EXCLUDED.on_chain_amount,
last_checked_at = NOW()`,
[input.userId, input.walletTypeId, input.address, input.onChainAmount.toString()]
);
} catch (e) {
if (isUndefinedTable(e)) {
console.warn('[treasury] deposit_hd_snapshots missing — run migrations');
return;
}
throw e;
}
}
export async function listPositiveSnapshots(): Promise<HdSnapshotRow[]> {
return query<HdSnapshotRow[]>(
try {
return await query<HdSnapshotRow[]>(
`SELECT
s.user_id,
s.wallet_type_id,
@ -74,12 +87,27 @@ export async function listPositiveSnapshots(): Promise<HdSnapshotRow[]> {
WHERE s.on_chain_amount > 0
AND u.deleted_at IS NULL
ORDER BY s.on_chain_amount DESC, s.last_checked_at DESC`
);
);
} catch (e) {
if (isUndefinedTable(e)) {
console.warn('[treasury] deposit_hd_snapshots missing — run migrations');
return [];
}
throw e;
}
}
export async function countPositive(): Promise<number> {
const rows = await query<{ c: string }[]>(
`SELECT COUNT(*)::text AS c FROM deposit_hd_snapshots WHERE on_chain_amount > 0`
);
return parseInt(rows[0]?.c ?? '0', 10);
try {
const rows = await query<{ c: string }[]>(
`SELECT COUNT(*)::text AS c FROM deposit_hd_snapshots WHERE on_chain_amount > 0`
);
return parseInt(rows[0]?.c ?? '0', 10);
} catch (e) {
if (isUndefinedTable(e)) {
console.warn('[treasury] deposit_hd_snapshots missing — run migrations');
return 0;
}
throw e;
}
}

View File

@ -21,17 +21,35 @@ function isBlockRangeLimitError(err: unknown): boolean {
(err as { message?: string })?.message,
(err as { shortMessage?: string })?.shortMessage,
(err as { error?: { message?: string } })?.error?.message,
JSON.stringify((err as { value?: unknown })?.value ?? ''),
];
return parts.some((m) => typeof m === 'string' && /block range exceeds|query returned more than|limit exceeded/i.test(m));
}
function isRpcRateLimitError(err: unknown): boolean {
const parts = [
(err as { message?: string })?.message,
(err as { shortMessage?: string })?.shortMessage,
JSON.stringify((err as { value?: unknown })?.value ?? ''),
];
return parts.some(
(m) =>
typeof m === 'string' &&
/rate limit|-32005|too many requests|429|triggered rate limit/i.test(m)
);
}
let provider: ethers.JsonRpcProvider | null = null;
function getProvider(): ethers.JsonRpcProvider {
if (!provider) {
const req = new ethers.FetchRequest(config.blockchain.bsc.rpcUrl);
req.timeout = RPC_TIMEOUT_MS;
provider = new ethers.JsonRpcProvider(req, 56);
// Public BSC RPCs reject batched eth_getLogs (-32005). One request at a time.
provider = new ethers.JsonRpcProvider(req, 56, {
staticNetwork: true,
batchMaxCount: 1,
});
}
return provider;
}
@ -112,6 +130,7 @@ export async function getUsdtTransfersToAddress(
let chunkSize = config.blockchain.bsc.getLogsBlockRange;
for (let start = fromBlock; start <= endCap; ) {
let chunk = chunkSize;
let rateLimitTries = 0;
while (true) {
const end = Math.min(start + chunk - 1, endCap);
try {
@ -135,8 +154,14 @@ export async function getUsdtTransfersToAddress(
chunk = Math.max(MIN_GETLOGS_BLOCK_RANGE, Math.floor(chunk / 2));
continue;
}
if (isRpcRateLimitError(err)) {
rateLimitTries += 1;
if (rateLimitTries > 6) throw err;
await new Promise((r) => setTimeout(r, 1500 * rateLimitTries));
continue;
}
const msg = err instanceof Error ? err.message : String(err);
if (/timeout|429|rate limit|too many requests|busy|503/i.test(msg) && chunk > MIN_GETLOGS_BLOCK_RANGE) {
if (/timeout|429|too many requests|busy|503/i.test(msg) && chunk > MIN_GETLOGS_BLOCK_RANGE) {
chunk = Math.max(MIN_GETLOGS_BLOCK_RANGE, Math.floor(chunk / 2));
await new Promise((r) => setTimeout(r, 400));
continue;

View File

@ -124,6 +124,13 @@ export async function getTreasuryOverview() {
const settings = await settingsRepository.getSettings();
let stuckDepositAddresses = 0;
try {
stuckDepositAddresses = await depositHdSnapshotRepository.countPositive();
} catch (e) {
console.warn('[treasury] stuck deposit count failed:', e instanceof Error ? e.message : e);
}
return {
sweepEnabled: config.treasury.sweepEnabled,
withdrawalsEnabled: settings.allow_withdrawals,
@ -144,7 +151,7 @@ export async function getTreasuryOverview() {
status: f.status,
createdAt: f.created_at,
})),
stuckDepositAddresses: await depositHdSnapshotRepository.countPositive(),
stuckDepositAddresses,
};
}