---
updatedAt: 2026-11-17T09:34:05.000Z
agentTools:
  projectIndex: https://cn.developers.tron.network/llms.txt
---

# 扫描已固化的 TRX 与 TRC-20 充值


```javascript JavaScript
import { readFile, rename, writeFile } from 'node:fs/promises';
import { parse } from 'lossless-json';
import { TronWeb } from 'tronweb';

const endpoint = process.env.SOLIDITY_NODE_URL || 'https://api.shasta.trongrid.io';
const networkId = process.env.NETWORK_ID || 'shasta';
const maxBlocks = Number(process.env.MAX_BLOCKS || '100');
const stateFile = process.env.SCAN_STATE_FILE || 'deposits-state.json';
const tokenAddress = process.env.TRC20_CONTRACT_ADDRESS;
const depositAddresses = (process.env.DEPOSIT_ADDRESSES || '')
  .split(',')
  .map((value) => value.trim())
  .filter(Boolean);

if (!Number.isSafeInteger(maxBlocks) || maxBlocks < 1 || maxBlocks > 1000) {
  throw new Error('MAX_BLOCKS 必须是 1 到 1000 之间的整数');
}
if (!TronWeb.isAddress(tokenAddress) || depositAddresses.some((value) => !TronWeb.isAddress(value))) {
  throw new Error('请提供有效的 TRC20_CONTRACT_ADDRESS 和 DEPOSIT_ADDRESSES');
}

const apiKey = process.env.TRON_PRO_API_KEY;
const addressKey = (value) => {
  const hex = String(value).replace(/^0x/, '').toLowerCase();
  if (/^[0-9a-f]{40,64}$/.test(hex)) return hex.slice(-40);
  return TronWeb.address.toHex(value).slice(-40).toLowerCase();
};
const watched = new Set(depositAddresses.map(addressKey));
const allowedToken = addressKey(tokenAddress);
const transferTopic = TronWeb.sha3('Transfer(address,address,uint256)').replace(/^0x/, '').toLowerCase();

async function post(path, body = {}) {
  const response = await fetch(`${endpoint}/${path}`, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      ...(apiKey ? { 'TRON-PRO-API-KEY': apiKey } : {}),
    },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(10_000),
  });
  if (!response.ok) throw new Error(`${path} 返回 HTTP ${response.status}`);
  return parse(await response.text());
}

function readSafeHeight(value, field) {
  const text = String(value);
  const height = Number(text);
  if (!/^\d+$/.test(text) || !Number.isSafeInteger(height)) {
    throw new Error(`${field} 不是有效区块高度`);
  }
  return height;
}

async function loadState() {
  try {
    const state = JSON.parse(await readFile(stateFile, 'utf8'));
    if (state.networkId !== networkId
      || !Number.isSafeInteger(state.nextHeight)
      || state.deposits === null
      || Array.isArray(state.deposits)
      || typeof state.deposits !== 'object') {
      throw new Error('扫描状态文件格式无效');
    }
    return state;
  } catch (error) {
    if (error.code !== 'ENOENT') throw error;
    const startHeight = Number(process.env.START_HEIGHT);
    if (!Number.isSafeInteger(startHeight) || startHeight < 0) {
      throw new Error('首次运行时，START_HEIGHT 必须是非负整数');
    }
    return { networkId, nextHeight: startHeight, lastBlockID: null, deposits: {} };
  }
}

async function saveBlock(state, height, blockID, candidates) {
  const candidateFile = `deposit-candidates-${height}.json`;
  const candidateOutput = {
    network: networkId,
    blockHeight: height,
    blockID,
    previousBlockID: state.lastBlockID,
    candidates,
  };
  await writeFile(
    `${candidateFile}.tmp`,
    `${JSON.stringify(candidateOutput, null, 2)}\n`,
    { mode: 0o600 },
  );
  await rename(`${candidateFile}.tmp`, candidateFile);

  const next = {
    networkId,
    nextHeight: height + 1,
    lastBlockID: blockID,
    deposits: { ...state.deposits },
  };
  for (const candidate of candidates) next.deposits[candidate.eventKey] ??= candidate;
  const temporaryFile = `${stateFile}.tmp`;
  await writeFile(temporaryFile, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
  await rename(temporaryFile, stateFile);
  return next;
}

function base58(value) {
  return TronWeb.address.fromHex(`41${addressKey(value)}`);
}

function readTrxDeposits(transaction, context) {
  const results = [];
  for (const [position, contract] of (transaction.raw_data?.contract || []).entries()) {
    if (contract.type !== 'TransferContract') continue;
    const value = contract.parameter?.value;
    if (!value?.owner_address || !value?.to_address || value.amount == null) continue;
    if (!watched.has(addressKey(value.to_address))) continue;
    const amount = String(value.amount);
    if (!/^\d+$/.test(amount) || BigInt(amount) <= 0n) continue;
    results.push({
      eventKey: `${networkId}:${transaction.txID}:contract:${position}`,
      network: networkId,
      asset: 'TRX',
      txID: transaction.txID,
      ...context,
      position,
      sender: base58(value.owner_address),
      recipient: base58(value.to_address),
      amount,
    });
  }
  return results;
}

async function readTrc20Deposits(transaction, context) {
  if (!(transaction.raw_data?.contract || []).some((contract) =>
    ['TriggerSmartContract', 'CreateSmartContract'].includes(contract.type))) {
    return [];
  }
  const info = await post('walletsolidity/gettransactioninfobyid', { value: transaction.txID });
  if (info.id !== transaction.txID
    || readSafeHeight(info.blockNumber, '收据区块高度') !== context.blockHeight) {
    throw new Error(`交易 ${transaction.txID} 的已固化收据与区块不一致`);
  }
  if (info.receipt?.result !== 'SUCCESS') return [];

  const results = [];
  for (const [position, log] of (info.log || []).entries()) {
    if (addressKey(log.address) !== allowedToken) continue;
    if (log.topics?.[0]?.replace(/^0x/, '').toLowerCase() !== transferTopic || log.topics.length !== 3) continue;
    const recipientHex = log.topics[2].slice(-40).toLowerCase();
    const data = String(log.data || '').replace(/^0x/, '');
    if (!watched.has(recipientHex) || !/^[0-9a-f]{64}$/i.test(data)) continue;
    const amount = BigInt(`0x${data}`);
    if (amount === 0n) continue;
    results.push({
      eventKey: `${networkId}:${transaction.txID}:log:${position}`,
      network: networkId,
      asset: tokenAddress,
      txID: transaction.txID,
      ...context,
      position,
      sender: base58(log.topics[1]),
      recipient: base58(recipientHex),
      amount: amount.toString(),
    });
  }
  return results;
}

const solidifiedHead = await post('walletsolidity/getnowblock');
const headHeight = readSafeHeight(
  solidifiedHead.block_header?.raw_data?.number,
  '已固化区块高度',
);

let state = await loadState();
if (state.lastBlockID) {
  const previousHeight = state.nextHeight - 1;
  const previousBlock = await post('walletsolidity/getblockbynum', { num: previousHeight });
  if (previousBlock.blockID !== state.lastBlockID) {
    throw new Error(`状态文件与 ${networkId} 在区块 ${previousHeight} 的区块 ID 不一致`);
  }
} else if (state.nextHeight > 0) {
  const previousHeight = state.nextHeight - 1;
  const previousBlock = await post('walletsolidity/getblockbynum', { num: previousHeight });
  if (!previousBlock.blockID) throw new Error(`未取得上一区块 ${previousHeight} 的区块 ID`);
  state.lastBlockID = previousBlock.blockID;
}
let height = state.nextHeight;
const endHeight = Math.min(headHeight, height + maxBlocks - 1);

for (; height <= endHeight; height += 1) {
  const block = await post('walletsolidity/getblockbynum', { num: height });
  if (readSafeHeight(block.block_header?.raw_data?.number, '区块高度') !== height || !block.blockID) {
    throw new Error(`未取得完整区块 ${height}`);
  }
  const context = { blockHeight: height, blockID: block.blockID };
  const candidates = [];
  for (const [transactionPosition, transaction] of (block.transactions || []).entries()) {
    const transactionContext = { ...context, transactionPosition };
    candidates.push(...readTrxDeposits(transaction, transactionContext));
    candidates.push(...await readTrc20Deposits(transaction, transactionContext));
  }
  state = await saveBlock(state, height, block.blockID, candidates);
  console.log(`区块 ${height}: ${candidates.length} 条充值候选`);
}

```

