games_app/backend/src/services/blockchain/bscService.ts

264 lines
8.2 KiB
TypeScript

/**
* BSC (EVM) blockchain integration via JSON-RPC.
* USDT BEP20 Transfer event scanning and outbound ERC-20 transfers.
*/
import { ethers } from 'ethers';
import { config } from '../../config';
import { parseExplorerTokenTxResult } from '../../utils/bscExplorerTokentx';
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 = 60_000;
const MIN_GETLOGS_BLOCK_RANGE = 10;
function isBlockRangeLimitError(err: unknown): boolean {
const parts = [
(err as { message?: string })?.message,
(err as { shortMessage?: string })?.shortMessage,
(err as { error?: { message?: string } })?.error?.message,
];
return parts.some((m) => typeof m === 'string' && /block range exceeds|query returned more than|limit exceeded/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);
}
return provider;
}
export function resolveUsdtContract(dbContract: string | null | undefined): string {
const fromEnv = config.blockchain.bsc.usdtBep20Contract?.trim();
if (fromEnv) return ethers.getAddress(fromEnv);
if (dbContract?.trim()) return ethers.getAddress(dbContract.trim());
return ethers.getAddress('0x55d398326f99059fF775485246999027B3197955');
}
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,
fromBlock: number,
maxEndBlock?: number
): Promise<
Array<{
txHash: string;
from: string;
to: string;
value: bigint;
blockNumber: number;
}>
> {
const p = getProvider();
const contract = new ethers.Contract(resolveUsdtContract(contractAddress), ERC20_ABI, p);
const toNormalized = ethers.getAddress(toAddress.startsWith('0x') ? toAddress : '0x' + toAddress);
const filter = contract.filters.Transfer(null, toNormalized);
const currentBlock = await p.getBlockNumber();
const endCap = maxEndBlock != null ? Math.min(maxEndBlock, currentBlock) : currentBlock;
const out: Array<{ txHash: string; from: string; to: string; value: bigint; blockNumber: number }> = [];
let chunkSize = config.blockchain.bsc.getLogsBlockRange;
for (let start = fromBlock; start <= endCap; ) {
let chunk = chunkSize;
while (true) {
const end = Math.min(start + chunk - 1, endCap);
try {
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 (isBlockRangeLimitError(err) && chunk > MIN_GETLOGS_BLOCK_RANGE) {
chunk = Math.max(MIN_GETLOGS_BLOCK_RANGE, Math.floor(chunk / 2));
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) {
chunk = Math.max(MIN_GETLOGS_BLOCK_RANGE, Math.floor(chunk / 2));
await new Promise((r) => setTimeout(r, 400));
continue;
}
throw err;
}
}
}
return out;
}
type ExplorerTokentxRow = {
hash?: string;
from?: string;
to?: string;
contractAddress?: string;
};
function explorerUsdtHashes(payload: unknown, usdtContract: string, toAddress: string): string[] {
const wantTo = toAddress.toLowerCase();
return parseExplorerTokenTxResult(payload, usdtContract)
.filter((row) => !row.to || row.to.toLowerCase() === wantTo)
.map((row) => row.hash);
}
async function fetchExplorerTokentx(url: string): Promise<unknown> {
const res = await fetch(url, { signal: AbortSignal.timeout(20_000) });
if (!res.ok) throw new Error(`explorer HTTP ${res.status}`);
return res.json();
}
/**
* Incoming USDT tx hashes for an address (Etherscan-compatible explorer).
* Used when eth_getLogs is empty/rate-limited but the HD still holds USDT.
*/
export async function listIncomingUsdtTxHashesViaExplorer(
toAddress: string,
contractAddress: string
): Promise<string[]> {
const usdt = resolveUsdtContract(contractAddress);
const to = ethers.getAddress(toAddress);
const key = config.blockchain.bsc.explorerApiKey.trim();
const urls: string[] = [];
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.blockchain.bsc.explorerApiUrl.replace(/\/$/, '');
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 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 [];
}
export async function sendUsdt(
fromPrivateKeyHex: string,
contractAddress: string,
toAddress: string,
amountRaw: bigint
): Promise<string> {
const p = getProvider();
const wallet = new ethers.Wallet(
fromPrivateKeyHex.startsWith('0x') ? fromPrivateKeyHex : '0x' + fromPrivateKeyHex,
p
);
const contract = new ethers.Contract(resolveUsdtContract(contractAddress), ERC20_ABI, wallet);
const tx = await contract.transfer(toAddress, amountRaw);
const receipt = await tx.wait();
return receipt.hash;
}
export async function getNativeBalanceWei(address: string): Promise<bigint> {
return getProvider().getBalance(address);
}
export async function getUsdtBalanceRaw(address: string, contractAddress: string): Promise<bigint> {
const p = getProvider();
const contract = new ethers.Contract(resolveUsdtContract(contractAddress), ERC20_ABI, p);
return contract.balanceOf(address);
}
export async function sendBnb(
fromPrivateKeyHex: string,
toAddress: string,
amountWei: bigint
): Promise<string> {
const p = getProvider();
const wallet = new 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;
}