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:
- Every invoice gets its own deposit address and a round amount (
49.90). - The deposit address is the counterfactual CREATE2 address of a tiny forwarder contract. Its only possible destination is the project's wallet, because the destination is hashed into the address.
- After the payment confirms, the gateway calls the factory once: deploy the forwarder (if needed) and flush the USDT to the wallet. That call is paid by a fee-payer wallet whose key the server holds.
- The fee-payer key can pay TRX for energy and nothing else of value. It cannot move USDT anywhere except to the wallet bound into each address. The merchant wallet's keys are never on the server. The fee wallet holds a small TRX float and nothing else.
- Sweeps cost TRX, so the fee wallet is a target for griefing. Only balances worth more than a sweep are swept automatically, and spending is capped per project per day (section 7).
- Unique-amount mode stays the default and is unchanged.
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.jsonCompiler 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):
EIP-1014 official vectors with
prefix = 0xffprove the function shape:(0x00…00, 0x00…00, 0x00) → 0x4D1A2e2bB4F88F0250f26Ffff098B0b30B26BF38,(0xdeadbeef00…00, 0, 0x00) → 0xB928f69Bb1D91Cd65274e3c79d8986362984fDA3,(0x00…00deadbeef, 0x00…00cafebabe, 0xdeadbeef) → 0x60f3f640a8508fC6a86d45DF051962668E1e8AC7,(0, 0, empty) → 0xE33C0C7F7df4809055C3ebA6c09CFe4BaF1BD9e0.Hand-computed TVM vectors (computed with a separate pure-Python Keccak, not with
@noble):deployer20 salt initCode address20 base58 00…0000…000065a4f4773d93d98362d0dc131dd51ada88c34f7fTKEerhofQTEicnAHg9HWdsMzm1mA6dBDwMdeadbeef00…0000…000029a2574c282a56ab6d8e12c922a0d63625a243efTDmMBaJ8s3pjwH6voNuYDQVMhgQNsMgaL600…00deadbeef00…00cafebabedeadbeefece484536af6315b7af4b9f5ad31eb684e1b3aa4TXZnDxq7amkCpeghQYbqj74vba2nTktxRV00…0000…00(empty) fb3a2d661eb5d8b080361a50803c425352242465TYsaJSXG8yHSd7V1NaGYQmLjsPyG4VoDhMA 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) == pairand that the 0xff prefix does not match.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 → TFoBfPJV98xmcv5nJegNxPayRoZtSg4R1TVectors 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 → TA1V1sjtcBtQKX8GP2R7V12HppVkMTnK6KSalt 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:
fetchis injected (default globalfetch). Tests pass a fake. Every request hasAbortSignal.timeout(15_000).All requests send
visible: true, so addresses are base58 in both directions.TRON-PRO-API-KEYis sent only when an API key is configured (today: mainnet only, same rule asTronGridClient).Requests go through one queue per instance with
minIntervalMs(default 80 ms) between them.Reads retry twice on HTTP 429/5xx and on network errors (500 ms, 1500 ms).
broadcastnever retries itself.Response shapes (Verified against TronGrid):
- constant call OK:
{ result: { result: true }, energy_used, energy_penalty, constant_result: ["<hex>"], transaction }. - constant call revert:
{ result: { result: true, message: "REVERT opcode executed" }, constant_result: [""], transaction: { ret: [{ ret: "FAILED" }] } }.okis false whenresult.result !== true, orresult.messageis set, ortransaction.ret[0].ret === "FAILED". triggersmartcontract:{ transaction: { raw_data, raw_data_hex, txID, visible }, result: { result: true } }.deploycontract:{ raw_data, raw_data_hex, txID, visible, contract_address: "41…" }(notransactionwrapper).gettransactioninfobyidfor an unknown transaction:{}.getaccountfor a never-activated address:{}.- An error body looks like
{ "Error": "class … : message" }: throwTronRpcError(code "node_error").
- constant call OK:
broadcastresult mapping ({ result: true }or{ code, message: <hex-encoded text> }, decode the message):codeMeaning for the caller result: trueaccepted DUP_TRANSACTION_ERRORaccepted (already in the pool) SERVER_BUSY,NO_CONNECTION,NOT_ENOUGH_EFFECTIVE_CONNECTION,BLOCK_UNSOLIDIFIED, HTTP 429/5xx, timeoutretryable: true. The fate of the transaction is unknownSIGERROR,CONTRACT_VALIDATE_ERROR,CONTRACT_EXE_ERROR,BANDWITH_ERROR,TAPOS_ERROR,TOO_BIG_TRANSACTION_ERROR,TRANSACTION_EXPIRATION_ERROR,OTHER_ERRORretryable: false. The node rejected it, it will never landVerify on Nile: record one real response for each row we can provoke and keep them as test fixtures.
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:
sha256(raw_data_hex) === txID(hex, case-insensitive).- Decode
raw_data_hexstrictly (rules below) and take exactly four values from it:ref_block_bytes(2 bytes),ref_block_hash(8 bytes),expirationandtimestamp. Nothing else from the node is used. - Encode a fresh
Transaction.rawfrom those four values plus what we asked for: one contract oftype = 31with theTriggerSmartContracttype 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 equalraw_data_hexbyte 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. expect.datastarts with the selector offlush,flushTRX,flushManyordeploy, andexpect.contractis a row offorwarder_factoriesfor this network.expect.feeLimitSunis an integer with0 < feeLimitSun <= expect.maxFeeLimitSun.timestamp <= expiration,expiration − timestamp <= 15 minandexpiration <= 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)
32333bbfe84cac887a8c29abbc0774bd05f6d4fe3789676addbe25e4f9b2c03f2bd671992fbdd9a1440a589a4624e5db00c797390729ccfdad90661cd80f6cbf00JSON 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;
}secp256k1.sign(txIdBytes, key)from@noble/curves/secp256k1(RFC 6979, low-S). Signature hex isr(32) ++ s(32) ++ recovery(1)with recovery00or01(what TronWeb produces).signthrows unlessisVerifiedTx(tx)is true, and it recomputessha256(raw_data_hex) === txIDitself. A cast toVerifiedTxis not enough to get a signature.- Before returning, recover the public key from the signature and require that its address equals
address. - The class has no method that signs arbitrary bytes. The private key lives in a
#privatefield and the class definestoJSON()and[util.inspect.custom]that return"[TronSigner T…]".
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:
- Reading needs no key.
TronForwarderChainis always constructed, with or without a fee payer key. Without one,feePayeris undefined andestimateFlush,prepareFlushandbroadcastthrow, whilebalances,txStatus,solidTimeandverifyFactorywork. Payment detection must never depend on the key. Lens calls use the factory's own address asowner_address(a constant call only needs a valid address). - Energy estimate:
callConstantof the same call,owner= fee payer.energyUsedalready includes the dynamic energy penalty.feeSun = energyUsed * energyPriceSun().amount= the decoded return value. An estimate withamount == 0is never turned into a transaction: on an undeployed address it would pay for a deployment that moves nothing. - Fee limit (the sweeper computes it, integers only):
feeLimitSun = clamp(ceil(energy * 13 / 10) * energyPrice, 1_000_000, config.forwarder.sweepFeeLimitSun). Ifenergy * energyPrice > sweepFeeLimitSunthe sweep is not sent (error text names both numbers). A fee limit is always set, andverifyTriggerTxrequires it to equal what we asked for. - txStatus: ask the solidity node first (
success/failedonly from solidified data). If it answers{}, ask the full node: found meanspending,{}meansunknown.movedis theamountword of theFlushedlog (topic above) that was emitted byexpect.factory, whoseforwardertopic isexpect.forwarderand whosetokentopic is the requested asset; it is 0 when there is no such log. Logs of any other address or forwarder are ignored.failed.reasonisreceipt.resultplus the decoded revert reason. - feeWallet level:
emptywhen the account does not exist orbalanceSun + energyAvailable * energyPriceis below the cost of one sweep (usesweepFeeLimitSun / 2as the yardstick),lowwhenbalanceSun < feeWalletMinSun, otherwiseok. A non-zerotokenBalanceis reported as a warning in the fee wallet card and inrequirements(). - Idempotency: TRON has no account nonce, so nothing sequences transactions. The sweeper keeps at most one open
transaction per invoice and asset (unique index in section 4), persists the
txIdandexpirationbefore broadcasting, and never builds a replacement until the old one is confirmed failed, or the solidified chain time (solidTime) is past itsexpirationand no node knows it. A duplicate flush would be harmless anyway (it moves 0 and costs a few thousand energy).
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:
fee_payer: a key is configured.factory_configured:config.networks[project.network].forwarderFactoryis set.factory_verified: the factory is inforwarder_factories, orregistersucceeds now.fee_wallet: the fee wallet exists on this network and its level is notempty(alowlevel 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".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-chainforwarderAddress(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.token: the lens returns a balance for the project wallet. The lens reverts when the token does not answerbalanceOf, so this provesTOKEN_CONTRACTis 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]:
- Require a configured fee payer. Print its address and balance. Refuse when a factory is already configured for
the network unless
--force. rpc.buildDeploywith the artifact's factory bytecode and ABI, nameTronGateForwarderFactory,consume_user_resource_percent: 100,origin_energy_limit: 10_000_000,call_value: 0, the fee limit.verifyDeployTx(section 3.3), sign, broadcast.- Poll
transactionInfo(txId, solid = true)for up to 3 minutes. RequireSUCCESS. ForwarderService.register(network, contractAddress, txId), which runs the on-chain verification below.- 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:
contractInfo(factory).runtimeCodeequals the artifact's factorydeployedBytecodeonce theimmutableRangesare zeroed in both. Verify on Nile thatruntimecodeis byte-identical to solc's runtime code.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.create2Prefix()is0x41.cloneCodeHash()equalskeccak256(cloneInitCode(implementation))computed locally.- For two random
(destination, salt)pairs and for one pair with leading zero bytes in both values,forwarderAddress()on-chain equalsforwarderAddress()insrc/tron/create2.ts. - Every code reference of every immutable holds the expected word (
implementation, the localcloneCodeHash,0x41left-aligned), and the forwarder'sfactoryreferences all hold this factory. The getters read one copy each;deploy()reads another. - Dry runs (constant calls, nothing is sent) of
deploy(probe)return the locally derived address and offlushTRX(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`- The amount is round:
amount_due === amount_base. There are no amount slots, soamount_slots_exhaustedcannot happen and long TTLs are cheap. allocateis DB-only and synchronous. It derives the salt withforwarderSaltForInvoice(id)and the address from theforwarder_factoriesrow. It fails closed with503 forwarder_unavailablewhen the project's factory is not inforwarder_factories. It never falls back to amount mode silently.- Both new checks run after the existing
order_idlookup, so repeating the request for an order that already has an open invoice returns that invoice and is never refused by the cap. - The cap (D12) exists because open invoices are what the watcher polls. Without it, a flood of checkouts would use up the API quota and delay payment detection for every project on the server.
- A missing fee payer key does not block creation. Payments are still detected and funds are safe at their addresses, sweeps simply wait. The dashboard shows a banner.
order_ididempotency is unchanged.supersedeSiblingsis unchanged and still runs onmarkPaid: it is mode-agnostic, and in forwarder mode a payment to a superseded invoice's address is still attributed to that invoice and shown for refund, so nothing extra is needed.
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.
wallets()keeps returning every active project's wallet, in both modes. In forwarder mode the wallet is where flushes arrive, and watching it is what makes detection independent of who flushes an address and when (see "Missed-flush safety" below). The cost is one confirmed-history request per wallet per tick, as in amount mode.walletsWithSettleableInvoices()returns thepay_addressof settleable amount-mode invoices (as today) plus theforwarder_destinationof forwarder invoices that are open, have unswept funds or a sweep in flight, or became terminal less than 7 days ago. This covers a project that changed its wallet or was disabled.hasOpenInvoices()counts amount-mode invoices only, so a forwarder-only wallet gets no unconfirmed lookup.findMatch()returns amount-mode invoices only. A customer who pays a forwarder project's wallet directly shows up as an unmatched transfer, which is the right outcome: visible and refundable.process()first checks whether the transfer'sfromis a known deposit address (SELECT id FROM invoices WHERE deposit_mode='forwarder' AND network=? AND pay_address=?). If so, the transfer is a flush arriving at the wallet. It is not stored, never matched against an amount-mode invoice and never listed as unmatched. Instead the watcher sets that invoice'sdeposit_changed_at = now, which forces a history scan of the deposit address, and callsonDepositChange(invoice.id). Without this rule a customer could send an amount-mode invoice's exact amount to a forwarder address and get one payment credited twice when the sweep arrives.
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:
- the books do not explain the balance:
deposit_balance <> amount_received - amount_sweptand the invoice has no sweep in flight. Either a payment is not indexed yet or someone else flushed the address. Cadence by the age ofdeposit_changed_at: every tick for 5 minutes, then once a minute for an hour, then every 10 minutes for as long as it lasts. There is deliberately no time limit: a payment that TronGrid indexes late must still be found, and money sitting at an address the gateway believes empty is effectively locked.health()reports how many addresses have been in this state for more than 30 minutes, deposit_changed_atis within the last 5 minutes (indexing lag, solidification, a flush that arrived at the wallet, a balance that went up and down between two lens polls),status = 'confirming'oramount_detected <> amount_received(something is still unconfirmed),- the invoice is
expiredanddeposit_scanned_atis null or older thanexpires_at(one final scan at expiry), - the invoice left the hot tier and
deposit_scanned_atis older than the moment it became terminal (one final scan).
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:
- Drop the transfer if its value is 0 (nothing is stored).
- Upsert the transfer with
invoice_id = invoice.id(sameON CONFLICTas today, same id scheme). - Recompute
receivedanddetectedfromtransfers(definitions in 6.2) and store them on the invoice. - Apply the table in 6.2 (
markConfirming,markPaid). - 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 flush between two lens polls leaves the lens unchanged (0 before, 0 after). The flushed USDT, however, arrives at
the destination wallet as a transfer from the deposit address. The wallet poll sees it and
process()forces a history scan of that address, which finds the customer's confirmed transfer and settles the invoice as usual. - If the lens did see the balance, the address stays in the "books do not explain the balance" state and keeps being scanned until the transfers are found.
- The final scans at expiry and on leaving the hot tier remain as a third net.
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 = NULLSo: 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"──▶ queuedBackoff 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):
- No fee payer key:
sweep_error = "FEE_PAYER_PRIVATE_KEY is not set", next attempt in 5 minutes, attempts unchanged. - Read the solidified balance
Bof the address through the lens (solid: true). Withoutstanding = 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. Setdeposit_changed_at = now, retry in 15 s (attempts unchanged), and only when a complete history scan has run after that reading andBis 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: setamount_swept = amount_received,sweep_status = 'swept',swept_at = now,sweep_error = NULL, and emitinvoice.sweptwithsweep.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 withB. Without this limit an address that a stranger flushed and a customer then paid again would stayqueuedforever.Bis below the applicable minimum of 7.1 and the sweep is not forced:skipped.
chain.estimateFlush. A revert is a counted failure with its reason (for exampleTG: token did not move). An estimate withamount == 0is never sent; handle it likeB == 0. Flushing an empty, undeployed address would pay about 5 TRX to deploy a clone and move nothing.- Compute the fee limit (section 3.5). Over the cap: counted failure, the error names the estimate and the cap.
- Daily budget.
spent= over this project'ssweep_txscreated in the last 24 hours:fee_limit_sunof open rows (signed,broadcast) plusmax(fee_sun, energy_used × energy price)ofsuccessandfailedrows (droppedrows cost nothing; counting energy keeps the cap meaningful when the fee wallet uses staked energy). Ifspent + 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. chain.feeWallet(network). If it cannot coverfeeLimitSunplus 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).chain.prepareFlush. ATxVerificationErroris a counted failure and is logged aterrorlevel with the mismatch: it means the node returned something we did not ask for.- In one DB transaction: insert
sweep_txs(status = 'signed',reason=paidwhen the invoice is paid and nothing was swept yet, elsestrayormanual) and set the invoice tobroadcastwithsweep_tx_id. chain.broadcast. Accepted:sweep_txs.status = 'broadcast'.retryableerror: leave itsigned, step 1 decides once the expiration passes. Non-retryable rejection:sweep_txs.status = 'failed', invoice back toqueuedas 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…" }
}deposit_modeis always present.amount_receivedis always present ("0"when nothing arrived; in amount mode it mirrorsamount_paid).sweepisnullwhensweep_statusisNULL.forwarderisnullin amount mode.pay_addressis the deposit address,amount_dueequalsamount.
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
- New event
invoice.swept: sent when a sweep transaction for the invoice token is confirmed with an amount greater than zero, and when the gateway establishes that someone else flushed the address (thensweep.tx_idisnull).data.invoice.sweepcarries the transaction. Add it toInvoiceEventType,DELIVERED_EVENTSand the SDK'sWebhookEventType.InvoiceServicegetsnotify(id, event)for the sweeper to emit it. - No other new events.
invoice.confirming,invoice.paidandinvoice.expiredbehave as today and now carryamount_received,sweepandforwarder. - Guidance for stores (docs): fulfil on
invoice.paid. At that point the funds are confirmed at an address whose only exit is the store's wallet.invoice.sweptis for accounting.
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().
- Settings → new card "How customers pay" (after the wallet card). Two radio options: Unique amount (default)
and Address per invoice (forwarder), each with one line of explanation. Under the second: the requirements
checklist from
/projects/:pid/forwarder(a tick or a cross and the message for each), the factory address, and the fee wallet address with its level, the fixed notice "Use a wallet you control…" (5.2) and one line on cost ("each payment costs the fee wallet about 11 to 13 TRX"). Admins get a Save button, disabled until every check passes. Members see the card read-only. Env-managed projects show "Set by DEPOSIT_MODE in the server environment". Changing the wallet while in forwarder mode shows a note: existing invoices keep paying the old wallet. - Invoices table → new "Sweep" column, shown when the project is in forwarder mode or any listed invoice is.
Badges:
queued,sweeping(broadcast),swept ↗(links tosweep.tx_url),failed(title =sweep.error),held(skipped: below the automatic sweep minimum, title = amount at the address),—. The amount cell showsreceived / duewhenamount_receiveddiffers fromamount_due, with a tag:partial,paid late(expired andamount_received >= amount_due) oroverpaid. Row actions: Accept (whenacceptDepositwould succeed), Sweep now (when status isfailed,skipped, or unswept funds remain; for a balance belowSWEEP_MIN_AMOUNTthe button is shown to admins only and sendsforce), and for admins Recover… (dialog: TRX or a token address). - Admin view → "Fee wallet" card (from
/admin/forwarder): address with copy button, and per network the balance in TRX, available energy, level pill (ok/low/empty/not configured), factory address and whether it is verified, queued / in-flight / failed sweep counts, and the average fee of the last 20 sweeps. When no key is configured the card says how to create one (npm run admin -- fee-wallet new). - Header pill: next to Live, a warning state when
sweeper.okis false, withlast_erroras the title. A project whose daily sweep budget is used up shows a banner on its invoices page ("Sweeps are paused until … : the daily fee budget is reached. Funds stay safe at their addresses."). - New invoice dialog: in forwarder mode the result shows the deposit address and the round amount.
8.5 Checkout (src/views/checkout.ts, public/checkout.js, src/views/i18n.ts)
data-mode="forwarder"on<body>. The amount is shown round, with at least two decimals and no highlighted digits (<mark>is not rendered). LabelsendAmount("Send") instead ofsendExactly.- Hint
hintForwarder: "This address is only for this payment. Send {amount} {symbol} on TRON (TRC-20). Do not send any other coin or token to it." - The QR code already encodes
pay_address, which is now the deposit address. The route is unchanged. - Partial payments: a banner
partialReceived("Received {received} of {amount} {symbol}. Send the remaining {remaining}.") driven by the status poll (amount_detected,amount_remaining). The TronLink button and the copy-amount button useamount_remainingonce something was received. - Footer
footerForwarder: "Non-custodial · this address can only pay out to the merchant's wallet · Powered by". - New keys in both
enandar:sendAmount,hintForwarder,partialReceived,footerForwarder. - Document for merchants: a first-time recipient address costs the sender more energy for a USDT transfer (about 130k instead of 65k) when paying from a self-custody wallet. Exchange withdrawals have a flat fee and are unaffected.
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.
- The committed artifact equals a fresh compile (bytecode, ABI, immutable ranges). This keeps the JSON honest.
- No
PUSH0in any bytecode (walk the opcodes, skip push data). NoSELFDESTRUCTorDELEGATECALLin the forwarder. - Factory deploys;
create2Prefix()is0xffon the EVM; the probe exists. forwarderAddress()equalssrc/tron/create2.tswith prefix 0xff;forwarderAddressWithPrefix(0x41, …)equals it with prefix 0x41;cloneCodeHash()equalscloneCodeHash(implementation).- Deployed clone code is exactly
363d3d373d3d3d363d73 ++ implementation ++ 5af43d82803e903d91602b57fd5bf3. - USDT-like token that returns false: fund the counterfactual address,
flushdeploys and moves everything, emitsForwarderDeployedandFlushed, returns the amount. - Second
flushreturns 0, emits nothing, does not revert. Top-up thenflushmoves the new balance. LyingTokenrevertsTG: token did not move. Frozen token reverts. Balance stays.- Destination binding:
(destination2, salt)is a different address and cannot touch the first address's funds. - Direct
flushToken/flushTRXon a clone and on the logic contract revertTG: only factory. - Zero destination reverts.
flushTRXfor an address funded before deployment and for value sent to a deployed clone; a receiver that rejects value revertsTG: TRX send failed.flushManywith a mix of funded and empty addresses.ReentrantToken(re-entersfactory.flushfromtransfer) cannot move funds anywhere but the destination.balancesOfreturns balances in order, and revertsTG: balanceOf failedfor a token whosebalanceOfreverts and for a token address without code.flushof an empty undeployed address deploys the clone and returns 0. The test records the gas so the cost the sweeper avoids (7.3 step 3) stays documented.- Gas guard: deploy + flush under 70,000 execution gas and a flush of a deployed address under 15,000 with the mock.
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)
- Decode the real fixture of section 3.3;
verifyTriggerTxaccepts it with the matching expectation, and re-encoding the decoded fixture reproducesraw_data_hexexactly. - Each tampering is rejected: wrong
txID, other contract address, other owner, changeddata, selector outside the allow-list,call_valueset,call_token_valueortoken_idset,fee_limitmismatch,fee_limitof2^32 + x(the 32-bit truncation case), a fee limit abovemaxFeeLimitSun, a second contract, an extra top-level field, a repeated field and an unknown field inside the contract and insideTriggerSmartContract,Permission_id, a non-canonical varint, trailing bytes, aTransferContract(type 1) with a valid hash, an expiration too far in the future. An expiration in the past is accepted (harmless, and it must not depend on the server clock). TronSigner: the fixture signature with key0x00…01is reproduced exactly; the recovered address matches; a plainUnsignedTxis not accepted by the type, and an object cast toVerifiedTxthat did not passtx.tsis rejected at run time; the key does not appear inJSON.stringify(signer)orutil.inspect.verifyDeployTx: accepts artifact bytecode, rejects other bytecode, checks the contract address formula (txID08ef158cd4a4d53c13c07548bb9098ce3fa931c793e0a39857f8abac19efbcf0+ owner key-1 address →41de3cd07e63cebc686e0e3ac68a1bf3984509e1fc, Verified).TronRpc: constant call OK and revert shapes; broadcast mapping for every row of the table in 3.2;{}handling fortransactionInfoandaccount; retries on 429 for reads and none forbroadcast; API key header only when set.TronForwarderChain.verifyFactory: passes on consistent fake responses and fails on each of the five checks.loadConfig: key and file handling, mutual exclusion, bad hex,DEPOSIT_MODE=forwarderwithout a key.
9.5 test/flow.test.ts: new describe("forwarder mode") blocks
Invoices and API:
- Creates an invoice with a round
amount_due, a uniquepay_addressthat equalsforwarderAddress(...)of the returnedforwarderfields, and noforwarder/sweepin the public status JSON. - 100 invoices for the same amount all succeed with distinct addresses (no slot exhaustion).
503 forwarder_unavailablewhen the factory is not registered;400 amount_too_smallbelow the minimum.forwarder.saltequalsforwarderSaltForInvoice(id); the address can be recomputed from the invoice id, the wallet and the factory alone.503 too_many_open_invoicesat the cap; repeating an existing order's request is still answered with its invoice.- Amount-mode projects behave exactly as before (the existing tests stay untouched and green).
Watcher:
pending → confirming → paidwith a round amount; webhooksinvoice.confirming,invoice.paid.- Two invoices of the same amount: a payment to one address settles only that invoice.
- Partial payment stays
pendingwithamount_received; a top-up settles it;amount_paidis the total. - Partial at expiry (an amount of at least
SWEEP_STRAY_MIN_AMOUNT):expired, funds swept as stray, Accept withforceturns itpaidwithsettled_manually. - Payment completed after
expires_at: staysexpired, attributed, swept; Accept works. - Payment sent in time but detected after expiry:
expired → paid. - Overpayment and a second transfer after
paid: attributed,amount_received > amount_paid, swept. - Rate-limit shape: 150 open invoices with no activity cause 2
balancescalls and 0 history queries per tick; one payment causes history queries for that address only. - A sweep arriving at the wallet is not recorded as an unmatched transfer.
- Warm and cold tiers: an expired invoice is still found when funds arrive a day later.
- Third-party flush between polls, and before the very first lens poll: the flush arriving at the wallet forces a scan and the payment is settled then, not only at expiry.
- A forwarder address receives exactly the amount of an open amount-mode invoice on the same wallet and is swept: the amount-mode invoice is not settled (no double credit).
- Late indexing (
historyLagMs= 20 minutes after the lens saw the balance): the address keeps being scanned and the invoice is settled when the transfer appears;deposits_unreconciledcounts it meanwhile. lensFails: no balance is overwritten, the tick fails, nothing is marked swept.- More transfers to one address than a single fetch returns: the cursor advances and a payment after the dust is found.
- Zero-value transfers are ignored (no row, no status change).
- An unconfirmed transfer that never confirms stops counting towards
amount_detectedafter 30 minutes. - An address older than 180 days is still checked (archive tier) and a payment to it is attributed.
- An expired invoice whose order was re-issued and paid is not settled automatically by an in-time payment found
later; Accept without
forceanswersneeds_confirmation.
Sweeper:
- Paid invoice:
queued → broadcast → swept,invoice.sweptwebhook,amount_swept,sweep.tx_url. - Nothing is sent before the balance is solidified.
- Estimate revert: backoff schedule,
failedafter 10 attempts, Sweep now resets and succeeds. - Fee wallet too low: stays
queuedwith the error, attempts unchanged, proceeds after a top-up. - No fee payer key: invoices are created and paid, sweeps wait,
sweeper.enabledis false. - Broadcast with unknown fate (
retryable), transaction never mined: after expiration it isdroppedand rebuilt; never two open transactions for one invoice. - Broadcast with unknown fate, transaction mined anyway: resolved as
success, no second transaction. - Mined failure (
revertSweeps): counted failure, retried. - Address already flushed by a third party: marked
sweptwithout a transaction. - Dust: below
SWEEP_MIN_AMOUNTisskipped; a forced sweep works for an admin and answers403for a member and for an API key. - Griefing: 1 USDT sent to each of 50 expired invoices causes zero transactions and no fee; every invoice shows
held. A stray balance ofSWEEP_STRAY_MIN_AMOUNTis swept. A member's Sweep now moves a held balance. - Daily budget: once a project's budget is used up its sweeps wait with the error text and unchanged attempts, another project still sweeps, and the first resumes when the window moves on.
- A dry run that reports
amount == 0is never broadcast. 0 < B < outstanding(a stranger flushed, then a second payment arrived): after 10 minutes the books are corrected and the remaining balance is swept.- A transaction is declared
droppedby chain time: with the server clock far ahead andchainTimebefore the expiration, nothing is rebuilt. - An address flushed by a third party emits
invoice.sweptwithsweep.tx_id = null. - A wallet change after invoice creation: the sweep still targets the snapshot destination.
- Simulated payment: no sweep is queued.
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
AGENTS.md: replace "The server must never hold private keys." with: "The server never holds a merchant wallet's keys. The only key it may hold is the optional fee-payer key (FEE_PAYER_PRIVATE_KEY). It pays TRX for sweeps and cannot move customer funds anywhere except to a project's own wallet. The signer signs only transactions that passedsrc/tron/tx.tsverification; never add another signing path." Add: "Contracts live incontracts/. After editing them runnpm run contracts:buildand commitcontracts/artifacts/forwarders.json." and "Forwarder-mode behaviour is tested intest/flow.test.tswithFakeChain; contracts intest/contracts.test.ts."README.md: a Features bullet and a "Two ways to match payments" section (comparison table: amount shown, keys on the server, cost per payment, partial payments, setup); the new env table rows; API additions; theinvoice.sweptevent; the updated Security model (below); measured costs from Nile. The "Non-custodial" bullet becomes mode-aware: in amount mode the server has no keys at all; in forwarder mode it has one fee key that cannot redirect funds. The section also says, plainly: each payment costs the fee wallet about 11 to 13 TRX; use a wallet you control as the project wallet (some exchanges do not credit deposits sent by contracts); send only the payment token to a deposit address (TRX is recoverable, other TRC-20 tokens are recoverable, TRC-10 tokens are not); small stray balances are held at their address until Sweep now.SECURITY.md: scope gains "anything that lets the fee-payer key, the server or a third party move funds from a deposit address to anywhere but the project wallet, or makes the gateway derive an address that cannot be flushed". Operator checklist gains: keep the fee wallet balance small and keep nothing else in it, never use a merchant wallet's key as the fee key, useFEE_PAYER_PRIVATE_KEY_FILE, back up the database, and know thatrecover-forwardercan flush any address from its invoice id if the database is ever lost..env.example: a "Forwarder mode (optional)" block with the variables of section 5.1.skills/qirsh-deploy/SKILL.md: enabling forwarder mode (create the fee wallet, fund it, factory, toggle, optional energy staking or delegation), monitoring the fee wallet.skills/qirsh-integrate/SKILL.md: round amounts, new fields,invoice.sweptis informational.skills/qirsh-test-payments/SKILL.md: partial, late and over payments, and how to watch a sweep on Nile.contracts/README.md: what the two contracts do, the address formula, and how to flush by hand: open the factory on Tronscan, Write contract,flush(destination, salt, token)with the values from the invoice'sforwarderobject or theforwardersCSV, or withsalt = keccak256("TronGate forwarder salt v1:" + invoice id)when only the invoice id is left. Any wallet can do it, the funds go todestination.docs/design/forwarders.md: this file, kept as the design record.
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
- 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.
- 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()returns0x41. Record energy and fee. verifyFactorypasses, including the exactruntimecodecomparison.- 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
Flushedlog as it appears ingettransactioninfobyid. - 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_ENERGYshape. 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 adjustTronRpcparsing if any shape differs.
- The factory deploys and
- Publish Nile: commit the Nile factory address to
NETWORKS.nile.forwarderFactory, update the README numbers. - 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.
- The fee collector is
FEE_COLLECTOR_ADDRESS(orFEE_COLLECTOR_ADDRESS_<NETWORK>). Its key is not on the server. Without it fees are off and every address is a fee-less address, exactly as before. - The fee is per project:
sweep_fee(base units;NULLmeansSWEEP_FEE_DEFAULT;0turns it off) andsweep_fee_payer:merchant(default: the customer pays the round amount and the wallet receives it minus the fee) orcustomer(the fee is added toamount_dueand shown on the checkout). - The fee, the fee token and the collector are hashed into the deposit address together with the destination. The address itself remembers what it has paid. So the server, the fee-payer key and any stranger can make an address pay at most its bound fee, once, to its bound collector, and everything else only to its bound destination.
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 factoryTronGateForwarderFactory (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):
- Over the whole life of the address, the total of
feeTokenthat leaves it forcollectoris0or exactlyfee. Never more, whoever calls and however often. - Every other base unit of every token, and all TRX, that leaves the address goes to
destination. - Nothing leaves it for any third address.
Why it holds:
- The clone accepts calls only from the factory (
TG: only factory), and the factory passes only arguments that hash to the clone's own address. SocollectorandfeeCapinsideflushTokenare always the bound ones. - The factory passes
feeCap = feeonly whentoken == feeToken, else0. Other tokens and TRX never pay a fee. feePaidis the clone's only storage and has no setter.flushTokentakes a fee only whilefeeCap > feePaid, and then takes exactlyfeeCap - feePaidand setsfeePaid = feeCap. Since the fee is taken whole or not at all (11.5),feePaidis only ever0orfee.feePaidis written before the fee transfer. A token that re-entersflushduring that transfer finds the fee already paid; the outer call then sees a balance change that is neither "the fee moved" nor "nothing moved" and reverts the whole transaction (TG: fee transfer mismatch). Tested withReentrantToken.- Neither transfer's return value is trusted (TRON USDT returns
falseon success). The fee counts as paid only if the address's own balance fell by exactly the fee; the destination transfer must lower the balance or the call reverts (TG: token did not move).
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:
- A flush never pays the collector without paying the destination. The alternatives were worse: taking a partial fee would let dust payments be turned entirely into operator income (a customer's 1 USDT mistake would vanish), and reverting would lock small balances at the address until someone tops it up, which nobody can be made to do.
- Funds are never stuck: any balance can always be flushed to the destination by anyone.
- The fee is all-or-nothing per flush, which keeps
feePaidat0orfeeand the books simple.
Consequences, and how the gateway handles them:
- The gateway's own sweeper never sends a sweep that would collect no fee: a balance
<=the unpaid fee is held (sweep_status = 'skipped', error "held at the deposit address (the balance does not exceed the network fee)"). Sweep now refuses it with409 below_minimum; only an admin's force sends it, and then the operator knowingly pays TRX for a sweep that earns nothing. When more arrives and the balance exceeds the fee, the next sweep takes it. - A third party may flush dust (they pay the TRX themselves). The merchant gets the dust, the address still owes the fee, and the next larger balance pays it. Someone could avoid the fee for a merchant by sending payments in pieces no larger than the fee and flushing each at their own cost; with a fee of about one sweep's TRX that costs them more than the fee. The operator loses income at most, never funds, and the merchant and customer lose nothing.
- Merchant-pays invoices must be worth sweeping after the fee:
amount - fee >= max(SWEEP_MIN_AMOUNT, 1 base unit), else400 amount_too_small. Customer-pays invoices areamount + fee, which always exceeds the fee.
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:
network_fee:null, or{ amount, payer: "merchant" | "customer", collector }. Alwaysnullin unique-amount mode and when no collector is configured.amount_net: what the project wallet receives for this invoice:amount_paid(oramount_duebefore payment) minus the network fee. Equal toamount_due/amount_paidwhennetwork_feeisnull.sweep.amount_sweptis what reached the wallet;sweep.fee_paidwhat reached the collector.forwardergainsversion,collector,fee_tokenandfee_units(the uint256 for a manual flush).
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.
- Forwarder invoices that existed before migration 6 are marked
forwarder_version = 1. Payments to them are still detected and settled as before. The sweeper never flushes them: they getsweep_status = 'skipped'with "this deposit address belongs to the previous contract version; flush it by hand through its factory". Sweep now, force and Recover answer409 legacy_forwarder. Their funds stay safe at the address and can be moved by anyone with the v1 factory'sflush(destination, salt, token)on Tronscan (contracts/README.md). - A v1 factory fails v2 verification (different code, no
VERSION()), so nothing is derived from it. After upgrading, deploy a v2 factory (deploy-factory --network <n> --force) and setFORWARDER_FACTORY_<NETWORK>to it. Forwarder projects that still pointed at a v1 factory are moved to the configured v2 factory when it verifies. Until then their invoice creation answers503 forwarder_unavailable. - At the time of this change no v1 invoice had been paid, so no funds sit at v1 addresses.
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:
- The invoice JSON and webhooks:
forwarder.collector,forwarder.fee_token,forwarder.fee_units. Stores that saveforwarderwith the order have everything. npm run admin -- forwardersprints them per invoice (collector,fee_token,fee_units).- Without any record:
recover-forwardertakes--collector T…and--fee <amount>and defaults toFEE_COLLECTOR_ADDRESSandSWEEP_FEE_DEFAULTfrom the environment;--fee 0derives 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
test/contracts.test.ts: fee taken once across many flushes (USDT that returnsfalseand a plain ERC-20), the cap across addresses and callers, the dust rule atfee - 1,feeandfee + 1, collector / fee / fee token / destination immutable, fee only in the fee token (other tokens and TRX whole to the destination), collector that cannot receive, destination that cannot receive, lying token, re-entrancy during the fee transfer, direct calls to a clone, bad fee terms,feesPaid, gas bounds.test/create2.test.ts: v2 vectors, every bound value changes the address, canonical-terms validation.test/verify-factory.test.ts: all eight immutable references of the factory are checked.test/forwarders.test.ts: merchant-pays and customer-pays flows with webhook and JSON fields, checkout line in English and Arabic, the fee charged once across partial, top-up and overpayment, dust hold and admin force, third-party flush with fee sync, failing fee lens, blocked collector, fees off without a collector, unique-amount mode unaffected, admin-only settings, collector never a project wallet, the admin fee report and recommendation, v1 invoices and the v5 to v6 migration, config validation and per-network fee keys.test/flow.test.ts:network_fee: nullandamount_netin unique-amount mode.
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
- 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
forwarderobject. 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). - 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).
- 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
pendingand the money sat at an address the gateway believed empty; one final scan at expiry was the only retry. Added the invariantbalance = received − swept, a backoff cadence and a health counter. - 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. - 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 needSWEEP_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. forceis admin-only (7.5, 8.2). The sweep route is reachable with an API key and by members.forcelet them spend the operator's fee wallet to move dust.- 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.
- 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 < outstandingheld permanently and the invoice stayedqueued. After 10 minutes the chain wins and the books are corrected. - 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_limitof2^32 + xasx, 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 usesBigInt. The signer checks at run time that an object really passed verification, since a type brand can be cast away. The lower bound onexpirationagainst the server clock was dropped (harmless to sign, and clock skew would have stopped all sweeps silently). - 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.
txStatusreads the amount only from theFlushedlog of the expected factory, forwarder and token (3.5). "The factory's Flushed log" was not specific enough onceflushManyor a re-entering token can emit several.- 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.
- 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.
- 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.
- Zero-value transfers are ignored, and unconfirmed transfers stop counting after 30 minutes (6.2, 6.3). USDT
allows zero-value
transferandtransferFromto any address (address poisoning), which would have filled the table and the history. An unconfirmed transfer that never confirmed keptamount_detectedhigh forever. - 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.
- No automatic settlement of an expired invoice whose order was already paid through a re-issued invoice; Accept
needs
forcefor underpaid, late and duplicate payments (6.2, 8.2, T23). Forwarder mode has no time limit onexpired → paid, so this case is more likely than in amount mode, and it would send a secondinvoice.paidfor one order. - 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.
- 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.
- 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.
- 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.
- Amount-mode isolation spelled out (4).
assignTransferrefuses forwarder invoices explicitly, and a test migrates a v4 database file and settles an old invoice.
Checked and left as it was
- The 0x41 CREATE2 formula, all EIP-1014, TVM, SunSwap and forwarder vectors, the key vectors, every selector and event
topic, the fixture
txID, its signature and the deploy-address formula: recomputed independently, all correct. - Both contracts compile as printed with solc 0.8.19 / london, without
PUSH0,SELFDESTRUCTor (in the forwarder)DELEGATECALL. The balance-delta check for USDT's false return value, the destination binding throughkeccak256(abi.encode(destination, salt)), the stateless clone and the constructor's prefix probe are sound. - Migration v5 (with the added column) applies to a v4 database and leaves existing rows in amount mode.
- Settlement uses only confirmed transfers of the configured TRC-20 contract. Nothing in the sweep path can change an invoice's status.
For the owner to decide
- Defaults:
SWEEP_STRAY_MIN_AMOUNT = 10,SWEEP_PROJECT_DAILY_BUDGET_TRX = 1000,FORWARDER_MAX_OPEN_INVOICES = 2000. They are chosen to be safe for a small install; a busy store raises the budget. - Public salts (item 1) trade secrecy that nothing needs for recovery without the database. If early flushes by
strangers are ever unwanted for a reason not seen here, the alternative is
HMAC(server secret, invoice id), which keeps recovery but adds a secret that must be backed up. - The server cannot tell whether a project wallet is an exchange address (item 19). The notice is the only defence.
Deviations (signer / RPC stage)
Small departures from section 3, made while implementing abi.ts, rpc.ts, tx.ts and signer.ts:
buildDeployandverifyDeployTxtake an explicitoriginEnergyLimit. Section 3.3 requiresorigin_energy_limitto equal "what we asked", but the printed signatures had no parameter for it.verifyTriggerTxdoes not readforwarder_factories(it has no database). Check 4's factory membership is the caller's job (TronForwarderChain). The selector allow-list is built in and can be narrowed withallowedSelectors.verifyDeployTxtreatsSmartContract.abi(field 3) as opaque bytes: it is metadata, and its entries are a repeated field. Every other level is decoded strictly.TronRpcgains the optionsretryDelaysMsandnow(tests), andlatestBlock(solid)(getnowblock), whichForwarderChain.solidTimeneeds.broadcast: besides the codes in the table, an unknown code, any HTTP error and any transport error areretryable: true(fate unknown). This only delays a rebuild until the expiration passes. A{ "Error": … }body (the node could not parse the request) isnode_error,retryable: false.- Key loading (
parsePrivateKeyHex,loadPrivateKey({ key, file })) lives insigner.tsforconfig.tsto call. Error messages never include the key. abi.ts:encodeAddressArray/encodeBytes32Arrayreturn only the tail (length, items);encodeArgswrites the head offsets, so a dynamic argument can sit anywhere in the argument list.
Deviations (integration stage)
Departures from sections 3 to 10, made while wiring forwarder mode into the app:
ForwarderChaingainsforwarderAddressOnChain(q)(thedestinationrequirement check reads the on-chain derivation through the port instead of a raw RPC call).FlushEstimate.energyPriceSunandFeeWalletStatus.energyPriceSunwere added so the sweeper can compute the fee limit (clamp(floor((energy × 13 + 9) / 10) × price, 1 TRX, SWEEP_FEE_LIMIT_TRX)) without a second RPC call.TxStatus.failedcarriesenergyUsedtoo, for thesweep_txsrecord.InvoiceService.useForwarders(forwarders)is a setter rather than a constructor argument (the service is built before the chain port inbuildApp).PaymentWatchertakes the chain as an optional 8th constructor argument.- Tests:
setup(env, { forwarder: true })instead ofsetup({ forwarder: true }). The forwarder-mode flow tests live intest/forwarders.test.ts, not indescribe("forwarder mode")blocks intest/flow.test.ts(the file is already long).AGENTS.mdnamestest/forwarders.test.tsaccordingly. - The watcher settles a deposit invoice once per history scan (after all new transfers of that address are recorded), not once per transfer. The outcome is the same; it saves repeated status transitions.
/healthreportssweeper { enabled, ok, queued, in_flight, failed, held }but not the sweeper's last error (it may name addresses and node errors; admins see it in the dashboard). The HTTP status still depends on the watcher only.- A member's
PATCH /settingswithdeposit_modeanswers 400, not 403: the member settings schema is strict and rejects the unknown key first, the same as formerchant_addresstoday. sweep_status = 'skipped'is shown as held in the dashboard, with "N USDT held at the deposit address" as the tooltip; Sweep now (with an admin's force belowSWEEP_MIN_AMOUNT) moves it.- CLI: the
forwardersCSV addssweep_statusandnetworkcolumns.recover-forwarderprints a balance only for tokens (the lens reads TRC-20 balances), verifies the factory on-chain before deriving anything, and only lets the signer flush through that one factory.fee-wallet newneeds no configuration or database.
Deviations (review fixes)
- Factory verification (5.4) gained steps 6 and 7. A factory whose
deploy()copy ofimplementationwas patched passed every getter and probe, and no clone could ever be deployed at its addresses. The artifact gainedimmutables(references grouped per variable) for this.test/verify-factory.test.tsruns the real contracts on@ethereumjs/evmwith CREATE2 switched to the0x41preimage. B == 0in the sweeper (7.3) needs a head-state reading of 0 while the newest confirmed transfer may be unsolidified (10 minutes). A lagging solidity node otherwise got a fresh payment recorded as "flushed by someone else". As a safety net, the sweeper reopens an invoice marked swept withsweep_tx_id = NULLwhen the lens still sees more at the address than the books leave there 15 minutes later (amount_swept = received − balance, thenreconcile).- Receipts are applied once.
onSuccess,onFailedandonDroppedclaim thesweep_txsrow with a status guard and re-read the invoice inside the transaction (the server tick and the CLI'ssweepAndWaitcan hold the same stale row). Adroppedtransaction that landed after all credits at most what the books do not yet explain, since the attempts after it already booked the emptied address. - Requirements checklist is cached per (project, network, wallet, factory) for 60 s with in-flight
de-duplication; enabling the mode (admin) skips the cache. The invoice list polls
?requirements=0, which makes no chain call. - Fee key per network. TRON transactions have no chain id.
sharedFeeKeyWarninglogs a warning at startup when one fee key is set up with factories for mainnet and a testnet;SECURITY.mdand the deploy skill require a separate testnet key. Per-network key variables were not added: the single fee payer address runs through the config, health and dashboard, and separate instances per network are the recommended setup anyway. - Checkout shows every significant decimal of a forwarder amount (
10.555, not10.55).