Documentation menu

Forwarder mode: a deposit address per invoice

Status: design, approved direction ("forwarder mode"). Target: Nile first, mainnet after a soak and a contract review. An adversarial review was applied on 2026-12-05. What it changed, and why, is listed in "Review notes" at the end.

Contracts v2 (sweep fees). Sections 1 to 10 describe the first contract version. The contracts, the salt scheme and the selectors were replaced by v2, which binds an optional sweep fee and its collector into each deposit address. Section 11 is the spec for v2 and wins wherever it differs from the text before it.

This document is the implementation spec. Names, types, SQL and Solidity here are meant to be used as written. Everything marked Verified was checked while writing this design (prototype compiled with solc 0.8.19 and run on @ethereumjs/evm, or read from TronGrid). Everything marked Verify on Nile is a rollout gate (section 10.3).

0. What we are building, in one page

Today every invoice is paid to the project's single wallet and matched by unique amount digits (49.907423). Forwarder mode is an optional, per-project alternative:

Decisions (each is explained in its section):

# Decision
D1 Forwarders are stateless EIP-1167 clones. The destination is not stored: the factory re-derives the clone address from (destination, salt) on every call, so only the right destination can address a clone. No init, no storage write, cheapest possible deploy.
D2 The factory is ownerless, stateless, permissionless. One deployment per network can serve every Qirsh install.
D3 The factory calibrates the CREATE2 prefix in its constructor (0x41 on the TVM, 0xff on an EVM) by creating a probe clone. The same bytecode is therefore correct on TRON and executable in tests on ethereumjs.
D4 salt is derived from the invoice id: keccak256("TronGate forwarder salt v1:" ‖ invoice_id) (ids are random, about 131 bits). It is also stored on the invoice, but it is not a secret and nothing relies on it being one. With an invoice id, the wallet and the factory, anyone can recompute a deposit address and flush it to the wallet without the database.
D5 Detection stays transfer-based (TronGrid TRC-20 history per address). A balance lens in the factory (balancesOf(token, address[]), one constant call per 100 addresses) tells the watcher which addresses changed, so idle addresses cost no per-address requests. Two safety nets make this complete: an address is scanned again and again until the books explain its balance (balance = received − swept), and the destination wallet stays polled, because every flush (ours or a stranger's) arrives there as a transfer from the deposit address. The lens reverts rather than report a 0 it did not read.
D6 Auto-settlement rule is the same as today: the transfer that completes the amount must be on-chain before expires_at. Partial, late and extra payments are attributed to the invoice (never "unmatched"), shown in the dashboard, and settled with one click (Accept).
D7 Sweep automatically only what is worth the fee: the funds that paid an invoice (from SWEEP_MIN_AMOUNT), and any other balance (partial, late, extra) only from SWEEP_STRAY_MIN_AMOUNT. Smaller balances stay at their address, which is safe, until someone presses Sweep now. Fee spending is capped per project per day. Sweep state lives on the invoice, every broadcast transaction is logged in sweep_txs.
D8 Transactions are built by TronGrid, then rebuilt locally from what we asked for and compared byte for byte before signing. The signer only accepts a VerifiedTx. A lying TronGrid cannot make the key sign a TRX transfer, a larger fee limit or anything else we did not ask for.
D9 Addresses are only derived from factories whose on-chain code matches the committed artifact (forwarder_factories table). A wrong factory address would otherwise strand funds forever.
D10 One new webhook event: invoice.swept. Stores still fulfil on invoice.paid.
D11 A deposit address is watched forever (once a day after 180 days). Customers reuse addresses, and one lens request covers 100 of them.
D12 A project can have at most FORWARDER_MAX_OPEN_INVOICES open forwarder invoices. Amount mode is capped by its amount slots; forwarder mode needs its own cap so a checkout flood cannot exhaust the API quota that payment detection depends on.

1. Contracts

1.1 Layout

contracts/
  TronGateForwarder.sol          logic contract behind every deposit address
  TronGateForwarderFactory.sol   CREATE2 clone factory, flush entry points, balance lens
  test/Mocks.sol                 MockUSDT, LyingToken, ReentrantToken, RejectingReceiver (tests only)
  artifacts/forwarders.json      committed build output (ABI, bytecode, immutable ranges)
  README.md                      what the contracts do, how to rebuild, how to flush by hand on Tronscan
scripts/compile-contracts.mjs    solc-js build -> contracts/artifacts/forwarders.json

Compiler settings (fixed, also recorded in the artifact): solc 0.8.19, evmVersion: "london", optimizer: { enabled: true, runs: 200 }, metadata: { bytecodeHash: "none" } (so the bytecode does not depend on file paths or comments). Verified: with these settings neither contract contains PUSH0 (0x5f), SELFDESTRUCT or (in the logic contract) DELEGATECALL. Sizes: factory creation code 5207 bytes, factory runtime 3033 bytes, forwarder runtime 1425 bytes (re-measured after the review's change to balancesOf).

package.json scripts: "contracts:build": "node scripts/compile-contracts.mjs". solc stays a devDependency, the runtime reads only the JSON artifact. The Dockerfile's final stage gains COPY contracts/artifacts ./contracts/artifacts.

Artifact shape (contracts/artifacts/forwarders.json):

{
  "compiler": { "version": "0.8.19+commit.7dd6d404", "evmVersion": "london", "optimizer": { "enabled": true, "runs": 200 }, "bytecodeHash": "none" },
  "contracts": {
    "TronGateForwarderFactory": {
      "abi": [],
      "bytecode": "<creation code hex, no 0x>",
      "deployedBytecode": "<runtime hex with immutables zeroed, as solc prints it>",
      "immutableRanges": [{ "start": 279, "length": 32 }],
      "methodIdentifiers": { "flush(address,bytes32,address)": "3ce3efa9" }
    },
    "TronGateForwarder": { "abi": [], "bytecode": "", "deployedBytecode": "", "immutableRanges": [], "methodIdentifiers": {} }
  }
}

immutableRanges is solc's evm.deployedBytecode.immutableReferences flattened and sorted by start. immutables holds the same ranges grouped by variable name (solc keys them by AST id; the build maps ids to names), so verification can check every reference of each immutable. src/tron/artifact.ts loads the file once with readFileSync(new URL("../../contracts/artifacts/forwarders.json", import.meta.url)) (same pattern as public/), which resolves from both src/tron/ (tsx) and dist/tron/ (build).

1.2 TronGateForwarder.sol (use as written; prototype-verified)

// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

/// @title Qirsh forwarder logic
/// @notice Logic behind every deposit address. Deposit addresses are EIP-1167 clones of this contract,
///         created by the factory with CREATE2. The contract has no storage and no owner: it only obeys the
///         factory, and the factory can only ever name the destination that is hashed into the clone's address.
contract TronGateForwarder {
    /// @notice The factory that deployed this logic contract. Lives in code, so clones see it through delegatecall.
    address public immutable factory;

    constructor() {
        factory = msg.sender;
    }

    /// @notice Lets a deployed deposit address receive TRX from contracts.
    receive() external payable {}

    /// @notice Sends this address's whole balance of `token` to `destination`.
    /// @dev TRON USDT returns false from a successful transfer(), so neither the call's success flag nor its
    ///      return data is trusted. The only check is that the balance of this address went down.
    function flushToken(address token, address destination) external returns (uint256 moved) {
        require(msg.sender == factory, "TG: only factory");
        uint256 before = _balanceOf(token);
        if (before == 0) return 0;
        (bool ignored, ) = token.call(abi.encodeWithSelector(0xa9059cbb, destination, before));
        ignored;
        uint256 remaining = _balanceOf(token);
        require(remaining < before, "TG: token did not move");
        moved = before - remaining;
    }

    /// @notice Sends this address's whole TRX balance to `destination`.
    function flushTRX(address payable destination) external returns (uint256 moved) {
        require(msg.sender == factory, "TG: only factory");
        moved = address(this).balance;
        if (moved == 0) return 0;
        (bool ok, ) = destination.call{value: moved}("");
        require(ok, "TG: TRX send failed");
    }

    function _balanceOf(address token) private view returns (uint256 balance) {
        (bool ok, bytes memory data) = token.staticcall(abi.encodeWithSelector(0x70a08231, address(this)));
        require(ok && data.length >= 32, "TG: balanceOf failed");
        balance = abi.decode(data, (uint256));
    }
}

1.3 TronGateForwarderFactory.sol (use as written; prototype-verified)

// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import "./TronGateForwarder.sol";

/// @title Qirsh forwarder factory
/// @notice Ownerless and stateless. A deposit address is the CREATE2 address of an EIP-1167 clone whose salt is
///         keccak256(abi.encode(destination, salt)). Anyone may deploy a clone or flush it, and the only place
///         its funds can go is the destination that is part of its address.
contract TronGateForwarderFactory {
    /// @notice Logic contract every clone delegates to.
    address public immutable implementation;
    /// @notice keccak256 of the clone creation code (constant for this factory).
    bytes32 public immutable cloneCodeHash;
    /// @notice First byte of the CREATE2 preimage on this chain: 0x41 on the TVM, 0xff on the EVM.
    bytes1 public immutable create2Prefix;

    event ForwarderDeployed(address indexed forwarder, address indexed destination, bytes32 salt);
    /// @param token The token that moved, or address(0) for TRX.
    event Flushed(address indexed forwarder, address indexed destination, address indexed token, uint256 amount);

    constructor() {
        address impl = address(new TronGateForwarder());
        bytes memory code = _cloneCode(impl);
        bytes32 codeHash = keccak256(code);
        // Calibrate the CREATE2 prefix against the chain itself, so a wrong formula can never ship:
        // create one throwaway clone and see which preimage reproduces its address.
        address probe;
        assembly {
            probe := create2(0, add(code, 0x20), mload(code), 0)
        }
        require(probe != address(0), "TG: probe failed");
        bytes1 prefix;
        if (probe == _derive(0x41, bytes32(0), codeHash)) prefix = 0x41;
        else if (probe == _derive(0xff, bytes32(0), codeHash)) prefix = 0xff;
        else revert("TG: unknown CREATE2 scheme");
        implementation = impl;
        cloneCodeHash = codeHash;
        create2Prefix = prefix;
    }

    // ---------------------------------------------------------------- views

    /// @notice The deposit address for (destination, salt). It exists as an address before any deployment.
    function forwarderAddress(address destination, bytes32 salt) public view returns (address) {
        return _derive(create2Prefix, _salt(destination, salt), cloneCodeHash);
    }

    /// @notice Same derivation with an explicit prefix. Lets tests cross-check the 0x41 formula on an EVM.
    function forwarderAddressWithPrefix(bytes1 prefix, address destination, bytes32 salt) external view returns (address) {
        return _derive(prefix, _salt(destination, salt), cloneCodeHash);
    }

    function isDeployed(address destination, bytes32 salt) external view returns (bool) {
        return forwarderAddress(destination, salt).code.length != 0;
    }

    /// @notice Balances of many holders in one call (the watcher's change detector).
    /// @dev All or nothing. If any balanceOf call fails or returns short data the whole call reverts: a silent 0
    ///      would look exactly like "someone flushed this address" to the watcher.
    function balancesOf(address token, address[] calldata holders) external view returns (uint256[] memory balances) {
        balances = new uint256[](holders.length);
        for (uint256 i = 0; i < holders.length; i++) {
            (bool ok, bytes memory data) = token.staticcall(abi.encodeWithSelector(0x70a08231, holders[i]));
            require(ok && data.length >= 32, "TG: balanceOf failed");
            balances[i] = abi.decode(data, (uint256));
        }
    }

    // ---------------------------------------------------------------- actions (all permissionless)

    /// @notice Deploys the clone for (destination, salt) if it is not deployed yet. Idempotent.
    function deploy(address destination, bytes32 salt) public returns (address forwarder) {
        require(destination != address(0), "TG: zero destination");
        forwarder = forwarderAddress(destination, salt);
        if (forwarder.code.length == 0) {
            bytes memory code = _cloneCode(implementation);
            bytes32 s = _salt(destination, salt);
            address created;
            assembly {
                created := create2(0, add(code, 0x20), mload(code), s)
            }
            require(created == forwarder, "TG: create2 failed");
            emit ForwarderDeployed(forwarder, destination, salt);
        }
    }

    /// @notice Deploys if needed, then sends the deposit address's whole `token` balance to `destination`.
    function flush(address destination, bytes32 salt, address token) public returns (uint256 amount) {
        address forwarder = deploy(destination, salt);
        amount = TronGateForwarder(payable(forwarder)).flushToken(token, destination);
        if (amount != 0) emit Flushed(forwarder, destination, token, amount);
    }

    /// @notice Deploys if needed, then sends the deposit address's whole TRX balance to `destination`.
    function flushTRX(address destination, bytes32 salt) external returns (uint256 amount) {
        address forwarder = deploy(destination, salt);
        amount = TronGateForwarder(payable(forwarder)).flushTRX(payable(destination));
        if (amount != 0) emit Flushed(forwarder, destination, address(0), amount);
    }

    /// @notice flush() for many deposit addresses of one destination. Empty addresses are skipped, not reverted.
    function flushMany(address destination, bytes32[] calldata salts, address token) external returns (uint256 total) {
        for (uint256 i = 0; i < salts.length; i++) {
            total += flush(destination, salts[i], token);
        }
    }

    // ---------------------------------------------------------------- internals

    function _salt(address destination, bytes32 salt) private pure returns (bytes32) {
        return keccak256(abi.encode(destination, salt));
    }

    function _derive(bytes1 prefix, bytes32 salt, bytes32 codeHash) private view returns (address) {
        return address(uint160(uint256(keccak256(abi.encodePacked(prefix, address(this), salt, codeHash)))));
    }

    /// @dev EIP-1167 minimal proxy creation code for `impl` (55 bytes, 45 bytes of runtime code).
    function _cloneCode(address impl) private pure returns (bytes memory) {
        return abi.encodePacked(hex"3d602d80600a3d3981f3363d3d373d3d3d363d73", impl, hex"5af43d82803e903d91602b57fd5bf3");
    }
}

Selectors (Verified from solc methodIdentifiers):

Function Selector
flush(address,bytes32,address) 3ce3efa9
flushTRX(address,bytes32) ecbd6eee
flushMany(address,bytes32[],address) 7b93fc7f
deploy(address,bytes32) 32c02a14
forwarderAddress(address,bytes32) 19e8131e
forwarderAddressWithPrefix(bytes1,address,bytes32) 514ab65d
isDeployed(address,bytes32) 4d16a9fa
balancesOf(address,address[]) e098e844
implementation() / cloneCodeHash() / create2Prefix() 5c60da1b / 3fefc032 / f6e9e41b

Event topics: Flushed(address,address,address,uint256) = f5c342afbc0fd5497d66d2246a8208902c06a969755b7f7c415041a67d222caf, ForwarderDeployed(address,address,bytes32) = 2211fc4e7096d5cc5ab1fcc4fbaec5de042ca727561d98d410ce9583b9ccc137.

1.4 Salt scheme: how the destination is bound

create2Salt   = keccak256(abi.encode(address destination, bytes32 salt))      // 64-byte preimage
cloneInitCode = 3d602d80600a3d3981f3363d3d373d3d3d363d73 ++ implementation20 ++ 5af43d82803e903d91602b57fd5bf3
depositAddr20 = keccak256(0x41 ++ factory20 ++ create2Salt ++ keccak256(cloneInitCode))[12..32]
depositAddr   = base58check(0x41 ++ depositAddr20)

salt is the invoice's 32 bytes, derived from the invoice id (D4, section 2.2). It only makes addresses distinct. It is public by design and is not what protects the funds. The destination is part of the CREATE2 salt, so a different destination is a different address. The clone itself stores nothing. Every factory entry point takes (destination, salt), derives the address from them, and tells that clone to pay destination. To make a clone pay anyone else, a caller would have to find a second (destination', salt') with the same Keccak-256 hash.

1.5 Edge cases and why they are safe

Case Behaviour
USDT transfer() returns false Ignored. flushToken checks only that the forwarder's balance went down. Verified with MockUSDT (returns false, moves funds).
Token claims success, moves nothing Reverts TG: token did not move. Verified with LyingToken.
Token reverts (frozen/blacklisted forwarder or destination) The balance did not move, so the flush reverts. Funds stay at the deposit address and can be flushed later. Verified.
Fee-on-transfer token Irrelevant: the check is on the sender side. moved is what left the forwarder.
Address already deployed deploy is a no-op, flush just flushes. A second payment to the same address is flushed the same way. Verified (top-up flush: ~10k gas on the EVM with the mock token).
Empty address Deployed: flush returns 0 without reverting and emits nothing (~3.9k gas), so a double sweep costs little and flushMany never fails because one address is empty. Not deployed: flush still deploys the clone (about 52k gas, roughly 5 TRX) and moves nothing (Verified on the EVM). The sweeper therefore never broadcasts a flush whose dry run reports amount == 0 (section 7.3).
Front-run deploy Harmless, deployment is idempotent and the clone is identical whoever deploys it.
TRX sent to the address flushTRX. Verified for an address funded before deployment and for value sent to a deployed clone (receive()). A TRX transfer to an undeployed address activates it as a normal account (the sender pays the activation fee). The later CREATE2 still works: under the Constantinople rules java-tron refuses CREATE2 only when a contract already exists at the address, converts an existing normal account into a contract account and keeps its balance (Verified in java-tron Program.createContractImpl: contractAlreadyExists = existingAccount != null && isContractExist(…), then updateAccountType(AccountType.Contract)). So nobody can block a deployment, and lock the USDT behind it, by sending dust first. This stays a Nile rollout gate anyway (10.3), because it is the one TVM behaviour whose failure would lock funds. Once the clone is deployed the network rejects plain TRX transfers to it (Cannot transfer TRX to a smartContract., Verified in TransferActuator).
TRC-10 token sent to the address Never counted as a payment: the watcher reads only TRC-20 transfers of the configured token contract, so a fake TRC-10 "USDT" cannot pay an invoice. Not recoverable: stock solc cannot emit the TVM token-transfer opcode, so the forwarder has no TRC-10 exit. In practice TRC-10 dust is worthless spam; the docs say so. Before deployment it activates the account exactly like TRX and is covered by the same CREATE2 rule and the same Nile gate. Signed transactions never carry call_token_value or token_id (3.3).
Zero-value transfers to the address USDT accepts transfer(x, 0) and transferFrom(anyone, x, 0) (the address-poisoning trick). They move nothing, never change a balance, and the watcher drops them (6.3).
Token call fails inside the lens balancesOf reverts with TG: balanceOf failed, also when token is not a contract. The watcher sees a failed tick, never an invented 0 that it would read as "flushed". Verified on the EVM.
The project wallet is an exchange deposit address A sweep reaches the wallet as a transfer made by a contract. USDT still emits a normal Transfer event, but some exchanges do not credit deposits sent by contracts, and TRX recovered with flushTRX is an internal transaction that many exchanges ignore. The settings card and the docs tell the merchant to use a self-custody wallet, or to confirm with the exchange first (5.2).
Wrong token sent flush(destination, salt, thatToken). Any token contract with balanceOf and transfer.
Reentrancy Neither contract has storage. A malicious token or destination that re-enters can only trigger more flushes to the bound destination.
Direct call to a clone or to the logic contract Reverts TG: only factory. Verified. Funds sent to the logic contract itself are not recoverable (document it, nobody has a reason to do it).
destination == address(0) Reverts TG: zero destination. Verified.
Logic contract destroyed Impossible: no SELFDESTRUCT, no DELEGATECALL, no owner. The test asserts the opcodes are absent.
Wrong CREATE2 formula The constructor reverts unless the probe clone lands where one of the two formulas says, and deploy reverts unless create2 returns the predicted address.

1.6 Why a compromised fee key cannot redirect funds

The fee key is an ordinary TRON account. It is not an owner or admin of anything: the factory has no privileged functions and the clones obey only the factory. With the key an attacker can do exactly what any stranger can do, call flush, which sends funds to the wallet bound into the address, plus spend the fee wallet's own TRX. Keep that balance small (section 5), and keep nothing else there: whatever the fee wallet holds besides its TRX float (tokens, staked TRX) belongs to whoever has the key. Never reuse a merchant wallet's key as the fee key; requirements() refuses a project whose wallet is the fee payer.

1.7 Cost

Measured on the EVM with a cheap mock token (execution gas, without the token's own transfer cost): deploy + flush about 56k, flush of an already deployed address about 10k, factory deployment about 967k. On TRON a USDT transfer adds roughly 65k energy (130k when the receiving wallet holds no USDT), and USDT is subject to the dynamic energy model. Expect about 110k to 130k energy for a first sweep, which is about 11 to 13 TRX at the current price of 100 sun per energy (Verified on mainnet and Nile: getEnergyFee = 100), or close to zero if the fee wallet has staked or delegated energy. Deploying the factory costs about 1M energy (about 100 TRX). Verify on Nile and put the measured numbers in the README.

A sweep is therefore worth a few US dollars of TRX unless the energy is staked or rented. Two consequences run through the rest of this design: a balance smaller than the cost of moving it is not swept automatically (7.1), and the README must tell merchants that forwarder mode has a per-payment cost that amount mode does not have, so SWEEP_MIN_AMOUNT (also the smallest invoice) should not be far below it.

2. Off-chain address derivation

2.1 src/tron/address.ts (extend the existing file)

export function base58CheckEncode(payload: Uint8Array): string;           // payload = 0x41 ++ 20 bytes
export function base58CheckDecode(address: string): Uint8Array;           // 21 bytes, throws on bad checksum/prefix
export function tronToEvm(address: string): Uint8Array;                   // 20 bytes
export function evmToTron(addr20: Uint8Array): string;                    // T...
export function addressFromPublicKey(uncompressed65: Uint8Array): string; // keccak256(pub[1..65])[12..32]
export function addressFromPrivateKey(key: Uint8Array): string;

isValidTronAddress keeps its behaviour and is reimplemented on top of base58CheckDecode.

2.2 src/tron/create2.ts

/** TRON derives CREATE2 addresses with 0x41 where Ethereum uses 0xff. */
export const TVM_CREATE2_PREFIX = 0x41;

/** keccak256(prefix ++ deployer20 ++ salt32 ++ initCodeHash32)[12..32] */
export function create2Address(deployer20: Uint8Array, salt32: Uint8Array, initCodeHash32: Uint8Array, prefix = TVM_CREATE2_PREFIX): Uint8Array;

/** EIP-1167 creation code for `implementation20` (55 bytes). Must stay byte-identical to the factory's _cloneCode. */
export function cloneInitCode(implementation20: Uint8Array): Uint8Array;
export function cloneCodeHash(implementation20: Uint8Array): Uint8Array;

/** keccak256(abi.encode(destination, salt)): 12 zero bytes ++ destination20 ++ salt32 */
export function forwarderCreate2Salt(destination20: Uint8Array, salt32: Uint8Array): Uint8Array;

export interface ForwarderParams {
  factory: string;        // T...
  cloneCodeHash: string;  // 0x + 64 hex, from forwarder_factories
  destination: string;    // T...
  salt: string;           // 0x + 64 hex
}
/** The deposit address (T...) for an invoice. Pure, no network. */
export function forwarderAddress(p: ForwarderParams, prefix = TVM_CREATE2_PREFIX): string;

/**
 * 0x + 64 hex: keccak256(utf8("TronGate forwarder salt v1:" + invoiceId)).
 * Deterministic and public on purpose (D4): an invoice id is enough to find and flush its address without the database.
 */
export function forwarderSaltForInvoice(invoiceId: string): string;

Hashing uses keccak_256 from @noble/hashes/sha3. All inputs are length-checked and throw on anything else.

2.3 Test vectors (test/create2.test.ts)

Five independent layers, all offline (every value below was recomputed during the review with @noble/hashes):

  1. EIP-1014 official vectors with prefix = 0xff prove the function shape: (0x00…00, 0x00…00, 0x00) → 0x4D1A2e2bB4F88F0250f26Ffff098B0b30B26BF38, (0xdeadbeef00…00, 0, 0x00) → 0xB928f69Bb1D91Cd65274e3c79d8986362984fDA3, (0x00…00deadbeef, 0x00…00cafebabe, 0xdeadbeef) → 0x60f3f640a8508fC6a86d45DF051962668E1e8AC7, (0, 0, empty) → 0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0.

  2. Hand-computed TVM vectors (computed with a separate pure-Python Keccak, not with @noble):

    deployer20 salt initCode address20 base58
    00…00 00…00 00 65a4f4773d93d98362d0dc131dd51ada88c34f7f TKEerhofQTEicnAHg9HWdsMzm1mA6dBDwM
    deadbeef00…00 00…00 00 29a2574c282a56ab6d8e12c922a0d63625a243ef TDmMBaJ8s3pjwH6voNuYDQVMhgQNsMgaL6
    00…00deadbeef 00…00cafebabe deadbeef ece484536af6315b7af4b9f5ad31eb684e1b3aa4 TXZnDxq7amkCpeghQYbqj74vba2nTktxRV
    00…00 00…00 (empty) fb3a2d661eb5d8b080361a50803c425352242465 TYsaJSXG8yHSd7V1NaGYQmLjsPyG4VoDhM
  3. A real mainnet contract (Verified against TronGrid on 2026-12-05). The SunSwap V2 USDT/WTRX pair is created with CREATE2, and the 0x41 formula reproduces its address:

    factory     TKWJdrQkqHisa1X8HUdHEfREvTzw4pMAaY   (689abaeeed3f0bb3585773192e23224cac25dd41)
    token0      891cdb91d149f23b1a45d9c5ca78a88d0cb44c18   (WTRX, TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR)
    token1      a614f803b6fd780986a42c78ec9c7f77e6ded13c   (USDT, TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t)
    salt        keccak256(token0 ++ token1) = a3180ab4660d65d7ba55bb4d985a145099e89c1e70c28311c89054447e3c4aee
    codeHash    6d3f89421f83e4b62e628de8fc7ff2b014a79bf8fd8e8b0ea46e4a1d9409b67d
    pair        3a10321a4e97a64d9376af42ec07d5fa50294b35   (TFGDbUyP8xez44C76fin3bn3Ss6jugoUwJ)

    The test asserts create2Address(factory, salt, codeHash) == pair and that the 0xff prefix does not match.

  4. Forwarder vectors (hand-computed, placeholder addresses):

    factory        TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
    implementation TG3XXyExBkPp9nzdajDZsozEu4BkaSJozs   (42a1e39aefa49290f2b3f9ed688d7cecf86cd6e0)
    destination    TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf   (eca9bc828a3005b9a3b909f2cc5c2a54794de05f)
    cloneInitCode  3d602d80600a3d3981f3363d3d373d3d3d363d7342a1e39aefa49290f2b3f9ed688d7cecf86cd6e05af43d82803e903d91602b57fd5bf3
    cloneCodeHash  739a5a69a0731e55054c9def8ef3447fa6af82cd86d8e14e0afc4199ed203a80
    salt 0x00…01   create2Salt bb4917527175d79adc10f5ad0bdde214064235a7bc323416c96384b149071487  → TYxsZkcLMXpVdEsJfrdXZUc1MPWBxWG8rJ
    salt 0xab…ab   create2Salt e25816637dda9e8cac6aa6d56e8b14892bbe69e1a97b1e8d9b7006c2fd51d2f1  → TFoBfPJV98xmcv5nJegNxPayRoZtSg4R1T

    Vectors with leading zero bytes (same factory and implementation). They catch the classic bug of losing leading zeros in a hex or BigInt conversion, which would produce addresses that can never be flushed:

    destination with leading zeros   T9yD14Nj9j7xAB4dbGeiX9h8unkp2kApxw (00…00ff), salt 0x00…02
                                     create2Salt 16ed800b3553d170d9b9afe6d01a73447a37318a016996524f15d95a2ceafbc3 → TYBKytF5kG87FHyUoVps5Yv4XvHtQ8wPmy
    address with a leading zero      destination TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf, salt 0x00…3e
                                     address20 006e33265feb5b7ec26c96d3236b1703d6ef048b → TA1V1sjtcBtQKX8GP2R7V12HppVkMTnK6K
  5. Salt derivation (section 2.2):

    forwarderSaltForInvoice("inv_0000000000000000000000") = 081f687806b7d82a03000de41bf1cda7c870aedd113f3479fc1c8c0ff82f5109
    with the factory, implementation and destination of layer 4:
    create2Salt b6464dd5ca6fc74d5dfcb166102b627d28b098de683ff0075fc091086e9b87be → TVH4Ax5pjcVd8twezNGtv6Xy4c3iBq7AD9

Key vectors for addressFromPrivateKey: key 0x00…01 → TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC (7e5f4552091a69125d5dfcb7b8c2659029395bdf); key 0x0123456789abcdef repeated four times → TZ1EafTG8FRtE6ef3H2dhaucDdjv36fzPY.

The contract test (section 9.2) closes the loop: on the EVM, factory.forwarderAddress() equals the TypeScript derivation with prefix 0xff, and factory.forwarderAddressWithPrefix(0x41, …) equals it with prefix 0x41. On a real TVM the factory constructor and verifyFactory (section 5.4) check the same thing against the chain.

3. TRON transaction signer and broadcaster

Four small modules. None of them is imported by the watcher's read path.

3.1 src/tron/abi.ts

Only what the factory needs: selector(signature), encodeAddress, encodeBytes32, encodeUint, encodeAddressArray (head offset, length, items), decodeUint, decodeUintArray, decodeAddress, decodeRevertReason (08c379a0 + ABI string, otherwise undefined). Addresses are encoded as 12 zero bytes plus the 20-byte form (never the 0x41 prefix).

3.2 src/tron/rpc.ts: TronRpc

export class TronRpcError extends Error {
  constructor(message: string, readonly code: string, readonly retryable: boolean) { super(message); }
}

export interface UnsignedTx { txID: string; raw_data_hex: string; raw_data: unknown; visible: true }
export interface SignedTx extends UnsignedTx { signature: string[] }

export interface TxInfo {
  blockNumber: number; blockTimestamp: number; feeSun: number; energyUsed: number;
  result: "SUCCESS" | string;                 // receipt.result, e.g. REVERT, OUT_OF_ENERGY
  revertReason?: string;                      // decoded from contractResult[0] or resMessage
  logs: { address: string; topics: string[]; data: string }[];
}

export class TronRpc {
  constructor(baseUrl: string, opts?: { apiKey?: string; fetch?: typeof fetch; timeoutMs?: number; minIntervalMs?: number });

  /** /wallet/triggerconstantcontract, or /walletsolidity/… when solid. Never throws for a revert. */
  callConstant(p: { owner: string; contract: string; selector: string; parameter: string; solid?: boolean }):
    Promise<{ ok: boolean; result: string; energyUsed: number; revertReason?: string }>;
  /** /wallet/triggersmartcontract with call_value 0. */
  buildTrigger(p: { owner: string; contract: string; selector: string; parameter: string; feeLimitSun: number }): Promise<UnsignedTx>;
  /** /wallet/deploycontract. */
  buildDeploy(p: { owner: string; bytecode: string; abi: string; name: string; feeLimitSun: number }): Promise<UnsignedTx & { contract_address: string }>;
  /** /wallet/broadcasttransaction. Resolves when the node accepted it; throws TronRpcError otherwise. */
  broadcast(tx: SignedTx): Promise<void>;
  /** /walletsolidity/gettransactioninfobyid (solid) or /wallet/…; undefined when the node answers {}. */
  transactionInfo(txId: string, solid: boolean): Promise<TxInfo | undefined>;
  account(address: string): Promise<{ exists: boolean; balanceSun: number }>;          // {} => exists: false
  accountResource(address: string): Promise<{ energyAvailable: number; bandwidthAvailable: number }>;
  contractInfo(address: string): Promise<{ runtimeCode: string } | undefined>;         // /wallet/getcontractinfo
  energyPriceSun(): Promise<number>;                                                    // getchainparameters.getEnergyFee, cached 10 min
}

Rules:

3.3 src/tron/tx.ts: decode and verify before signing

A 40-line protobuf reader (varint and length-delimited fields only; any other wire type throws) decodes raw_data_hex. Layout (Verified on real TronGrid output): Transaction.raw fields 1 ref_block_bytes, 4 ref_block_hash, 8 expiration, 11 contract, 14 timestamp, 18 fee_limit. contract = { 1 type, 2 parameter: Any { 1 type_url, 2 value } }. TriggerSmartContract value = { 1 owner_address (21 bytes), 2 contract_address (21 bytes), 3 call_value, 4 data, 5 call_token_value, 6 token_id }. CreateSmartContract value = { 1 owner_address, 2 new_contract { 1 origin_address, 3 abi, 4 bytecode, 5 call_value, 6 consume_user_resource_percent, 7 name, 8 origin_energy_limit } }.

declare const verified: unique symbol;
/** Only tx.ts can make one. The signer accepts nothing else. */
export type VerifiedTx = UnsignedTx & { readonly [verified]: true; readonly expiration: number };

export class TxVerificationError extends Error {}

export function verifyTriggerTx(tx: UnsignedTx, expect: {
  owner: string;            // fee payer
  contract: string;         // a factory from forwarder_factories
  data: Uint8Array;         // selector + arguments we asked for
  feeLimitSun: number;
  maxFeeLimitSun: number;   // config.forwarder.sweepFeeLimitSun
  now: number;
}): VerifiedTx;

export function verifyDeployTx(tx: UnsignedTx & { contract_address: string }, expect: {
  owner: string; bytecode: Uint8Array; feeLimitSun: number; now: number;
}): VerifiedTx & { contractAddress: string };

verifyTriggerTx does not rely on its parser understanding everything a node could put into a transaction. It rebuilds the transaction from our own expectation and compares bytes. It throws unless all of these hold:

  1. sha256(raw_data_hex) === txID (hex, case-insensitive).
  2. Decode raw_data_hex strictly (rules below) and take exactly four values from it: ref_block_bytes (2 bytes), ref_block_hash (8 bytes), expiration and timestamp. Nothing else from the node is used.
  3. Encode a fresh Transaction.raw from those four values plus what we asked for: one contract of type = 31 with the TriggerSmartContract type URL, owner_address = 0x41 ++ expect.owner, contract_address = 0x41 ++ expect.contract, data = expect.data, fee_limit = expect.feeLimitSun, and no other field. Fields are written in field-number order and zero values are omitted, which is how java-tron serializes. The result must equal raw_data_hex byte for byte. A memo, a second contract, call_value, call_token_value, token_id, Permission_id, a repeated or unknown field or a non-canonical encoding all change the bytes, whether or not the verifier knows about them.
  4. expect.data starts with the selector of flush, flushTRX, flushMany or deploy, and expect.contract is a row of forwarder_factories for this network.
  5. expect.feeLimitSun is an integer with 0 < feeLimitSun <= expect.maxFeeLimitSun.
  6. timestamp <= expiration, expiration − timestamp <= 15 min and expiration <= expect.now + 15 min. There is no lower bound against the server clock: signing an already expired transaction is harmless (it can never land), and a skewed clock must not silently stop every sweep.

Strict decoding: varints are decoded with BigInt and may be at most 10 bytes long (never with 32-bit bit operators: a fee_limit of 2^32 + x must not read as x); only wire types 0 and 2 exist; every message at every nesting level accepts only its known field numbers, each at most once; lengths must not run past the buffer and no bytes may be left over. A test re-encodes the fixture below and gets the identical hex (Verified during the review with a 20-line encoder: canonical field order with zero values omitted reproduces the fixture exactly).

verifyDeployTx checks 1 and 6, a fee limit that equals the CLI's and is at most 2,000 TRX, and uses the same strict decoder (the node encodes the ABI, so rebuilding the bytes is not practical for a deployment; unknown and repeated fields are still rejected at every level). It also requires: one contract of type === 30 with the CreateSmartContract type URL, owner_address and new_contract.origin_address equal the fee payer, new_contract.bytecode equals the artifact's factory creation code, call_value, call_token_value and token_id absent or zero, consume_user_resource_percent === 100 (callers pay for their own calls, the deployer's energy can never be spent by strangers), origin_energy_limit equal to what we asked, and the returned contract_address equals 0x41 ++ keccak256(txID ++ 0x41 ++ owner20)[12..32] (Verified: this formula reproduces TronGrid's contract_address).

The VerifiedTx brand is a compile-time guard only. tx.ts therefore also keeps a module-private WeakSet of the objects it verified and exports isVerifiedTx(tx); the signer checks it at run time (3.4).

The node rebuilds the transaction from the JSON raw_data when broadcasting. If that JSON differed from the hex we verified, our signature would not match and the node would answer SIGERROR. The signature therefore commits to exactly the bytes we checked.

Test fixture (Verified, a real unsigned transaction built by Nile TronGrid; it was never signed with a funded key or broadcast): owner TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC (private key 0x00…01), contract TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf, fee_limit 50000000, expiration 1796464812000, timestamp 1796464753603.

raw_data_hex
0a028fd82208f763f8ba9621b80140e0bf96ada4345acf01081f12ca010a31747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e54726967676572536d617274436f6e74726163741294010a15417e5f4552091a69125d5dfcb7b8c2659029395bdf121541eca9bc828a3005b9a3b909f2cc5c2a54794de05f22643ce3efa9000000000000000000000000eca9bc828a3005b9a3b909f2cc5c2a54794de05fabababababababababababababababababababababababababababababababab000000000000000000000000eca9bc828a3005b9a3b909f2cc5c2a54794de05f70c3f792ada434900180e1eb17
txID
ff669a50e7db71857638b4436c25b39ca422cf1c187e8080871471e17a22f583
signature with key 0x00…01 (r ++ s ++ recovery id)
32333bbfe84cac887a8c29abbc0774bd05f6d4fe3789676addbe25e4f9b2c03f2bd671992fbdd9a1440a589a4624e5db00c797390729ccfdad90661cd80f6cbf00

JSON raw_data of the same fixture, for the fake fetch:

{"ref_block_bytes":"8fd8","ref_block_hash":"f763f8ba9621b801","expiration":1796464812000,"contract":[{"parameter":{"value":{"owner_address":"TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC","contract_address":"TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf","data":"3ce3efa9000000000000000000000000eca9bc828a3005b9a3b909f2cc5c2a54794de05fabababababababababababababababababababababababababababababababab000000000000000000000000eca9bc828a3005b9a3b909f2cc5c2a54794de05f"},"type_url":"type.googleapis.com/protocol.TriggerSmartContract"},"type":"TriggerSmartContract"}],"timestamp":1796464753603,"fee_limit":50000000}

3.4 src/tron/signer.ts: TronSigner

export class TronSigner {
  constructor(privateKey: Uint8Array);   // 32 bytes, 0 < key < n, otherwise throws
  readonly address: string;              // T...
  /** Signs sha256(raw_data), i.e. the txID. Returns the transaction with one 65-byte signature. */
  sign(tx: VerifiedTx): SignedTx;
}

3.5 src/tron/forwarder-chain.ts: the port the app uses

The watcher and sweeper never see protobuf or HTTP. They use this interface. TronForwarderChain implements it with TronRpc + TronSigner + the artifact. FakeChain implements it in tests.

export type Asset = { kind: "token"; contract: string } | { kind: "trx" };

export interface FlushRequest {
  network: Network;
  factory: string;       // invoice.forwarder_factory
  destination: string;   // invoice.forwarder_destination
  salt: string;          // invoice.forwarder_salt
  asset: Asset;
}

export interface FlushEstimate { energy: number; feeSun: number; amount: bigint }
export interface PreparedFlush { txId: string; expiration: number; feeLimitSun: number; signed: SignedTx }

export type TxStatus =
  | { state: "pending" }                                                          // seen, not solidified yet
  | { state: "success"; moved: bigint; feeSun: number; energyUsed: number; blockTimestamp: number }
  | { state: "failed"; reason: string; feeSun: number }
  | { state: "unknown" };                                                         // no node knows it

export interface FeeWalletStatus {
  address: string; exists: boolean; balanceSun: number; energyAvailable: number;
  /** Balance of the network's payment token. Should be 0: the fee wallet is not a place to keep funds. */
  tokenBalance: bigint;
  level: "ok" | "low" | "empty";
}

export interface ForwarderChain {
  /** The fee payer's address, or undefined when no key is configured. */
  readonly feePayer?: string;
  /** Token balances through the factory lens, one constant call per call (callers chunk). */
  balances(q: { network: Network; factory: string; token: string; holders: string[]; solid: boolean }): Promise<bigint[]>;
  /** Dry run with the fee payer as caller. A revert is returned, not thrown. */
  estimateFlush(req: FlushRequest): Promise<({ ok: true } & FlushEstimate) | { ok: false; reason: string }>;
  /** Build, verify, sign. Nothing is sent. */
  prepareFlush(req: FlushRequest, feeLimitSun: number): Promise<PreparedFlush>;
  /** Send a prepared transaction. Throws TronRpcError; `retryable` means "fate unknown". */
  broadcast(network: Network, tx: PreparedFlush): Promise<void>;
  txStatus(network: Network, txId: string, expect: { factory: string; forwarder: string; asset: Asset }): Promise<TxStatus>;
  /** Timestamp of the latest solidified block. Chain time, not the server clock (used to declare a transaction dead). */
  solidTime(network: Network): Promise<number>;
  feeWallet(network: Network): Promise<FeeWalletStatus>;                          // cached 30 s
  /** Checks the factory on-chain against the artifact (section 5.4). Throws FactoryVerificationError. */
  verifyFactory(network: Network, address: string): Promise<{ implementation: string; cloneCodeHash: string }>;
}

Details of TronForwarderChain:

4. Database: migration v5

Append to MIGRATIONS in src/db.ts (Verified: runs on a v4 database, existing rows get deposit_mode = 'amount', no foreign key breakage):

-- v5: forwarder deposit mode (a deposit address per invoice, swept to the project wallet).
ALTER TABLE projects ADD COLUMN deposit_mode TEXT NOT NULL DEFAULT 'amount' CHECK (deposit_mode IN ('amount','forwarder'));
ALTER TABLE projects ADD COLUMN forwarder_factory TEXT;

-- Factories whose on-chain code was verified against the committed artifact. Addresses are only ever derived from these.
CREATE TABLE forwarder_factories (
  network         TEXT NOT NULL,
  address         TEXT NOT NULL,
  implementation  TEXT NOT NULL,
  clone_code_hash TEXT NOT NULL,
  deploy_tx_id    TEXT,
  verified_at     INTEGER NOT NULL,
  PRIMARY KEY (network, address)
);

ALTER TABLE invoices ADD COLUMN deposit_mode TEXT NOT NULL DEFAULT 'amount' CHECK (deposit_mode IN ('amount','forwarder'));
ALTER TABLE invoices ADD COLUMN forwarder_factory TEXT;
ALTER TABLE invoices ADD COLUMN forwarder_salt TEXT;
ALTER TABLE invoices ADD COLUMN forwarder_destination TEXT;
ALTER TABLE invoices ADD COLUMN amount_received INTEGER NOT NULL DEFAULT 0;
ALTER TABLE invoices ADD COLUMN amount_detected INTEGER NOT NULL DEFAULT 0;
ALTER TABLE invoices ADD COLUMN deposit_balance INTEGER NOT NULL DEFAULT 0;
ALTER TABLE invoices ADD COLUMN deposit_changed_at INTEGER;
ALTER TABLE invoices ADD COLUMN deposit_scanned_at INTEGER;
ALTER TABLE invoices ADD COLUMN deposit_cursor INTEGER;
ALTER TABLE invoices ADD COLUMN sweep_status TEXT CHECK (sweep_status IN ('queued','broadcast','swept','failed','skipped'));
ALTER TABLE invoices ADD COLUMN sweep_tx_id TEXT;
ALTER TABLE invoices ADD COLUMN sweep_attempts INTEGER NOT NULL DEFAULT 0;
ALTER TABLE invoices ADD COLUMN sweep_next_attempt_at INTEGER;
ALTER TABLE invoices ADD COLUMN sweep_error TEXT;
ALTER TABLE invoices ADD COLUMN amount_swept INTEGER NOT NULL DEFAULT 0;
ALTER TABLE invoices ADD COLUMN swept_at INTEGER;

-- A deposit address belongs to exactly one invoice.
CREATE UNIQUE INDEX idx_invoices_deposit ON invoices(network, pay_address) WHERE deposit_mode = 'forwarder';
CREATE INDEX idx_invoices_deposit_watch ON invoices(network, expires_at) WHERE deposit_mode = 'forwarder';
CREATE INDEX idx_invoices_sweep ON invoices(sweep_status, sweep_next_attempt_at) WHERE sweep_status IN ('queued','broadcast');

-- Every transaction the fee payer signed, for audit, fee accounting and crash recovery.
CREATE TABLE sweep_txs (
  tx_id           TEXT PRIMARY KEY,
  invoice_id      TEXT NOT NULL REFERENCES invoices(id),
  project_id      TEXT NOT NULL,
  network         TEXT NOT NULL,
  asset           TEXT NOT NULL,                       -- token contract (T...) or 'TRX'
  reason          TEXT NOT NULL CHECK (reason IN ('paid','stray','manual','recover')),
  status          TEXT NOT NULL CHECK (status IN ('signed','broadcast','success','failed','dropped')),
  amount_expected TEXT,                                -- base units as text (other tokens can exceed 2^53)
  amount_moved    TEXT,
  fee_limit_sun   INTEGER NOT NULL,
  expiration      INTEGER NOT NULL,
  energy_used     INTEGER,
  fee_sun         INTEGER,
  error           TEXT,
  created_at      INTEGER NOT NULL,
  resolved_at     INTEGER
);
CREATE INDEX idx_sweep_txs_invoice ON sweep_txs(invoice_id, created_at);
-- At most one open transaction per deposit address and asset.
CREATE UNIQUE INDEX idx_sweep_txs_inflight ON sweep_txs(invoice_id, asset) WHERE status IN ('signed','broadcast');

Column meanings:

Column Meaning
projects.deposit_mode Mode for new invoices. Each invoice keeps its own copy.
projects.forwarder_factory Factory used for new invoices. Set when the mode is enabled.
invoices.pay_address Amount mode: the wallet. Forwarder mode: the deposit address.
invoices.forwarder_factory / forwarder_salt / forwarder_destination Snapshot taken at creation. Sweeps use only these, never the project's current wallet or factory. forwarder_salt is 0x + 64 hex and always equals forwarderSaltForInvoice(id).
invoices.amount_received Confirmed total sent to the deposit address (base units).
invoices.amount_detected Same, including unconfirmed transfers.
invoices.deposit_balance Last head-state balance the lens reported (change detection only).
invoices.deposit_changed_at When the lens last saw a change, or a sweep resolved. Drives the hot scan window.
invoices.deposit_scanned_at Last complete, successful transfer-history scan of the address.
invoices.deposit_cursor Block timestamp up to which confirmed transfers to the address have been read. Scans resume from here (minus the usual overlap), so a history longer than one fetch is read over several ticks instead of being cut off.
invoices.sweep_status NULL nothing to sweep, queued, broadcast, swept, failed (needs a human), skipped (held at the address: below the automatic sweep minimum of 7.1).
invoices.amount_swept Confirmed total flushed to the wallet. amount_received - amount_swept is what is still at the address. The sweeper corrects it when someone else flushed the address (7.3).

InvoiceRow and ProjectRow gain these fields with matching types (deposit_mode: "amount" | "forwarder", nullable strings, numbers). amount_due equals amount_base in forwarder mode.

Existing queries that must add AND deposit_mode = 'amount': findMatch, allocateUniqueAmount, hasOpenInvoices, and the existing branch of walletsWithSettleableInvoices (which gains a second branch for forwarder destinations, section 6.3). assignTransfer refuses a forwarder invoice explicitly (invalid_state), instead of relying on the address comparison. With these filters an amount-mode project behaves exactly as before the migration: the existing tests stay untouched and green, and a test opens a v4 database file, migrates it and settles an old invoice.

5. Configuration, factories and the CLI

5.1 Environment (src/config.ts, .env.example)

Variable Default Meaning
FEE_PAYER_PRIVATE_KEY 64 hex characters. The fee payer's key.
FEE_PAYER_PRIVATE_KEY_FILE Path to a file holding the key (Docker or Kubernetes secret). Set one of the two, not both.
FORWARDER_FACTORY_MAINNET / _NILE / _SHASTA built-in address once we publish one, otherwise unset Factory per network.
SWEEP_FEE_LIMIT_TRX 50 Hard cap per sweep transaction (1 to 1000).
SWEEP_MIN_AMOUNT 1 Token units. The smallest balance that is ever swept without an admin's force, and the minimum invoice amount in forwarder mode. A sweep costs about 11 to 13 TRX: do not set this far below that value.
SWEEP_STRAY_MIN_AMOUNT 10 Token units. Balances that did not pay an invoice (partial, late, extra, a reused address) are swept automatically only from this amount. Below it they stay at their address until Sweep now. Must be at least SWEEP_MIN_AMOUNT.
SWEEP_PROJECT_DAILY_BUDGET_TRX 1000 Rolling 24 h cap on what the sweeps of one project may cost the fee wallet. When it is reached that project's sweeps wait (the funds stay safe at their addresses) and the dashboard says so. 0 disables the cap.
FORWARDER_MAX_OPEN_INVOICES 2000 Per project. Creating another forwarder invoice while this many are pending or confirming answers 503 too_many_open_invoices.
FEE_WALLET_MIN_TRX 100 Below this the dashboard and logs warn.
DEPOSIT_MODE amount Single-store (env-managed) project only: amount or forwarder.

Config additions:

export interface NetworkInfo { /* existing */ forwarderFactory?: string }

export interface ForwarderConfig {
  /** Present when a key is configured. The key is behind a function so JSON.stringify(config) cannot leak it. */
  feePayer?: { address: string; privateKey(): Uint8Array };
  sweepFeeLimitSun: number;     // parseAmount(SWEEP_FEE_LIMIT_TRX, 6)
  sweepMinAmount: string;       // decimal string, parsed per network with the token's decimals
  sweepStrayMinAmount: string;  // same; validated >= sweepMinAmount
  projectDailyBudgetSun: number; // parseAmount(SWEEP_PROJECT_DAILY_BUDGET_TRX, 6); 0 = no cap
  maxOpenInvoices: number;
  feeWalletMinSun: number;      // parseAmount(FEE_WALLET_MIN_TRX, 6)
}
export interface Config { /* existing */ forwarder: ForwarderConfig }
export interface LegacyProjectConfig { /* existing */ depositMode: "amount" | "forwarder" }

TRX amounts are integer sun (1 TRX = 1,000,000 sun), parsed with parseAmount(value, 6). No floats.

Validation (superRefine): the key is 64 hex characters and a valid scalar; FEE_PAYER_PRIVATE_KEY and _FILE are mutually exclusive; factory values are valid TRON addresses; SWEEP_STRAY_MIN_AMOUNT is at least SWEEP_MIN_AMOUNT; DEPOSIT_MODE=forwarder requires a key and a factory for NETWORK. The key is never logged, never returned by any route, and never passed to the fee wallet card (only the address is). NETWORKS in config.ts gets an optional forwarderFactory per network: unset for all three until the Nile deployment, then Nile's canonical address, mainnet's only after the review. Env overrides the built-in value.

5.2 src/forwarders.ts: ForwarderService

Owns the forwarder_factories table and the checks around enabling the mode.

export interface FactoryRow { network: Network; address: string; implementation: string; clone_code_hash: string; deploy_tx_id: string | null; verified_at: number }
export interface Requirement { id: "fee_payer" | "factory_configured" | "factory_verified" | "fee_wallet" | "destination" | "token"; ok: boolean; message: string }

export class ForwarderService {
  constructor(db: DB, config: Config, chain: ForwarderChain | undefined, log: Logger, now?: () => number);
  /** Sync, DB only. Used by invoice creation. */
  factory(network: Network, address: string): FactoryRow | undefined;
  /** Verifies on-chain and stores the row. Idempotent. */
  register(network: Network, address: string, deployTxId?: string): Promise<FactoryRow>;
  /** Registers every configured factory that is not in the table yet. Called at startup (not awaited) and by the sweeper every 5 minutes while one is missing. */
  refresh(): Promise<void>;
  /** The checklist shown next to the toggle. */
  requirements(project: ProjectRow): Promise<{ ok: boolean; factory?: string; checks: Requirement[] }>;
  /** Allocates the deposit address for a new invoice. Sync, DB only. Throws InvoiceError(503, "forwarder_unavailable"). */
  allocate(project: ProjectRow, invoiceId: string): { payAddress: string; factory: string; salt: string; destination: string };
}

Requirements, in order:

  1. fee_payer: a key is configured.
  2. factory_configured: config.networks[project.network].forwarderFactory is set.
  3. factory_verified: the factory is in forwarder_factories, or register succeeds now.
  4. fee_wallet: the fee wallet exists on this network and its level is not empty (a low level passes with a warning text). A fee wallet that holds the payment token also passes with a warning: "move these funds out, this wallet's key is on the server".
  5. destination: the project wallet is not the fee payer, the factory, the logic contract, the token contract or a deposit address of this gateway. In addition the on-chain forwarderAddress(wallet, probeSalt) (solidity node) must equal the local derivation for this exact wallet, which catches an encoding bug that only shows for particular address bytes before any customer is shown an address.
  6. token: the lens returns a balance for the project wallet. The lens reverts when the token does not answer balanceOf, so this proves TOKEN_CONTRACT is a working token contract on this network.

Next to the checklist the card shows one fixed notice that is not a check, because the server cannot test it: "Use a wallet you control. Sweeps are sent by a contract, and some exchanges do not credit deposits that come from contracts."

5.3 Deploying the factory

npm run admin -- deploy-factory --network nile [--fee-limit-trx 500] [--force]:

  1. Require a configured fee payer. Print its address and balance. Refuse when a factory is already configured for the network unless --force.
  2. rpc.buildDeploy with the artifact's factory bytecode and ABI, name TronGateForwarderFactory, consume_user_resource_percent: 100, origin_energy_limit: 10_000_000, call_value: 0, the fee limit.
  3. verifyDeployTx (section 3.3), sign, broadcast.
  4. Poll transactionInfo(txId, solid = true) for up to 3 minutes. Require SUCCESS.
  5. ForwarderService.register(network, contractAddress, txId), which runs the on-chain verification below.
  6. Print the address, the energy and fee used, and the line to add to the environment: FORWARDER_FACTORY_NILE=T….

The factory is ownerless, so whoever deploys it gains nothing. Once a canonical address is committed to config.ts operators do not need this command at all.

5.4 On-chain factory verification (verifyFactory)

A wrong factory address is the one mistake that can strand funds, so no address is ever derived from an unverified factory. Every call of this check goes to the solidity node (solid: true): a factory is accepted only once its deployment is final, because a factory lost in a reorg would get a different address when redeployed. All of these must hold:

  1. contractInfo(factory).runtimeCode equals the artifact's factory deployedBytecode once the immutableRanges are zeroed in both. Verify on Nile that runtimecode is byte-identical to solc's runtime code.
  2. implementation() returns an address whose runtime code equals the artifact's forwarder runtime the same way, and the forwarder's immutable word is this factory's address.
  3. create2Prefix() is 0x41.
  4. cloneCodeHash() equals keccak256(cloneInitCode(implementation)) computed locally.
  5. For two random (destination, salt) pairs and for one pair with leading zero bytes in both values, forwarderAddress() on-chain equals forwarderAddress() in src/tron/create2.ts.
  6. Every code reference of every immutable holds the expected word (implementation, the local cloneCodeHash, 0x41 left-aligned), and the forwarder's factory references all hold this factory. The getters read one copy each; deploy() reads another.
  7. Dry runs (constant calls, nothing is sent) of deploy(probe) return the locally derived address and of flushTRX(probe) succeed and return 0.

This check trusts the node it asks, like every read in the gateway (T4). A node that lies here could make the gateway hand out addresses that cannot be flushed, so: the canonical factory entries committed to config.ts carry their implementation address as well, and register refuses a built-in factory whose on-chain answer differs from the committed constants. Operators who deploy their own factory on mainnet should look at it once on Tronscan before enabling a project.

5.5 Other CLI commands (src/cli.ts)

Command What it does
fee-wallet new Generates a key locally (secp256k1.utils.randomPrivateKey()), prints the key once and the address, and explains where to put it and how much TRX to send. Nothing is stored.
fee-wallet Address, and per network: balance, staked energy, level.
verify-factory --network <n> [address] Runs 5.4 and registers the factory.
sweep <invoice> [--trx | --token <T…>] [--force] One sweep, synchronously: preflight, send, wait for confirmation, print the transaction link. --force ignores the sweep minimums. The CLI is the operator, so it is exempt from the daily budget; it still never sends a flush whose dry run moves nothing.
forwarders [--project <id>] [--unswept] CSV of invoice, address, factory, destination, salt, received, swept, status. A convenience export of what is still at deposit addresses.
recover-forwarder --network <n> --factory <T…> --destination <T…> --invoice <inv_…> [--token <T…> | --trx] [--send] Works without the database. Derives the salt from the invoice id and the address from the arguments, prints the address and its balance, and with --send flushes it using the fee payer. --invoices-file <path> takes one id per line. This is the disaster-recovery path: invoice ids are in the store's orders, in webhook logs and in checkout URLs.

The CLI gets a small flag parser (--name value, --flag). Its logic lives in ForwarderService and Sweeper so it is testable with a fake fetch; the CLI file only parses arguments and prints.

6. Invoices, matching and the watcher

6.1 Creating an invoice (InvoiceService.create)

InvoiceService takes the ForwarderService as a new constructor argument. Inside the existing transaction:

const id = newId("inv");
if (project.deposit_mode === "forwarder") {
  if (amountBase < minSweepBase) throw new InvoiceError(`Amount must be at least ${min} ${symbol} for this project.`, 400, "amount_too_small");
  if (this.openForwarderInvoices(project.id) >= this.config.forwarder.maxOpenInvoices)
    throw new InvoiceError("Too many open invoices for this project. Try again shortly.", 503, "too_many_open_invoices");
}
const forwarder = project.deposit_mode === "forwarder" ? this.forwarders.allocate(project, id) : undefined;
const amountDue = forwarder ? amountBase : this.allocateUniqueAmount(...);
// row.id = id, row.deposit_mode, row.pay_address = forwarder?.payAddress ?? project.merchant_address,
// row.forwarder_factory / forwarder_salt / forwarder_destination from `forwarder`

6.2 Matching rules

Any transfer of the invoice's token to its deposit address belongs to that invoice. There is no amount matching and no "unmatched" bucket in forwarder mode.

Definitions for an invoice: received = sum of confirmed transfers, detected = received plus unconfirmed transfers first seen less than 30 minutes ago (an unconfirmed transfer that never confirms stops counting, so the checkout does not keep showing money that is not coming), crossing = the first confirmed transfer (by block time) at which the running total reaches amount_due. Transfers with value 0 are ignored everywhere.

Situation Result
detected >= amount_due, not all confirmed yet, last transfer in time pending → confirming (invoice.confirming)
received >= amount_due and crossing.blockTimestamp <= expires_at → paid, tx_id/from_address from crossing, amount_paid = received. Works from pending, confirming and expired, like today. Exception: an expired invoice is not settled automatically when another invoice of the same project with the same order_ref is already paid. The order was re-issued and paid elsewhere, so this is a duplicate payment: it is attributed, shown as "duplicate", and left for the merchant to refund or Accept.
Partial payment (0 < received < amount_due) Stays pending. amount_received shows on the API, the dashboard and the checkout ("Received 40 of 50, send the remaining 10"). A top-up to the same address completes it.
Partial at expiry expired with amount_received > 0. The funds are swept to the wallet when they reach SWEEP_STRAY_MIN_AMOUNT, otherwise held at the address until Sweep now (7.1). The merchant can Accept (settle manually) or refund.
Completed after expires_at (late) Attributed, swept or held (7.1), not settled automatically. The invoice stays expired and shows "paid late". Accept settles it. Same contract with stores as today: a payment counts automatically only if it was sent before the deadline.
More than amount_due at settlement paid, amount_paid = received (so coversOrderTotal keeps working).
Another transfer after paid Attributed. amount_received > amount_paid marks the invoice "overpaid". The extra is swept or held (7.1).
Transfer of another token or TRX Not detected, never counts as payment. Recoverable with sweep --token / --trx. TRC-10 tokens are neither detected nor recoverable (1.5).

Accept is InvoiceService.acceptDeposit(projectId, id): forwarder invoices only, status pending, confirming or expired, amount_received > 0. It calls markPaid(id, lastConfirmedTransfer.tx_id, from, { amountPaid: amount_received, manual: true }). Like assignTransfer today it answers needs_confirmation unless force is set when the invoice is underpaid (amount_received < amount_due), was completed after expires_at, or has a paid sibling for the same order. Settling an invoice that the rules did not settle is always an explicit human decision. /transfers/:id/assign is unchanged and does not apply (forwarder transfers always have an invoice).

6.3 Watcher changes (src/watcher.ts)

PaymentWatcher gets the ForwarderChain and a callback onDepositChange(invoiceId) wired to the sweeper. The chain is always present in the running server, with or without a fee payer key (3.5); the constructor argument is optional only so that existing amount-mode tests can leave it out. One tick is now: poll wallets (both modes), poll deposits (new), expireOverdue().

Wallet polling changes.

Deposit polling: pollDeposits().

Step 1, pick the watch list from the DB by tier:

Tier Invoices Lens cadence
hot pending or confirming; or sweep_status IN ('queued','broadcast'); or deposit_changed_at within 10 min; or terminal (paid/expired) for less than 60 min every tick
warm terminal for less than 7 days every 5 minutes
cold created less than 180 days ago every 6 hours
archive everything older every 24 hours

lastWarmAt, lastColdAt and lastArchiveAt are kept in meta (watcher.deposits.warm, .cold, .archive). An address is never dropped from the watch list (D11): customers save addresses and pay them again months later, and funds nobody knows about are as good as locked. 100,000 old addresses cost 1,000 lens requests a day.

Step 2, group the list by (network, forwarder_factory, token_contract) and call chain.balances({ …, holders, solid: false }) in chunks of 100 addresses. One request per chunk. For each address whose balance differs from deposit_balance: store the new value and set deposit_changed_at = now.

A balance is only ever stored from a successful lens call. The lens reverts when the token does not answer (TG: balanceOf failed); a revert, a timeout or a node limit writes nothing for that chunk. The chunk is retried once at half size in the same tick, and if that fails too the tick counts as failed. The watcher must never turn "could not read" into "balance is 0".

Step 3, scan addresses that need it. A scan is the existing per-address TRC-20 history call (source.incomingTransfers). An address needs a scan when any of these is true:

Each scan reads confirmed transfers from deposit_cursor − 10 min (initially created_at − 120 s; the same cursor-and-overlap rule as pollWallet) and, for hot addresses, unconfirmed transfers of the last 30 minutes. When a page is incomplete (more transfers than one fetch returns), deposit_cursor moves to the newest transfer read and the address is scanned again on the next tick; otherwise it moves to the newest confirmed transfer seen. deposit_scanned_at = now is set only after a complete, successful scan. Someone who buries an address under thousands of dust transfers delays its scan by a few ticks and cannot hide a later payment. At most 40 scans per tick, least recently scanned first; the rest wait for the next tick (deposit scans never set catchingUp).

Step 4, processDeposit(invoice, transfer, confirmed) in one DB transaction:

  1. Drop the transfer if its value is 0 (nothing is stored).
  2. Upsert the transfer with invoice_id = invoice.id (same ON CONFLICT as today, same id scheme).
  3. Recompute received and detected from transfers (definitions in 6.2) and store them on the invoice.
  4. Apply the table in 6.2 (markConfirming, markPaid).
  5. Call onDepositChange(invoice.id) so the sweeper can queue a sweep.

Transfers are de-duplicated by id exactly as today, so re-reading an address is free of side effects.

Why the lens. TronGrid has no "transfers to any of these addresses" query, and polling every open address every 10 seconds does not fit a free API plan (100,000 requests a day). With the lens an idle address costs 1/100 of a request per tick, and only addresses that actually changed are scanned. The wallet poll adds 8,640 requests a day per wallet at a 10 s interval, exactly what amount mode costs today.

Open invoices Poll interval Lens requests per day Extra per payment
100 10 s 8,640 about 20 (scans until solidified)
500 10 s 43,200 about 20
2,000 20 s 86,400 about 20

Verified: TronGrid's per-address TRC-20 history returns transfers for addresses that were never activated (no TRX, getaccount answers {}), which is the normal state of a deposit address. Verify on Nile: the same for only_unconfirmed, and the lens with 100 holders.

Missed-flush safety. Salts are public (D4), so anyone can flush any deposit address at any time, at their own cost. Detection must not depend on a balance staying where it is, and it does not:

A stranger's flush therefore costs the stranger a sweep fee, saves the merchant one, and delays nothing beyond the confirmation time that settlement needs anyway.

health() keeps its fields and gains deposits_unreconciled (addresses whose balance the books have not explained for more than 30 minutes; informational, it does not change ok). A lens failure counts as a failed tick like a wallet failure.

7. Sweeper (src/sweeper.ts)

7.1 When to sweep

Sweeper.reconcile(invoiceId) is synchronous and DB-only. It runs after every deposit change, and on the invoice.paid and invoice.expired events.

if invoice.deposit_mode != 'forwarder'                        → return
if invoice.status not in ('paid','expired')                   → return      // an open invoice waits for its top-up
if invoice.sweep_status in ('queued','broadcast','failed')    → return      // failed waits for a human
outstanding = amount_received - amount_swept
if outstanding <= 0                                           → return
settlement = invoice.status == 'paid' and amount_swept == 0                 // the funds that paid the invoice
minimum    = settlement ? minSweep : max(minSweep, strayMin)
if outstanding < minimum                                      → sweep_status = 'skipped', sweep_error = "held at the deposit address (below the automatic sweep minimum)"
else  sweep_status = 'queued', sweep_attempts = 0, sweep_next_attempt_at = now, sweep_error = NULL

So: the funds that paid an invoice are swept as soon as it is confirmed paid. Everything else (partial at expiry, late, extra, a reused address) is swept automatically only from SWEEP_STRAY_MIN_AMOUNT; below that it is held at its address, shown in the dashboard, and swept when someone presses Sweep now. A partial payment on a still-open invoice waits for the top-up. Simulated payments have amount_received = 0 and are never queued.

Why two minimums. A sweep costs the fee wallet about 11 to 13 TRX. A paid invoice is backed by an order of at least SWEEP_MIN_AMOUNT at a price the merchant chose. A stray balance is backed by nothing: invoices can be created for free through any store's checkout, and if 1 USDT sent to an expired address triggered a sweep, an attacker would turn each dollar into several dollars of the merchant's TRX. With the stray minimum the merchant always receives more than the sweep costs, and nothing is lost by waiting: funds at a deposit address can only ever go to the wallet.

7.2 State machine (invoices.sweep_status)

NULL ──reconcile──▶ queued ──prepared + persisted──▶ broadcast ──confirmed SUCCESS──▶ swept
                      ▲  │                               │                              │
                      │  └─ preflight error ─▶ queued    ├─ confirmed failure ─▶ queued │ new funds
                      │     (attempts+1, backoff)        │   (attempts+1, backoff)      ▼
                      │                                  └─ expired, unknown ──▶ queued queued
   attempts == 10 ──▶ failed ──"Sweep now" / CLI──▶ queued (attempts = 0)
   outstanding below the automatic minimum ──▶ skipped ──"Sweep now"──▶ queued

Backoff after a counted failure: 30 s, 2 m, 10 m, 30 m, 1 h, 3 h, 6 h, 12 h, 24 h, then failed.

7.3 One tick

The sweeper has its own timer (max(pollIntervalMs, 10 s)), a running guard like the watcher, and is started and stopped from src/index.ts next to the watcher. Without a fee payer key it still runs step 1 and reports enabled: false.

Step 1, resolve open transactions (sweep_txs.status IN ('signed','broadcast')), using chain.txStatus:

Status Action
success sweep_txs: success, amount_moved, fee_sun, energy_used. For the invoice token: amount_swept += moved (if that exceeds amount_received, keep it and force a scan), swept_at = now, sweep_tx_id, deposit_changed_at = now (forces a history scan), sweep_status = 'swept', then reconcile (re-queues if more arrived). Emit invoice.swept.
failed sweep_txs: failed with the reason. Invoice: attempts + 1, backoff or failed, sweep_error.
pending Nothing.
unknown and solidTime > expiration + 60 s sweep_txs: dropped. Invoice: queued, attempts + 1, next attempt now. A transaction cannot be included after its expiration, and the comparison uses the chain's solidified time, not the server clock, so a lagging node or a skewed clock cannot declare a live transaction dead. dropped rows are looked up once more an hour later; one that landed after all is corrected to success or failed for the fee accounting.
unknown, solidified time not past the expiration Nothing (wait).

Step 2, send queued sweeps (sweep_status = 'queued' AND sweep_next_attempt_at <= now, oldest first, at most 5 per tick):

  1. No fee payer key: sweep_error = "FEE_PAYER_PRIVATE_KEY is not set", next attempt in 5 minutes, attempts unchanged.
  2. Read the solidified balance B of the address through the lens (solid: true). With outstanding = amount_received − amount_swept:
    • B == 0: the funds are gone, and the only place they can have gone is the destination (flush is permissionless). One reading is not enough to write that down. Set deposit_changed_at = now, retry in 15 s (attempts unchanged), and only when a complete history scan has run after that reading and B is still 0, and, while the newest confirmed transfer is less than 10 minutes old (a lagging solidity node reads exactly 0 for a fresh payment), a head-state lens reading is 0 as well: set amount_swept = amount_received, sweep_status = 'swept', swept_at = now, sweep_error = NULL, and emit invoice.swept with sweep.tx_id = null (it was not our transaction). No transaction is sent.
    • 0 < B < outstanding: either the last transfer is not solidified at this node yet, or someone else flushed part of what the books expect. Retry in 15 s, attempts unchanged, for at most 10 minutes after the invoice's newest confirmed transfer. After that the chain is right and the books are corrected: amount_swept = amount_received − B, and the sweep continues with B. Without this limit an address that a stranger flushed and a customer then paid again would stay queued forever.
    • B is below the applicable minimum of 7.1 and the sweep is not forced: skipped.
  3. chain.estimateFlush. A revert is a counted failure with its reason (for example TG: token did not move). An estimate with amount == 0 is never sent; handle it like B == 0. Flushing an empty, undeployed address would pay about 5 TRX to deploy a clone and move nothing.
  4. Compute the fee limit (section 3.5). Over the cap: counted failure, the error names the estimate and the cap.
  5. Daily budget. spent = over this project's sweep_txs created in the last 24 hours: fee_limit_sun of open rows (signed, broadcast) plus max(fee_sun, energy_used × energy price) of success and failed rows (dropped rows cost nothing; counting energy keeps the cap meaningful when the fee wallet uses staked energy). If spent + feeLimitSun > projectDailyBudgetSun: sweep_error = "daily sweep budget reached (X of Y TRX)", next attempt in 15 minutes, attempts unchanged. Sweeps started from the CLI are exempt.
  6. chain.feeWallet(network). If it cannot cover feeLimitSun plus 1 TRX of bandwidth: sweep_error = "fee wallet T… has X TRX, needs about Y", next attempt in 5 minutes, attempts unchanged (waiting for a top-up is not a failure).
  7. chain.prepareFlush. A TxVerificationError is a counted failure and is logged at error level with the mismatch: it means the node returned something we did not ask for.
  8. In one DB transaction: insert sweep_txs (status = 'signed', reason = paid when the invoice is paid and nothing was swept yet, else stray or manual) and set the invoice to broadcast with sweep_tx_id.
  9. chain.broadcast. Accepted: sweep_txs.status = 'broadcast'. retryable error: leave it signed, step 1 decides once the expiration passes. Non-retryable rejection: sweep_txs.status = 'failed', invoice back to queued as a counted failure.

A transaction that fails on-chain with OUT_OF_ENERGY has burned its whole fee limit. It is a counted failure, the next attempt re-estimates with a fresh fee limit, and the daily budget bounds the total.

A crash between 8 and 9 leaves a signed row that was never sent. Step 1 turns it into dropped after its expiration and the sweep is rebuilt. A crash after 9 is resolved by step 1 normally.

7.4 Double sweeps, and why they are harmless

At most one open transaction per invoice and asset is enforced by idx_sweep_txs_inflight. If two flushes ever ran anyway (a third party, the CLI and the server at once), the second moves 0, emits nothing and costs a few thousand energy, because by then the clone is deployed. Funds can only arrive at forwarder_destination. The expensive case, a flush of an address that is empty and undeployed, is excluded by step 3.

7.5 Manual sweeps and other assets

class Sweeper {
  start(): void; stop(): void; tick(): Promise<void>;
  reconcile(invoiceId: string): void;
  /** "Sweep now": re-queue the invoice token. `force` ignores the minimum. Returns the invoice. */
  sweepNow(projectId: string, invoiceId: string, opts?: { force?: boolean }): InvoiceRow;
  /** Recover TRX or another token from the deposit address. Sends one transaction and returns its id. */
  recover(invoiceId: string, asset: Asset): Promise<{ txId: string; amount: string }>;
  /** Used by the CLI: run one sweep and wait for the result. */
  sweepAndWait(invoiceId: string, opts?: { force?: boolean; asset?: Asset; timeoutMs?: number }): Promise<TxStatus & { txId?: string }>;
  health(): SweeperHealth;
}

sweepNow resets attempts and queues (it sends nothing when the balance is 0, see step 2). Without force it accepts a failed sweep or a held balance of at least SWEEP_MIN_AMOUNT: that is the merchant deciding the amount is worth the fee, and it stays subject to the daily budget. force (anything below SWEEP_MIN_AMOUNT) is accepted only from a dashboard admin or the CLI. The fee wallet belongs to the operator and may be shared by many projects; a project's member or API key must not be able to spend 12 TRX of it to move a cent. A manual or forced sweep is remembered in an in-memory Map of invoice id to "manual" or "forced" that step 2 consults and clears: manual lowers the minimum to SWEEP_MIN_AMOUNT (so a held stray balance can be moved), forced removes it. After a restart the button simply has to be pressed again. recover estimates first and refuses when the amount is 0, logs the transaction in sweep_txs with reason = 'recover', and does not touch sweep_status. recover is admin-only because an arbitrary token contract can burn energy up to the fee limit.

7.6 Fee wallet monitoring

SweeperHealth:

interface SweeperHealth {
  enabled: boolean;                   // a fee payer key is configured
  ok: boolean;                        // no failed sweeps, nothing queued for more than 30 min, no wallet 'empty'
  queued: number; in_flight: number; failed: number;
  held: number;                       // skipped: balances waiting below the automatic minimum
  budget_exhausted: string[];         // project ids whose daily budget is used up
  oldest_queued_at: string | null;
  last_error: string | null;
  fee_wallet: { address: string; networks: Partial<Record<Network, { balance_trx: string; energy_available: number; level: "ok" | "low" | "empty" }>> } | null;
}

Only networks with forwarder invoices are queried. A level change is logged once (warn for low, error for empty). /health gains a sweeper object but its HTTP status still depends on the watcher only: a stuck sweeper does not lose payments, and restarting the container would not fix it.

8. API, webhooks, dashboard, checkout

8.1 Invoice JSON (src/serialize.ts)

Added to invoiceToJson (authenticated API and webhooks):

{
  "deposit_mode": "forwarder",
  "amount_received": "50",
  "sweep": {
    "status": "swept",
    "tx_id": "…", "tx_url": "https://nile.tronscan.org/#/transaction/…",
    "amount_swept": "50", "swept_at": "2026-12-05T10:00:00.000Z",
    "attempts": 0, "error": null
  },
  "forwarder": { "factory": "T…", "destination": "T…", "salt": "0x…" }
}

Added to invoiceToPublicJson (checkout): deposit_mode, amount_received, amount_detected, amount_remaining (max(0, amount_due - amount_detected)). Not forwarder or sweep: the checkout has no use for them. (The salt is not a secret, see D4. Nothing may be built on the assumption that it is.)

projectToJson adds deposit_mode and forwarder_factory.

8.2 Routes

Project scope (src/routes/project-api.ts, so both /api/v1 and /dashboard/api/projects/:pid):

Method Path
POST /invoices/:id/accept Body { "force"?: boolean }. Settle a forwarder invoice manually with what it received (6.2). 409 needs_confirmation for an underpaid, late or duplicate payment without force; 409 invalid_state otherwise.
POST /invoices/:id/sweep Body { "force"?: boolean }. "Sweep now" for the invoice token. Returns the invoice. 409 in amount mode. force (below SWEEP_MIN_AMOUNT) is honoured only for a dashboard admin session; an API key or a member session gets 403 forbidden (7.5).
GET /invoices/:id/sweeps The invoice's sweep_txs (id, link, asset, reason, status, amounts, fee, error, times).

ListQuery gains sweep_status. The CSV export gains deposit_mode, pay_address, amount_received, sweep_status, sweep_tx_id. /transfers adds to_address to each row.

Dashboard (src/routes/dashboard.ts):

Method Path Who
GET /projects/:pid/forwarder members { deposit_mode, factory, requirements: { ok, checks } | null, fee_wallet: { address, level } | null, sweeps: { queued, in_flight, failed } }. ?requirements=0 answers from the database only (requirements: null). Own rate limit of 60 per minute.
PATCH /projects/:pid/settings admin for this field accepts deposit_mode. Add it to ADMIN_ONLY and ENV_MANAGED. Enabling runs requirements() and answers 409 forwarder_requirements with the failing checks; on success it stores deposit_mode and forwarder_factory.
GET /admin/forwarder admin { fee_payer: { configured, address }, networks: { <n>: { factory, verified, energy_price_sun, fee_wallet, sweeps, avg_fee_trx } } }
POST /admin/invoices/:id/recover admin Body { "asset": "trx" | "<token address>" }. Calls Sweeper.recover.

/me adds sweeper: sweeper.health() for admins, and for members sweeper.summaryFor(their projects) (counts and budget state of their own projects; no last error, no fee wallet balances, no other projects' ids). ProjectService.update accepts depositMode and forwarderFactory; changing network while in forwarder mode requires a factory for the new network, otherwise it throws. syncLegacyProject applies DEPOSIT_MODE and the configured factory.

8.3 Webhooks

SDK (sdk/src/index.ts): add the new Invoice fields and the event type. coversOrderTotal is unchanged.

8.4 Dashboard UI (src/views/admin.ts, public/admin.js, public/admin.css)

No inline scripts, every interpolated value through esc().

8.5 Checkout (src/views/checkout.ts, public/checkout.js, src/views/i18n.ts)

9. Test plan

Nothing in the test suite touches the network. npm test and npm run typecheck must pass.

9.1 test/helpers.ts: FakeChain extensions

FakeChain keeps implementing TransferSource and additionally implements ForwarderChain:

class FakeChain implements TransferSource, ForwarderChain {
  feePayer = "TMVQGm1qAQYVdetCeGRRkTWYYrLXuHK2HC";
  feeBalanceSun = 1_000_000_000;            // 1000 TRX
  sweepFeeSun = 12_000_000;                 // charged per mined sweep
  balanceCalls: { holders: number; solid: boolean }[] = [];
  estimateFailure?: string;                 // makes estimateFlush return ok: false
  broadcastError?: TronRpcError;            // makes broadcast throw
  dropBroadcasts = false;                   // accepted but never mined
  revertSweeps = false;                     // mined as failed
  invalidFactory = false;                   // verifyFactory throws
  lensFails = false;                        // balances() throws, like the reverting lens
  historyLagMs = 0;                         // incomingTransfers hides transfers newer than this (late indexing)
  chainTime?: number;                       // solidTime(); defaults to the test clock

  pay(invoice: { pay_address: string }, value: string, opts?: { at?: number; confirmed?: boolean; txId?: string }): RawTransfer;
  /** Executes broadcast sweeps: empties the address, records the transfer to the destination, charges the fee. */
  mineSweeps(): void;
  /** Someone else flushes the address (permissionless flush). */
  thirdPartyFlush(address: string): void;
  balanceOf(address: string, solid: boolean): bigint;   // confirmed (+ unconfirmed when !solid) in, minus flushed
}

Mined sweeps and thirdPartyFlush are also pushed into confirmed as a transfer from the deposit address to the destination wallet, so the flush-arrival rule of 6.3 is exercised (not matched, not unmatched, forces a scan). setup({ forwarder: true }) adds FEE_PAYER_PRIVATE_KEY (key 0x00…01), FORWARDER_FACTORY_NILE, DEPOSIT_MODE=forwarder, passes the fake as forwarderChain to buildApp, awaits forwarders.refresh(), and returns sweeper and forwarders. AppOptions gains forwarderChain?: ForwarderChain and rpcFetch?: typeof fetch.

9.2 test/contracts.test.ts (solc + @ethereumjs/evm, Hardfork.London)

Compiles contracts/ once in beforeAll (60 s timeout) with the fixed settings. Notes from the prototype: solc.compile(JSON.stringify(input)) with every source keyed by its path relative to contracts/ resolves the import "./TronGateForwarder.sol". For execution: createEVM({ common: new Common({ chain: Mainnet, hardfork: Hardfork.London }) }), deploy and call with evm.runCall({ caller, to?, data, value?, gasLimit }), read createdAddress and execResult.{ exceptionError, returnValue, executionGasUsed, logs }, fund accounts with evm.stateManager.putAccount(address, createAccount({ balance })). The TypeScript derivation is compared with the EVM by passing prefix = 0xff.

9.3 test/create2.test.ts

The five vector layers of section 2.3 (including the leading-zero vectors and the salt derivation), base58 round trips, the key vectors, and input validation (wrong lengths throw).

9.4 test/tron-tx.test.ts (fake fetch)

9.5 test/flow.test.ts: new describe("forwarder mode") blocks

Invoices and API:

Watcher:

Sweeper:

Dashboard (test/projects.test.ts): only admins can change deposit_mode; enabling with failing requirements answers 409 forwarder_requirements; /admin/forwarder never contains the private key; members can read /projects/:pid/forwarder; migration from a v4 database keeps old invoices in amount mode.

10. Docs, threat model, rollout

10.1 Documentation changes

10.2 Threat model

Assets: customer payments in flight (at deposit addresses), the merchant wallet, the fee wallet's TRX.

# Threat Outcome Why / mitigation
T1 Fee-payer key stolen The attacker can spend the fee wallet's TRX and call flush. No customer funds are lost or redirected. The key has no role in any contract. flush pays only the bound destination. Keep the balance small, rotate by setting a new key (no on-chain change needed).
T2 Server or database fully compromised Same as amount mode for new invoices (the attacker can show any address or lie about statuses). Funds already at deposit addresses still only move to the wallet they were created for. The destination is in the address. Stores fulfil on signed webhooks and can cross-check tx_id. Future work: an SDK helper that recomputes pay_address from forwarder and the store's own wallet.
T3 TronGrid lies or is intercepted while building a transaction The transaction is rejected locally and nothing is signed. verifyTriggerTx rebuilds the transaction from what we asked for and compares it byte for byte with what the node returned, so nothing we did not ask for can ride along (including a larger fee limit hidden behind a parser quirk). The signer accepts only objects that tx.ts verified, checked at run time.
T4 TronGrid lies about transfers or balances Wrong statuses, as today. No funds move wrongly. Unchanged trust assumption of the read path. Only solidified transfers settle invoices.
T5 Wrong factory address configured Would strand funds. Addresses are derived only from factories that passed verifyFactory (code comparison and live probes).
T6 Wrong CREATE2 formula Would strand funds. 0x41 confirmed against a real mainnet contract; hand-computed vectors; constructor probe; require(created == forwarder); on-chain versus off-chain probe; Nile soak.
T7 Dust or spam deposits to drain the fee wallet Bounded, and never profitable for the attacker. Only the funds that paid an invoice are swept from SWEEP_MIN_AMOUNT. Any other balance needs SWEEP_STRAY_MIN_AMOUNT (more than a sweep costs) or a deliberate Sweep now. No transaction is sent for amount == 0. Zero-value transfers are ignored. Per-transaction fee cap, per-project daily budget, at most 5 sweeps per tick.
T8 Third party flushes or deploys first, at any time (salts are public) None. The stranger pays the fee. Idempotent and destination-bound. The flush arrives at the wallet, the wallet poll forces a scan of the deposit address, the payment is settled from its confirmed transfer, and the sweeper records the address as swept.
T9 Reentrancy, malicious token passed to flush None. No storage. The forwarder only ever calls token.transfer(boundDestination, balance) and token.balanceOf(self).
T10 USDT freezes the deposit address or the wallet The flush reverts. Funds are frozen by the issuer, as they would be anywhere. Surfaced as a failed sweep with the reason.
T11 Database lost Recoverable. The salt is derived from the invoice id (D4). recover-forwarder needs only invoice ids (the store's orders, webhook logs, checkout URLs), the wallet and the factory, and contracts/README.md gives the formula for doing it by hand. Backups remain the fast path.
T12 Fee wallet empty Sweeps wait. Payments are still detected and safe. Dashboard card, logs, /health detail, sweeper.ok.
T13 Key leaks through logs or API The key is behind a function in config, a #private field in the signer, never serialised, and a test asserts it is absent from /admin/forwarder and from JSON.stringify.
T14 Replay of a signed transaction None. TRON transactions expire (about 60 s) and are bound to a recent block. A replayed flush would be harmless anyway.
T15 Customer sends the wrong asset Recoverable. flushTRX and flush with any token.
T16 Logic contract destroyed or upgraded Impossible. No SELFDESTRUCT, no DELEGATECALL, no owner, no proxy admin. A new version is a new factory address; old invoices keep theirs.
T17 TRX or TRC-10 dust sent to an address before its clone is deployed, to block the deployment None for the payment token. The TRX is recoverable, TRC-10 is not. java-tron allows CREATE2 onto an existing account that is not a contract and keeps its balance (source checked; Nile gate in 10.3). After deployment the network rejects plain TRX transfers to the contract.
T18 Checkout flood: thousands of invoices to exhaust the API quota and stall payment detection Bounded. FORWARDER_MAX_OPEN_INVOICES per project. An idle address costs 1/100 of a request per poll, and terminal addresses move to slower tiers.
T19 The lens fails or returns garbage Nothing is marked swept or paid on a bad reading. The lens reverts instead of returning 0. Balances are stored only from successful calls. "Swept by someone else" needs a solidified 0 and a complete history scan after it. Settlement never uses the lens, only confirmed transfers. A node that lies consistently is T4.
T20 A project member or API key spends the operator's fee wallet (multi-project server) Bounded per project per day. Enabling the mode, force and recover are admin-only. Daily budget per project. sweep_txs.project_id gives per-project fee accounting.
T21 A payment is indexed late, or an address is buried under dust transfers Found late, never lost. Addresses whose balance the books cannot explain are scanned without a time limit, each address has its own scan cursor, and deposits_unreconciled shows up in /health.
T22 One transfer credited twice: to a forwarder invoice and, when swept, to an amount-mode invoice on the same wallet None. A transfer whose sender is a deposit address is never matched or listed as unmatched. Tested.
T23 A duplicate payment for a re-issued order settles a second invoice Not automatic. An expired invoice with a paid sibling is not settled automatically. Accept needs force for underpaid, late and duplicate payments. Stores stay idempotent per order as before.
T24 The project wallet is an exchange address that does not credit transfers sent by contracts Possible loss outside the gateway's control. Fixed notice in the settings card, README and deploy skill: use a wallet you control.
T25 A customer pays an old deposit address again months later Found and shown. Addresses are never dropped from the watch list (archive tier).
T26 The fee key is also the key of a wallet that holds value Whatever that wallet holds is exposed. requirements() refuses a project wallet equal to the fee payer and warns when the fee wallet holds the payment token. Docs: a dedicated key, a small TRX float, nothing else.

What forwarder mode changes for the operator: the server now signs transactions and spends TRX. It still cannot take customer funds. It is honest to keep calling the gateway non-custodial, and the README must say exactly what the fee key can and cannot do.

10.3 Rollout

  1. Build (this branch): contracts, artifact, modules, migration, sweeper, UI, tests. Forwarder mode is off unless a project enables it, and cannot be enabled without a factory, so merging is safe for existing installs.
  2. Nile: create a fee wallet, fund it from the faucet, run deploy-factory --network nile, enable the mode on a test project. Acceptance checklist:
    • The factory deploys and create2Prefix() returns 0x41. Record energy and fee.
    • verifyFactory passes, including the exact runtimecode comparison.
    • Off-chain addresses equal forwarderAddress() for random salts.
    • A USDT payment to a counterfactual address is seen unconfirmed, then confirmed, and settles the invoice.
    • The lens works with 100 holders in one call.
    • Deploy + flush succeeds. Record energy, fee, and the Flushed log as it appears in gettransactioninfobyid.
    • A second payment to a deployed address is flushed. Record the cheaper cost.
    • TRX sent to an address before deployment is recovered with flushTRX.
    • Activation gate (must pass before any mainnet use): send TRX dust to one counterfactual address and a TRC-10 token to another, then send USDT to both and flush. Both deployments must succeed and the USDT must arrive.
    • A plain TRX transfer to a deployed clone is rejected by the network.
    • A flush sent by a wallet that is not the fee payer works, and the gateway follows it (settles, marks swept).
    • The TRC-20 history endpoint still returns incoming transfers for an address after its clone is deployed (the address is then a contract account).
    • The lens reverts for a token address without code, and the node reports that as a failed constant call.
    • Measure the lens energy and response time for 100 holders against the real USDT contract.
    • A deliberately low fee limit: record the OUT_OF_ENERGY shape. An unfunded fee wallet: record the broadcast error.
    • A dropped transaction is rebuilt after expiration.
    • Partial, late and over payments behave as in section 6.2.
    • Save the real responses as fixtures in test/fixtures/ and adjust TronRpc parsing if any shape differs.
  3. Publish Nile: commit the Nile factory address to NETWORKS.nile.forwarderFactory, update the README numbers.
  4. Mainnet: only after at least a week and 50 sweeps on Nile without manual intervention, and an independent review of the two contracts (about 150 lines). Deploy the factory, run verifyFactory, enable one project with small invoices, watch the fee wallet card. Then commit the mainnet address.

11. Contracts v2: each project pays its own sweep gas, in USDT

Status: implemented. This section replaces the parts of sections 1 to 10 it contradicts (the contract API, the salt scheme, the selectors, migration numbering). Everything else in those sections still holds, including the destination-binding argument of 1.6, which v2 keeps unchanged and extends to the fee.

11.1 What changes and why

In v1 the operator's fee wallet paid TRX for every sweep and got nothing back. In v2 a deposit address can carry a sweep fee: a fixed amount of the payment token that goes to the operator's fee collector wallet when the address is flushed. The fee wallet still pays the TRX; the collector receives USDT that makes up for it.

11.2 Contract API (v2)

TronGateForwarder (logic contract; every deposit address is an EIP-1167 clone of it):

address public immutable factory;
uint256 public feePaid;                         // clone storage, slot 0; 0 or the bound fee
receive() external payable;
function flushToken(address token, address destination, address collector, uint256 feeCap)
    external returns (uint256 amount, uint256 feeTaken);   // only the factory
function flushTRX(address payable destination) external returns (uint256 moved);   // only the factory

TronGateForwarderFactory (ownerless, no storage, every action permissionless):

uint256 public constant VERSION = 2;
address public immutable implementation;
bytes32 public immutable cloneCodeHash;
bytes1  public immutable create2Prefix;

function forwarderAddress(address destination, address collector, address feeToken, uint256 fee, bytes32 salt) view returns (address);
function forwarderAddressWithPrefix(bytes1 prefix, address destination, address collector, address feeToken, uint256 fee, bytes32 salt) view returns (address);
function isDeployed(address destination, address collector, address feeToken, uint256 fee, bytes32 salt) view returns (bool);
function balancesOf(address token, address[] holders) view returns (uint256[]);
function feesPaid(address[] forwarders) view returns (uint256[]);          // 0 for an address that is not deployed

function deploy(address destination, address collector, address feeToken, uint256 fee, bytes32 salt) returns (address);
function flush(address destination, address collector, address feeToken, uint256 fee, bytes32 salt, address token) returns (uint256 amount, uint256 feeTaken);
function flushTRX(address destination, address collector, address feeToken, uint256 fee, bytes32 salt) returns (uint256 amount);
function flushMany(address destination, address collector, address feeToken, uint256 fee, bytes32[] salts, address token) returns (uint256 total, uint256 totalFee);

event ForwarderDeployed(address indexed forwarder, address indexed destination, address indexed collector, address feeToken, uint256 fee, bytes32 salt);
event Flushed(address indexed forwarder, address indexed destination, address indexed token, uint256 amount, uint256 fee);

Selectors (asserted in test/contracts.test.ts): VERSION() ffa1ad74, deploy 1767d7ea, flush d8b21fe8, flushTRX 347aa805, flushMany 90360a26, forwarderAddress a186771b, forwarderAddressWithPrefix a24ca862, isDeployed a7077f8b, feesPaid(address[]) 3a28687d, balancesOf e098e844; forwarder feePaid() ac7c5780, flushToken(address,address,address,uint256) 08115d07, flushTRX(address) 48bbb1e5. Flushed topic b09c95c9…384d3a, ForwarderDeployed topic 320e9fd7…62577f. The signer's allow-list (ALLOWED_FACTORY_SELECTORS in src/tron/tx.ts) holds the four v2 actions only, so no v1 call can be signed.

The artifact carries a top-level version (2). src/tron/artifact.ts refuses an artifact whose version is not FORWARDER_VERSION in src/tron/create2.ts, and verifyFactory requires VERSION() == 2 on-chain.

11.3 Salt scheme

create2Salt   = keccak256(abi.encode(address destination, address collector, address feeToken, uint256 fee, bytes32 salt))
depositAddr20 = keccak256(0x41 ++ factory20 ++ create2Salt ++ cloneCodeHash)[12..32]

Five 32-byte words, addresses left-padded, the fee as a big-endian uint256. salt is unchanged: keccak256("TronGate forwarder salt v1:" ++ invoice_id). The clone code hash and the 0x41 prefix are unchanged.

Canonical terms. A fee-less address has collector = feeToken = address(0) and fee = 0. deploy (and so every flush) reverts with TG: bad fee terms unless fee == 0, collector == 0 and feeToken == 0 are all true or all false. forwarderAddress() in src/tron/create2.ts enforces the same rule (collector: null, feeToken: null, fee: 0n or all three set) and rejects a fee that is not a uint256 bigint. This gives one encoding per address: a "fee 0 to some collector" address cannot exist.

Changing any of the five values gives another address. That is the whole binding argument, as in 1.4 and 1.6: a caller who names another collector, a higher fee, another fee token or another destination is talking about a different, empty address.

Vectors are in test/create2.test.ts (derived with an independent implementation: another keccak library and hand-written base58check and ABI words) and are cross-checked against the Solidity factory for both prefixes in test/contracts.test.ts.

11.4 The fee cap invariant

For a deposit address with bound terms (destination, collector, feeToken, fee):

  1. Over the whole life of the address, the total of feeToken that leaves it for collector is 0 or exactly fee. Never more, whoever calls and however often.
  2. Every other base unit of every token, and all TRX, that leaves the address goes to destination.
  3. Nothing leaves it for any third address.

Why it holds:

11.5 Dust rule (balance not larger than the unpaid fee)

Decision: a flush takes the fee only when the balance is strictly larger than the unpaid fee. Otherwise it takes no fee and sends the whole balance to the destination; the fee stays owed by the address.

Reasons:

Consequences, and how the gateway handles them:

A collector that cannot receive (frozen by the token, for example): the fee transfer moves nothing, the contract restores feePaid, skips the fee and pays the destination in full. A collector can therefore never hold a merchant's funds hostage. Any other outcome of the fee transfer (a balance change that is not exactly the fee) reverts.

11.6 Off-chain: what is stored and how the books work

Migration v6 (src/db.ts):

Table Column Meaning
projects sweep_fee INTEGER NULL Base units. NULL = SWEEP_FEE_DEFAULT. 0 = no fee.
projects sweep_fee_payer TEXT NOT NULL DEFAULT 'merchant' merchant or customer.
forwarder_factories version INTEGER NOT NULL DEFAULT 1 Existing rows are v1. Rows written by this build are 2.
invoices forwarder_version INTEGER NULL 1 for forwarder invoices that existed before the migration, 2 for new ones, NULL in amount mode.
invoices fee_amount INTEGER NOT NULL DEFAULT 0 Snapshot of the bound fee (the cap for this address).
invoices fee_payer TEXT NULL, fee_collector TEXT NULL Snapshot of who bears it and where it goes.
invoices fee_paid INTEGER NOT NULL DEFAULT 0 What the address has paid its collector (0 or fee_amount).
sweep_txs fee_taken TEXT NULL The part of amount_moved that went to the collector.

Every sweep is built from the invoice's snapshot only (forwarder_factory, forwarder_destination, forwarder_salt, fee_collector, fee_amount, the invoice's token as fee token). Changing a project's fee, its payer or FEE_COLLECTOR_ADDRESS later affects new invoices only; an open invoice keeps the terms its address was derived from.

Books: amount_swept is everything that left the address (to the wallet and to the collector), so deposit_balance == amount_received - amount_swept still holds and the watcher is unchanged. fee_paid is the part that went to the collector. sweep_txs.amount_moved is likewise the total, fee_taken the fee part. A dry run that reports a fee above fee_amount is treated as a failed attempt and nothing is sent. When someone else flushed an address, the sweeper reads feesPaid() (solidified) and raises fee_paid to it; it never lowers it, and a failing lens changes nothing.

Money stays integer base units everywhere. The fee recommendation uses an exact fraction for the TRX price (parseRate and sunToTokenUnits in src/money.ts, BigInt, rounded up); there is no price oracle and no float.

11.7 Invoice JSON, webhooks, checkout

Every invoice (API, webhooks, SDK Invoice type) gains:

Customer-pays: amount_due = amount + fee. The public checkout JSON carries network_fee: { amount } only in that case, and the page shows "Network fee X USDT (included)" (English and Arabic). Merchant-pays shows the customer nothing about the fee and exposes no collector address publicly.

Stores keep comparing amount_paid with their order total: in both modes amount_paid >= amount for a fully paid invoice.

11.8 Existing v1 invoices and factories

v1 and v2 addresses come from different factories and different salt schemes. This build signs no v1 call.

11.9 recover-forwarder and manual flushes

A v2 address needs the fee terms as well as the factory, destination and invoice id. Where to find them:

  1. The invoice JSON and webhooks: forwarder.collector, forwarder.fee_token, forwarder.fee_units. Stores that save forwarder with the order have everything.
  2. npm run admin -- forwarders prints them per invoice (collector, fee_token, fee_units).
  3. Without any record: recover-forwarder takes --collector T… and --fee <amount> and defaults to FEE_COLLECTOR_ADDRESS and SWEEP_FEE_DEFAULT from the environment; --fee 0 derives fee-less addresses. The fee token is the network's payment token. A wrong guess is harmless: it derives a different, empty address and the command sends nothing for an address whose dry run moves nothing. If a project had its own fee, pass it.

11.10 Threat model additions

Threat Outcome Why
Fee-payer key or server compromised, attacker wants the fee income Cannot redirect it. Fees only ever reach the collector bound into each address. The collector is in the CREATE2 salt; naming another one addresses a different, empty clone.
Fee-payer key or server compromised, attacker wants to overcharge an existing address Cannot. At most the bound fee, once per address. The fee is in the salt; feePaid in the clone caps the total across all flushes.
Server or database compromised, attacker sets a huge fee or their own collector for new invoices Possible for new invoices, as it can already show customers any address. Existing addresses are unaffected. Same trust as the destination of a new invoice. Stores can check network_fee on each invoice; merchants see fee and net on every row.
Operator sets a fee the merchant did not expect Visible, not hidden. network_fee and amount_net are on every invoice, webhook and CSV row; the project's settings show the fee and who pays it (members read-only).
Collector wallet's key lost or wallet frozen by the token Fee income is lost or skipped. Merchant funds still flow. A fee transfer that moves nothing is skipped; the destination is paid in full.
Collector equals a project wallet or the fee wallet Refused at startup and when a project is saved. Config and ProjectService checks; the fee wallet's key is on the server, so fees must not accumulate there.
Dust sent to make the operator sweep for no fee No transaction. The sweeper holds any balance that does not exceed the unpaid fee (11.5), on top of the existing minimums and budgets.
Someone flushes an address themselves to dodge the fee Only for balances no larger than the fee, at their own TRX cost. Dust rule; a flush of a larger balance pays the bound fee whoever sends it.
Malicious token re-enters during the fee transfer Transaction reverts; nothing is paid twice. feePaid is written first; a mismatch reverts.
TronGrid's dry run claims a fee above the bound one Nothing is signed. The sweeper compares the estimate with fee_amount; the transaction itself is still verified byte for byte.

11.11 Cost

Measured on @ethereumjs/evm (London) with the mock token, as in 1.7: a first flush with a fee (deploy, fee transfer, one storage write, transfer) uses about 97k gas, against under 70k without a fee; later flushes of the same address about 14k. On TRON the two USDT transfers dominate, so expect a first sweep with a fee to cost roughly one extra USDT transfer of energy when the collector already holds USDT. Not yet measured on Nile: do that before choosing a mainnet fee. The dashboard's Fee wallet tab shows the measured average TRX per sweep and, with the operator's TRX price (TRX_USDT_RATE or the field on that tab), the fee that would cover it.

11.12 Tests

Appendix A. File change list

File Change
contracts/*, scripts/compile-contracts.mjs New (section 1).
src/tron/address.ts Base58check encode/decode, hex conversion, key to address.
src/tron/abi.ts, create2.ts, artifact.ts, rpc.ts, tx.ts, signer.ts, forwarder-chain.ts New (sections 2 and 3).
src/db.ts Migration v5.
src/config.ts, .env.example Section 5.1.
src/forwarders.ts New: ForwarderService.
src/sweeper.ts New: Sweeper.
src/invoices.ts Forwarder creation, new row fields, acceptDeposit, notify, mode filters on amount-mode queries, invoice.swept type.
src/watcher.ts Wallet filter, own-sweep filter, pollDeposits, processDeposit.
src/projects.ts deposit_mode, forwarder_factory, env sync.
src/serialize.ts, src/webhooks.ts New fields, invoice.swept.
src/routes/project-api.ts, src/routes/dashboard.ts, src/routes/public.ts Section 8.2, /health detail.
src/server.ts, src/index.ts, src/cli.ts Wiring, sweeper lifecycle, CLI commands.
src/views/admin.ts, public/admin.js, public/admin.css Section 8.4.
src/views/checkout.ts, src/views/i18n.ts, public/checkout.js, public/checkout.css Section 8.5.
sdk/src/index.ts Types.
Dockerfile, package.json Copy the artifact, contracts:build script.
test/* Section 9.
AGENTS.md, README.md, SECURITY.md, skills/* Section 10.1.

Suggested build order: contracts and artifact → address/abi/create2 with vectors → tx/signer/rpc with the fixture → migration and config → ForwarderService and invoice creation → watcher → sweeper → routes and serializer → UI and checkout → CLI → docs.

Appendix B. Facts checked for this design

Fact How it was checked
TVM CREATE2 uses the 0x41 prefix Reproduced the address of the SunSwap V2 USDT/WTRX pair on mainnet (section 2.3). 0xff does not match.
The contracts compile with solc 0.8.19 / london, no PUSH0 Compiled with the installed solc, opcode walk.
Counterfactual flush, false-returning token, TRX flush, binding, reverts Executed on @ethereumjs/evm 10.1.3 (London).
txID = sha256(raw_data_hex), protobuf field layout, deploy address formula Real unsigned transactions built by Nile TronGrid, decoded locally.
Response shapes of constant calls, reverts, missing transactions and accounts Read from TronGrid mainnet.
getEnergyFee = 100, getMaxFeeLimit = 15,000 TRX, dynamic energy enabled getchainparameters on mainnet and Nile.
TRC-20 history is available for never-activated addresses Queried two such USDT recipients on mainnet.
Migration v5 applies to a v4 database Run in memory with better-sqlite3.
CREATE2 onto an existing non-contract account succeeds and keeps the balance Read in java-tron Program.createContractImpl (contractAlreadyExists = existingAccount != null && isContractExist(…), then updateAccountType(AccountType.Contract)). Review, 2026-12-05. Still a Nile gate.
Plain TRX transfers to a contract account are rejected Read in java-tron TransferActuator.validate ("Cannot transfer TRX to a smartContract."). Review.
Every vector, selector, event topic, the fixture txID and its signature Recomputed independently during the review with @noble/hashes and @noble/curves. All matched.
Both contracts as printed here compile and contain no PUSH0 Recompiled during the review with the installed solc 0.8.19 / london, including the revised balancesOf.
The lens reverts on a failing token and on a token without code; an empty undeployed flush costs about 52k gas Executed during the review on @ethereumjs/evm (London).

Review notes

Adversarial review, 2026-12-05. The goal was to find anything that could lose or lock merchant funds, redirect them, settle an unpaid invoice, fulfil twice, drain the fee wallet, break on TVM specifics, or break amount mode and its migration. Each item below was fixed in place in the sections named.

Changed

  1. Salts are derived from the invoice id instead of random (D4, 2.2, 2.3, 5.5, 6.1, T11). With random salts, losing the database locked every unswept address forever unless the store had kept the forwarder object. Now an invoice id, the wallet and the factory are enough to recompute and flush an address (recover-forwarder, no database). The price is that salts are public, so anyone can flush early; that was already true after the first sweep, flush is permissionless by design, and items 2 and 3 remove the one thing that relied on secrecy (detection).
  2. The destination wallet stays polled in forwarder mode, and a transfer from a deposit address forces a scan of that address (6.3). The lens only sees balance changes. A flush between two lens polls (0 before, 0 after) hid the payment until the final scan at expiry, and a flushed payment to an already terminal address was never found. Every flush necessarily shows up at the wallet, so watching the wallet closes this for good. The original rule "ignore transfers from deposit addresses" is kept as part of it, because it also prevents a double credit (T22).
  3. Addresses are scanned until the books explain the balance, with no time limit (6.3, T21). The original scanned for 5 minutes after a balance change. If TronGrid indexed the transfer later than that, the invoice stayed pending and the money sat at an address the gateway believed empty; one final scan at expiry was the only retry. Added the invariant balance = received − swept, a backoff cadence and a health counter.
  4. The lens reverts instead of returning 0 for a failed token call (1.3, 1.5, 6.3, T19). A silent 0 (token call out of energy, wrong TOKEN_CONTRACT, node limit) was indistinguishable from "someone flushed this address", and the sweeper would have marked unswept funds as swept. Balances are now stored only from successful calls, and "flushed by someone else" needs a solidified 0 plus a complete history scan after it. Factory sizes re-measured.
  5. Two sweep minimums and a per-project daily budget (D7, 5.1, 7.1, 7.3, T7, T20). A sweep costs about 11 to 13 TRX. Sweeping every terminal invoice from 1 USDT let anyone create invoices through a store's checkout and turn each dollar sent into several dollars of the merchant's TRX. Now only funds that paid an invoice are swept from SWEEP_MIN_AMOUNT; partial, late and extra balances need SWEEP_STRAY_MIN_AMOUNT (default 10) or a deliberate Sweep now. SWEEP_PROJECT_DAILY_BUDGET_TRX (default 1000) is the circuit breaker for everything else, including a tenant on a shared server. Held funds are safe: their only exit is the wallet.
  6. force is admin-only (7.5, 8.2). The sweep route is reachable with an API key and by members. force let them spend the operator's fee wallet to move dust.
  7. A flush whose dry run moves nothing is never broadcast (1.5, 3.5, 7.3). The document said an empty flush costs about 3.9k gas. That holds only for a deployed address; on an undeployed one it deploys the clone for about 52k gas (measured), roughly 5 TRX for nothing.
  8. The sweeper no longer waits forever when the solidified balance is below what the books expect (7.3). After a stranger's flush followed by another payment, 0 < B < outstanding held permanently and the invoice stayed queued. After 10 minutes the chain wins and the books are corrected.
  9. Transactions are verified by rebuilding them, not by parsing them (D8, 3.3, 3.4, T3). A field-by-field check is only as good as the parser: a 32-bit varint decoder reads a fee_limit of 2^32 + x as x, and nested messages had no rule against unknown or repeated fields. The verifier now encodes the expected transaction itself and compares bytes; only the block reference, expiration and timestamp come from the node. The decoder is strict and uses BigInt. The signer checks at run time that an object really passed verification, since a type brand can be cast away. The lower bound on expiration against the server clock was dropped (harmless to sign, and clock skew would have stopped all sweeps silently).
  10. A transaction is declared dropped by solidified chain time, not by the server clock (3.5, 7.3). With a skewed clock or a lagging node the sweeper could rebuild a transaction that was still alive.
  11. txStatus reads the amount only from the Flushed log of the expected factory, forwarder and token (3.5). "The factory's Flushed log" was not specific enough once flushMany or a re-entering token can emit several.
  12. Detection never depends on the fee key (3.5, 6.3). The chain object was optional in the watcher; without a key there would have been no lens and no detection, while invoice creation still worked. Reads need no key and use the factory as the caller of constant calls.
  13. Deposit addresses are watched forever (D11, 6.3, T25). Customers reuse addresses. After 180 days a payment would have been invisible. The archive tier costs one request per 100 addresses per day.
  14. Per-address scan cursor (4, 6.3). Scans always started at the invoice's creation and one fetch is capped. An address buried under dust transfers would have hidden every later payment.
  15. Zero-value transfers are ignored, and unconfirmed transfers stop counting after 30 minutes (6.2, 6.3). USDT allows zero-value transfer and transferFrom to any address (address poisoning), which would have filled the table and the history. An unconfirmed transfer that never confirmed kept amount_detected high forever.
  16. Cap on open forwarder invoices per project (D12, 5.1, 6.1, T18). Amount mode is capped by amount slots. Forwarder mode had no cap, and open invoices are what the watcher polls.
  17. No automatic settlement of an expired invoice whose order was already paid through a re-issued invoice; Accept needs force for underpaid, late and duplicate payments (6.2, 8.2, T23). Forwarder mode has no time limit on expired → paid, so this case is more likely than in amount mode, and it would send a second invoice.paid for one order.
  18. TVM account facts written down and gated (1.5, 10.3, T17, Appendix B). TRX or TRC-10 dust activates a deposit address as a normal account before its clone exists. If CREATE2 failed on such an address, 1 TRX of dust would lock the USDT behind it. java-tron's source shows CREATE2 succeeds on a non-contract account and keeps its balance, and that plain TRX transfers to a deployed contract are rejected. This is now a hard Nile gate. TRC-10 tokens are documented as not counted and not recoverable.
  19. Project wallet guidance and checks (1.5, 1.6, 5.2, 8.4, 10.1, T24, T26). Sweeps arrive from a contract; some exchanges do not credit such deposits and most ignore internal TRX. The fee wallet must hold nothing but a TRX float. The destination check also covers the token contract and deposit addresses, and compares the on-chain address with the local one for the project's actual wallet.
  20. Factory verification uses the solidity node and committed constants for built-in factories (5.4). A factory accepted before its deployment was final could vanish in a reorg, and a redeploy has a different address.
  21. Leading-zero test vectors (2.3, 5.4). Random probes rarely hit an address or salt with leading zero bytes, which is where hex and BigInt conversions break, and a wrong derivation means unflushable addresses.
  22. Amount-mode isolation spelled out (4). assignTransfer refuses forwarder invoices explicitly, and a test migrates a v4 database file and settles an old invoice.

Checked and left as it was

For the owner to decide

Deviations (signer / RPC stage)

Small departures from section 3, made while implementing abi.ts, rpc.ts, tx.ts and signer.ts:

Deviations (integration stage)

Departures from sections 3 to 10, made while wiring forwarder mode into the app:

Deviations (review fixes)

Edit this page on GitHub