334 lines
14 KiB
JavaScript
334 lines
14 KiB
JavaScript
"use strict";
|
||
/**
|
||
* BSC (EVM) blockchain integration via JSON-RPC.
|
||
* USDT BEP20 Transfer event scanning and outbound ERC-20 transfers.
|
||
*/
|
||
Object.defineProperty(exports, "__esModule", { value: true });
|
||
exports.resolveUsdtContract = resolveUsdtContract;
|
||
exports.getCurrentBlock = getCurrentBlock;
|
||
exports.getTransactionReceipt = getTransactionReceipt;
|
||
exports.getNativeTransfer = getNativeTransfer;
|
||
exports.getUsdtTransfersToAddress = getUsdtTransfersToAddress;
|
||
exports.getUsdtTransfersToAddressUntilValue = getUsdtTransfersToAddressUntilValue;
|
||
exports.listIncomingUsdtTxHashesViaExplorer = listIncomingUsdtTxHashesViaExplorer;
|
||
exports.sendUsdt = sendUsdt;
|
||
exports.getNativeBalanceWei = getNativeBalanceWei;
|
||
exports.getUsdtBalanceRaw = getUsdtBalanceRaw;
|
||
exports.sendBnb = sendBnb;
|
||
const ethers_1 = require("ethers");
|
||
const config_1 = require("../../config");
|
||
const bscExplorerTokentx_1 = require("../../utils/bscExplorerTokentx");
|
||
const bscRpcErrors_1 = require("../../utils/bscRpcErrors");
|
||
const ERC20_ABI = [
|
||
'function transfer(address to, uint256 amount) returns (bool)',
|
||
'function balanceOf(address) view returns (uint256)',
|
||
'event Transfer(address indexed from, address indexed to, uint256 value)',
|
||
];
|
||
const RPC_TIMEOUT_MS = 60000;
|
||
const MIN_GETLOGS_BLOCK_RANGE = 10;
|
||
/** Pause between getLogs chunks / wallets to reduce public-RPC bans. */
|
||
const GETLOGS_GAP_MS = 350;
|
||
/** Skip RPCs that recently returned rate-limit / 403 (ms). */
|
||
const RPC_COOLDOWN_MS = 10 * 60 * 1000;
|
||
const providerByUrl = new Map();
|
||
const rpcCooldownUntil = new Map();
|
||
function markRpcCooldown(url, reason) {
|
||
rpcCooldownUntil.set(url, Date.now() + RPC_COOLDOWN_MS);
|
||
console.warn(`[bsc] cooldown ${RPC_COOLDOWN_MS / 1000}s for ${url} (${reason.slice(0, 80)})`);
|
||
}
|
||
function providerFor(url) {
|
||
const key = url.trim();
|
||
let p = providerByUrl.get(key);
|
||
if (!p) {
|
||
const req = new ethers_1.ethers.FetchRequest(key);
|
||
req.timeout = RPC_TIMEOUT_MS;
|
||
// Public BSC RPCs reject batched eth_getLogs (-32005). One request at a time.
|
||
p = new ethers_1.ethers.JsonRpcProvider(req, 56, {
|
||
staticNetwork: true,
|
||
batchMaxCount: 1,
|
||
});
|
||
providerByUrl.set(key, p);
|
||
}
|
||
return p;
|
||
}
|
||
function getProvider() {
|
||
return providerFor(config_1.config.blockchain.bsc.rpcUrl);
|
||
}
|
||
/** Primary RPC + configured fallbacks (deduped) for eth_getLogs only. Cool RPC last. */
|
||
function getLogsRpcUrls() {
|
||
const primary = config_1.config.blockchain.bsc.rpcUrl.trim();
|
||
const fallbacks = config_1.config.blockchain.bsc.rpcFallbacks;
|
||
const all = [];
|
||
for (const u of [primary, ...fallbacks]) {
|
||
const t = u.trim();
|
||
if (t && !all.includes(t))
|
||
all.push(t);
|
||
}
|
||
const now = Date.now();
|
||
const ready = all.filter((u) => (rpcCooldownUntil.get(u) ?? 0) <= now);
|
||
const cooling = all.filter((u) => (rpcCooldownUntil.get(u) ?? 0) > now);
|
||
// Prefer ready RPCs; only retry cooled ones if nothing else is left.
|
||
return ready.length > 0 ? ready : cooling;
|
||
}
|
||
function resolveUsdtContract(dbContract) {
|
||
const fromEnv = config_1.config.blockchain.bsc.usdtBep20Contract?.trim();
|
||
if (fromEnv)
|
||
return ethers_1.ethers.getAddress(fromEnv);
|
||
if (dbContract?.trim())
|
||
return ethers_1.ethers.getAddress(dbContract.trim());
|
||
return ethers_1.ethers.getAddress('0x55d398326f99059fF775485246999027B3197955');
|
||
}
|
||
async function getCurrentBlock() {
|
||
return getProvider().getBlockNumber();
|
||
}
|
||
const TRANSFER_TOPIC = ethers_1.ethers.id('Transfer(address,address,uint256)');
|
||
/** Fetches a tx receipt and parses ERC-20 Transfer logs (for deposit recovery). */
|
||
async function getTransactionReceipt(txHash) {
|
||
const p = getProvider();
|
||
const receipt = await p.getTransactionReceipt(txHash);
|
||
if (!receipt)
|
||
return null;
|
||
const transfers = [];
|
||
for (const log of receipt.logs) {
|
||
if (log.topics[0] !== TRANSFER_TOPIC || log.topics.length < 3)
|
||
continue;
|
||
try {
|
||
transfers.push({
|
||
contract: ethers_1.ethers.getAddress(log.address),
|
||
from: ethers_1.ethers.getAddress(ethers_1.ethers.dataSlice(log.topics[1], 12)),
|
||
to: ethers_1.ethers.getAddress(ethers_1.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,
|
||
};
|
||
}
|
||
/** Native BNB transfer details (for cold↔hot gas funding confirm). */
|
||
async function getNativeTransfer(txHash) {
|
||
const p = getProvider();
|
||
const [tx, receipt] = await Promise.all([p.getTransaction(txHash), p.getTransactionReceipt(txHash)]);
|
||
if (!tx || !receipt)
|
||
return null;
|
||
return {
|
||
status: receipt.status === null ? 0 : Number(receipt.status),
|
||
from: tx.from,
|
||
to: tx.to,
|
||
value: tx.value,
|
||
};
|
||
}
|
||
async function queryUsdtTransfersOnRpc(rpcUrl, toAddress, contractAddress, fromBlock, endCap) {
|
||
const p = providerFor(rpcUrl);
|
||
const contract = new ethers_1.ethers.Contract(resolveUsdtContract(contractAddress), ERC20_ABI, p);
|
||
const toNormalized = ethers_1.ethers.getAddress(toAddress.startsWith('0x') ? toAddress : '0x' + toAddress);
|
||
const filter = contract.filters.Transfer(null, toNormalized);
|
||
const out = [];
|
||
let chunkSize = config_1.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 {
|
||
await new Promise((r) => setTimeout(r, GETLOGS_GAP_MS));
|
||
const events = await contract.queryFilter(filter, start, end);
|
||
for (const e of events) {
|
||
const args = 'args' in e ? e.args : undefined;
|
||
if (args && e.blockNumber !== null) {
|
||
out.push({
|
||
txHash: e.transactionHash,
|
||
from: String(args[0]),
|
||
to: String(args[1]),
|
||
value: BigInt(args[2]),
|
||
blockNumber: e.blockNumber,
|
||
});
|
||
}
|
||
}
|
||
start = end + 1;
|
||
break;
|
||
}
|
||
catch (err) {
|
||
if ((0, bscRpcErrors_1.isBlockRangeLimitError)(err) && chunk > MIN_GETLOGS_BLOCK_RANGE) {
|
||
chunk = Math.max(MIN_GETLOGS_BLOCK_RANGE, Math.floor(chunk / 2));
|
||
continue;
|
||
}
|
||
if ((0, bscRpcErrors_1.isRpcRateLimitError)(err)) {
|
||
rateLimitTries += 1;
|
||
if (rateLimitTries > 3)
|
||
throw err;
|
||
await new Promise((r) => setTimeout(r, 2000 * rateLimitTries));
|
||
continue;
|
||
}
|
||
const msg = err instanceof Error ? err.message : String(err);
|
||
if (/timeout|busy|503|502/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;
|
||
}
|
||
throw err;
|
||
}
|
||
}
|
||
}
|
||
return out;
|
||
}
|
||
/**
|
||
* eth_getLogs for USDT transfers to an HD address.
|
||
* Tries primary RPC then configured fallbacks (public dataseed often returns -32005).
|
||
*/
|
||
async function getUsdtTransfersToAddress(toAddress, contractAddress, fromBlock, maxEndBlock) {
|
||
const tipProvider = getProvider();
|
||
const currentBlock = await tipProvider.getBlockNumber();
|
||
const endCap = maxEndBlock != null ? Math.min(maxEndBlock, currentBlock) : currentBlock;
|
||
if (fromBlock > endCap)
|
||
return [];
|
||
const urls = getLogsRpcUrls();
|
||
let lastErr;
|
||
for (let i = 0; i < urls.length; i++) {
|
||
const url = urls[i];
|
||
try {
|
||
const hits = await queryUsdtTransfersOnRpc(url, toAddress, contractAddress, fromBlock, endCap);
|
||
if (url !== config_1.config.blockchain.bsc.rpcUrl.trim() && hits.length > 0) {
|
||
console.warn(`[bsc] eth_getLogs ok via ${url} for ${toAddress} hits=${hits.length} blocks=${fromBlock}-${endCap}`);
|
||
}
|
||
else if (hits.length > 0) {
|
||
console.log(`[bsc] eth_getLogs ok via primary for ${toAddress} hits=${hits.length} blocks=${fromBlock}-${endCap}`);
|
||
}
|
||
return hits;
|
||
}
|
||
catch (err) {
|
||
lastErr = err;
|
||
const msg = err instanceof Error ? err.message : String(err);
|
||
markRpcCooldown(url, msg);
|
||
console.warn(`[bsc] eth_getLogs failed on ${url} for ${toAddress}: ${msg.slice(0, 180)} — trying next RPC`);
|
||
}
|
||
}
|
||
throw lastErr instanceof Error
|
||
? lastErr
|
||
: new Error(`eth_getLogs failed on all RPCs for ${toAddress}`);
|
||
}
|
||
/**
|
||
* Newest-first getLogs for unpaid HDs: stop once cumulative Transfer value covers on-chain balance.
|
||
* Avoids scanning a full 7-day window when the deposit is only ~1–2 days old.
|
||
*/
|
||
async function getUsdtTransfersToAddressUntilValue(toAddress, contractAddress, fromBlock, maxEndBlock, minValue) {
|
||
const tipProvider = getProvider();
|
||
const currentBlock = await tipProvider.getBlockNumber();
|
||
const endCap = Math.min(maxEndBlock, currentBlock);
|
||
const startFloor = Math.max(0, fromBlock);
|
||
if (startFloor > endCap)
|
||
return [];
|
||
const chunk = Math.max(MIN_GETLOGS_BLOCK_RANGE, config_1.config.blockchain.bsc.getLogsBlockRange);
|
||
const byHash = new Map();
|
||
let covered = 0n;
|
||
for (let end = endCap; end >= startFloor && covered < minValue;) {
|
||
const start = Math.max(startFloor, end - chunk + 1);
|
||
const part = await getUsdtTransfersToAddress(toAddress, contractAddress, start, end);
|
||
for (const t of part) {
|
||
if (!byHash.has(t.txHash)) {
|
||
byHash.set(t.txHash, t);
|
||
covered += t.value;
|
||
}
|
||
}
|
||
if (start <= startFloor)
|
||
break;
|
||
end = start - 1;
|
||
}
|
||
return [...byHash.values()].sort((a, b) => a.blockNumber - b.blockNumber);
|
||
}
|
||
async function fetchExplorerTokentx(url) {
|
||
const res = await fetch(url, { signal: AbortSignal.timeout(20000) });
|
||
if (!res.ok)
|
||
throw new Error(`explorer HTTP ${res.status}`);
|
||
return res.json();
|
||
}
|
||
function explorerUsdtHashes(payload, usdtContract, toAddress) {
|
||
const wantTo = toAddress.toLowerCase();
|
||
return (0, bscExplorerTokentx_1.parseExplorerTokenTxResult)(payload, usdtContract)
|
||
.filter((row) => !row.to || row.to.toLowerCase() === wantTo)
|
||
.map((row) => row.hash);
|
||
}
|
||
/**
|
||
* Incoming USDT tx hashes for an address (Etherscan-compatible explorer).
|
||
* Used when eth_getLogs is empty/rate-limited but the HD still holds USDT.
|
||
*/
|
||
async function listIncomingUsdtTxHashesViaExplorer(toAddress, contractAddress) {
|
||
const usdt = resolveUsdtContract(contractAddress);
|
||
const to = ethers_1.ethers.getAddress(toAddress);
|
||
const key = config_1.config.blockchain.bsc.explorerApiKey.trim();
|
||
const urls = [];
|
||
if (key) {
|
||
const q = new URLSearchParams({
|
||
chainid: '56',
|
||
module: 'account',
|
||
action: 'tokentx',
|
||
contractaddress: usdt,
|
||
address: to,
|
||
page: '1',
|
||
offset: '25',
|
||
sort: 'desc',
|
||
apikey: key,
|
||
});
|
||
urls.push(`https://api.etherscan.io/v2/api?${q.toString()}`);
|
||
}
|
||
const base = config_1.config.blockchain.bsc.explorerApiUrl.replace(/\/$/, '');
|
||
if (base) {
|
||
const q2 = new URLSearchParams({
|
||
module: 'account',
|
||
action: 'tokentx',
|
||
contractaddress: usdt,
|
||
address: to,
|
||
page: '1',
|
||
offset: '25',
|
||
sort: 'desc',
|
||
});
|
||
urls.push(`${base}?${q2.toString()}`);
|
||
}
|
||
for (const url of urls) {
|
||
try {
|
||
const json = await fetchExplorerTokentx(url);
|
||
const status = json?.status;
|
||
const message = json?.message;
|
||
if (status === '0' && message && /NOTOK|deprecated|upgrade|api/i.test(message)) {
|
||
console.warn(`[bsc] explorer NOTOK: ${message}`);
|
||
continue;
|
||
}
|
||
const hashes = explorerUsdtHashes(json, usdt, to);
|
||
if (hashes.length > 0)
|
||
return hashes;
|
||
}
|
||
catch (e) {
|
||
console.warn('[bsc] explorer tokentx failed:', e instanceof Error ? e.message : e);
|
||
}
|
||
}
|
||
return [];
|
||
}
|
||
async function sendUsdt(fromPrivateKeyHex, contractAddress, toAddress, amountRaw) {
|
||
const p = getProvider();
|
||
const wallet = new ethers_1.ethers.Wallet(fromPrivateKeyHex.startsWith('0x') ? fromPrivateKeyHex : '0x' + fromPrivateKeyHex, p);
|
||
const contract = new ethers_1.ethers.Contract(resolveUsdtContract(contractAddress), ERC20_ABI, wallet);
|
||
const tx = await contract.transfer(toAddress, amountRaw);
|
||
const receipt = await tx.wait();
|
||
return receipt.hash;
|
||
}
|
||
async function getNativeBalanceWei(address) {
|
||
return getProvider().getBalance(address);
|
||
}
|
||
async function getUsdtBalanceRaw(address, contractAddress) {
|
||
const p = getProvider();
|
||
const contract = new ethers_1.ethers.Contract(resolveUsdtContract(contractAddress), ERC20_ABI, p);
|
||
return contract.balanceOf(address);
|
||
}
|
||
async function sendBnb(fromPrivateKeyHex, toAddress, amountWei) {
|
||
const p = getProvider();
|
||
const wallet = new ethers_1.ethers.Wallet(fromPrivateKeyHex.startsWith('0x') ? fromPrivateKeyHex : '0x' + fromPrivateKeyHex, p);
|
||
const tx = await wallet.sendTransaction({ to: toAddress, value: amountWei });
|
||
const receipt = await tx.wait();
|
||
return receipt.hash;
|
||
}
|
||
//# sourceMappingURL=bscService.js.map
|