258 lines
9.6 KiB
JavaScript
258 lines
9.6 KiB
JavaScript
"use strict";
|
|
/**
|
|
* TRON blockchain integration via TronGrid.
|
|
* Read incoming TRX/TRC20 transfers and broadcast outbound transactions.
|
|
*/
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.PG_BIGINT_MAX = void 0;
|
|
exports.parseTrc20TokenAmount = parseTrc20TokenAmount;
|
|
exports.getCurrentBlock = getCurrentBlock;
|
|
exports.getBlockTimestamp = getBlockTimestamp;
|
|
exports.getTrxTransactionsToAddress = getTrxTransactionsToAddress;
|
|
exports.getTrc20TransfersToAddress = getTrc20TransfersToAddress;
|
|
exports.sendTrx = sendTrx;
|
|
exports.sendTrc20 = sendTrc20;
|
|
exports.getTrxBalanceSun = getTrxBalanceSun;
|
|
exports.getTrc20BalanceRaw = getTrc20BalanceRaw;
|
|
const hdWallet_1 = require("../hdWallet");
|
|
const TRON_GRID_URL = process.env.TRON_NODE_URL || 'https://api.trongrid.io';
|
|
const TRON_API_KEY = process.env.TRON_API_KEY || '';
|
|
/** PostgreSQL signed BIGINT upper bound. */
|
|
exports.PG_BIGINT_MAX = 9223372036854775807n;
|
|
/**
|
|
* Parses a TRC20 transfer `value` from TronGrid into smallest token units.
|
|
* Rejects non-decimal strings, floats, negative values, and amounts that do not fit in PG BIGINT.
|
|
*/
|
|
function parseTrc20TokenAmount(raw) {
|
|
if (raw == null)
|
|
return null;
|
|
let digits;
|
|
if (typeof raw === 'bigint') {
|
|
digits = raw.toString();
|
|
}
|
|
else if (typeof raw === 'number') {
|
|
if (!Number.isFinite(raw) || raw <= 0 || !Number.isInteger(raw))
|
|
return null;
|
|
digits = raw.toString();
|
|
}
|
|
else if (typeof raw === 'string') {
|
|
const s = raw.trim();
|
|
if (!/^\d+$/.test(s))
|
|
return null;
|
|
digits = s;
|
|
}
|
|
else {
|
|
return null;
|
|
}
|
|
try {
|
|
const amount = BigInt(digits);
|
|
if (amount <= 0n || amount > exports.PG_BIGINT_MAX)
|
|
return null;
|
|
return amount;
|
|
}
|
|
catch {
|
|
return null;
|
|
}
|
|
}
|
|
/**
|
|
* Performs an authenticated GET request to TronGrid REST API.
|
|
* @param path API path including query string (e.g. /v1/accounts/...)
|
|
* @returns Parsed JSON response body
|
|
* @throws {Error} When HTTP status is not OK
|
|
*/
|
|
async function tronFetch(path) {
|
|
const url = `${TRON_GRID_URL}${path}`;
|
|
const headers = { 'Content-Type': 'application/json' };
|
|
if (TRON_API_KEY)
|
|
headers['TRON-PRO-API-KEY'] = TRON_API_KEY;
|
|
const res = await fetch(url, { headers });
|
|
if (!res.ok)
|
|
throw new Error(`TronGrid: ${res.status}`);
|
|
return res.json();
|
|
}
|
|
/**
|
|
* Returns the current TRON block number from the node.
|
|
* @returns Latest block height
|
|
*/
|
|
async function getCurrentBlock() {
|
|
const tronWeb = (0, hdWallet_1.getTronWeb)();
|
|
const block = await tronWeb.trx.getCurrentBlock();
|
|
return block.block_header.raw_data.number;
|
|
}
|
|
/**
|
|
* Returns the block timestamp in Unix ms for a given block height.
|
|
*/
|
|
async function getBlockTimestamp(blockNumber) {
|
|
if (!Number.isFinite(blockNumber) || blockNumber < 0)
|
|
return null;
|
|
try {
|
|
const tronWeb = (0, hdWallet_1.getTronWeb)();
|
|
const trx = tronWeb.trx;
|
|
const block = await trx.getBlock(blockNumber);
|
|
const ts = block?.block_header?.raw_data?.timestamp;
|
|
return typeof ts === 'number' && ts > 0 ? ts : null;
|
|
}
|
|
catch {
|
|
return null;
|
|
}
|
|
}
|
|
/**
|
|
* Normalizes a TRON address to lowercase hex for comparison (API raw_data often returns hex).
|
|
* @param address Base58 or hex TRON address
|
|
* @returns Lowercase hex without 0x prefix, or original on conversion failure
|
|
*/
|
|
function toHexAddress(address) {
|
|
if (!address)
|
|
return '';
|
|
const tw = (0, hdWallet_1.getTronWeb)();
|
|
try {
|
|
const hex = tw.address.toHex(address);
|
|
return (hex || '').toLowerCase().replace(/^0x/, '');
|
|
}
|
|
catch {
|
|
return address.toLowerCase();
|
|
}
|
|
}
|
|
/**
|
|
* Fetches confirmed incoming TRX transfers to an address since an optional timestamp.
|
|
* @param address TRON base58 deposit address
|
|
* @param minTimestamp Optional minimum block timestamp in ms (filters older txs)
|
|
* @returns Parsed incoming transactions with estimated confirmations (~3s per block)
|
|
*/
|
|
async function getTrxTransactionsToAddress(address, minTimestamp) {
|
|
const q = new URLSearchParams();
|
|
q.set('limit', '200');
|
|
q.set('only_confirmed', 'true');
|
|
q.set('only_to', 'true');
|
|
if (minTimestamp != null && minTimestamp > 0)
|
|
q.set('min_block_timestamp', String(minTimestamp));
|
|
const data = (await tronFetch(`/v1/accounts/${address}/transactions?${q.toString()}`));
|
|
const addressHex = toHexAddress(address);
|
|
const rawList = data.data || [];
|
|
const txs = [];
|
|
for (const tx of rawList) {
|
|
const contract = tx.raw_data?.contract?.[0];
|
|
const param = contract?.parameter?.value;
|
|
if (!param || param.to_address == null)
|
|
continue;
|
|
const toRaw = (param.to_address || '').trim();
|
|
const toHex = toRaw.startsWith('T')
|
|
? toHexAddress(toRaw)
|
|
: toRaw.toLowerCase().replace(/^0x/, '');
|
|
if (!toHex || !addressHex || toHex !== addressHex)
|
|
continue;
|
|
const amount = param.amount ?? 0;
|
|
const from = param.owner_address ?? '';
|
|
// block_timestamp is Unix ms; chain block number is not timestamp/3000. Use elapsed time for confirmations (~3s per block).
|
|
const confirmations = Math.max(0, Math.floor((Date.now() - tx.block_timestamp) / 3000));
|
|
txs.push({
|
|
txId: tx.txID,
|
|
from,
|
|
to: address,
|
|
amount,
|
|
block: 0,
|
|
confirmations,
|
|
});
|
|
}
|
|
if (process.env.NODE_ENV !== 'production' && rawList.length > 0 && txs.length === 0) {
|
|
const sample = rawList[0];
|
|
const c = sample.raw_data?.contract?.[0];
|
|
const p = c?.parameter?.value;
|
|
console.log('[tron] TRX: API returned', rawList.length, 'tx(s) but none matched address. Sample:', {
|
|
txID: sample.txID,
|
|
to_address_raw: p?.to_address,
|
|
addressHex,
|
|
hasRawData: !!sample.raw_data,
|
|
});
|
|
}
|
|
return txs;
|
|
}
|
|
/**
|
|
* Fetches confirmed incoming TRC20 transfers to an address for a given contract.
|
|
* @param address TRON base58 deposit address
|
|
* @param contractAddress TRC20 contract address (e.g. USDT)
|
|
* @param minTimestamp Optional minimum event timestamp in ms
|
|
* @returns Transfers where `to` matches the address, with raw token value as string
|
|
*/
|
|
async function getTrc20TransfersToAddress(address, contractAddress, minTimestamp) {
|
|
const q = new URLSearchParams();
|
|
q.set('limit', '200');
|
|
q.set('contract_address', contractAddress);
|
|
q.set('only_confirmed', 'true');
|
|
if (minTimestamp != null && minTimestamp > 0)
|
|
q.set('min_timestamp', String(minTimestamp));
|
|
const data = (await tronFetch(`/v1/accounts/${address}/transactions/trc20?${q.toString()}`));
|
|
const out = [];
|
|
for (const e of data.data || []) {
|
|
if (e.to?.toLowerCase() !== address.toLowerCase())
|
|
continue;
|
|
const amount = parseTrc20TokenAmount(e.value);
|
|
if (amount == null) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
console.warn(`[tron] TRC20: skip invalid amount for tx=${e.transaction_id} value=${String(e.value)}`);
|
|
}
|
|
continue;
|
|
}
|
|
const confirmations = Math.max(0, Math.floor((Date.now() - e.block_timestamp) / 3000));
|
|
out.push({
|
|
txId: e.transaction_id,
|
|
from: e.from,
|
|
to: e.to,
|
|
value: amount.toString(),
|
|
block: 0,
|
|
block_timestamp: e.block_timestamp,
|
|
confirmations,
|
|
});
|
|
}
|
|
return out;
|
|
}
|
|
/**
|
|
* Sends native TRX from a hot wallet private key.
|
|
* @param fromPrivateKeyHex Sender private key in hex
|
|
* @param toAddress Recipient base58 address
|
|
* @param amountSun Amount in sun (1 TRX = 1e6 sun)
|
|
* @returns Broadcast transaction ID
|
|
* @throws {Error} When broadcast returns no txid
|
|
*/
|
|
async function sendTrx(fromPrivateKeyHex, toAddress, amountSun) {
|
|
const tronWeb = (0, hdWallet_1.getTronWeb)();
|
|
const tx = await tronWeb.transactionBuilder.sendTrx(toAddress, Number(amountSun), fromPrivateKeyHex);
|
|
const signed = await tronWeb.trx.sign(tx, fromPrivateKeyHex);
|
|
const result = await tronWeb.trx.sendRawTransaction(signed);
|
|
const txId = result.txid || result.transaction?.txID;
|
|
if (!txId)
|
|
throw new Error('Send TRX: no txid in result');
|
|
return txId;
|
|
}
|
|
/**
|
|
* Sends TRC20 tokens via contract transfer from a hot wallet.
|
|
* @param fromPrivateKeyHex Sender private key in hex
|
|
* @param contractAddress TRC20 contract address
|
|
* @param toAddress Recipient base58 address
|
|
* @param amountRaw Token amount in smallest unit (string passed to contract)
|
|
* @returns Transaction ID from broadcast result
|
|
*/
|
|
async function sendTrc20(fromPrivateKeyHex, contractAddress, toAddress, amountRaw) {
|
|
const tronWeb = (0, hdWallet_1.getTronWeb)();
|
|
const contract = await tronWeb.contract().at(contractAddress);
|
|
const result = await contract.transfer(toAddress, amountRaw.toString()).send({ from: fromPrivateKeyHex, feeLimit: 100000000 });
|
|
return result?.transaction?.txID || result?.txid || String(result);
|
|
}
|
|
/**
|
|
* Returns native TRX balance in sun for an address.
|
|
*/
|
|
async function getTrxBalanceSun(address) {
|
|
const tronWeb = (0, hdWallet_1.getTronWeb)();
|
|
const balance = await tronWeb.trx.getBalance(address);
|
|
return BigInt(balance ?? 0);
|
|
}
|
|
/**
|
|
* Returns TRC20 token balance in smallest units for an address.
|
|
*/
|
|
async function getTrc20BalanceRaw(address, contractAddress) {
|
|
const tronWeb = (0, hdWallet_1.getTronWeb)();
|
|
const contract = await tronWeb.contract().at(contractAddress);
|
|
const balance = await contract.balanceOf(address).call();
|
|
return BigInt(balance?.toString?.() ?? balance ?? 0);
|
|
}
|
|
//# sourceMappingURL=tronService.js.map
|