# 准备扫描参数

<!-- javascript@1-74 -->

运行扫描脚本前，先安装 Node.js 22.23.4 或更新的 22.x 版本，再安装本例依赖的 TronWeb 6.5.2 和 lossless-json 4.3.1：

```shell
npm install --save-exact tronweb@6.5.2 lossless-json@4.3.1
export SOLIDITY_NODE_URL='https://api.shasta.trongrid.io'
export NETWORK_ID='shasta'
export START_HEIGHT='填写开始扫描的已固化区块高度'
export DEPOSIT_ADDRESSES='T地址1,T地址2'
export TRC20_CONTRACT_ADDRESS='T...'
node scan-deposits.mjs
```

`NETWORK_ID` 是写入充值记录和扫描状态的网络标识，同一个状态文件不能跨网络复用。`START_HEIGHT` 只在首次运行时使用。此后脚本从 `deposits-state.json` 中保存的下一高度继续扫描，并核对上一已处理区块的 ID；`MAX_BLOCKS` 控制单次最多处理多少个区块。使用 TronGrid API Key 时，通过 `TRON_PRO_API_KEY` 环境变量提供。脚本还会为每个扫描过的区块生成 `deposit-candidates-<区块高度>.json`，其中包括区块 ID、上一区块 ID 和该区块的充值候选。

# 识别与保存充值候选

<!-- javascript@76-205 -->

脚本从 SolidityNode 获取已固化区块：

* 对 TRX，只识别顶层 `TransferContract`；
* 对 TRC-20，检查合约调用和部署交易的收据，只接受允许列表合约在执行成功交易中发出的标准 `Transfer` Event；零金额 Event 不生成充值候选记录；
* 使用无损 JSON 解析保留 `int64` 金额，并将金额保存为最小单位的十进制整数字符串；
* 每个区块的候选文件与累计状态文件都通过临时文件原子重命名；只有候选文件写入成功后才会前移扫描高度；
* `网络 + txID + contract/log 位置` 构成唯一键，回退游标并重扫不会重复插入。

JSON 状态文件便于查看单进程原型结果，不适合并发扫描或持续增长的生产数据。业务系统应改用数据库唯一约束，并在同一事务中写入充值记录、账本流水和扫描游标，同时处理资产开关、最小充值额和地址归属。若平台允许通过合约路径接收 TRX，还需要解析成功收据中的内部交易。

### 相关阅读

* [交易所钱包集成 — 基于区块扫描的充值监听机制](doc:exchangewallet-integrate-with-the-tron-network#5-基于区块扫描的充值监听机制)
* [确认语义](https://cn.developers.tron.network/docs/confirmation-semantics)
* [TRC-20 Event](doc:trc20-protocol-interface#事件参考)