Repository navigation
feat(cli): decdn node earnings prints settled and owed USDC per period - #2623
Merged
Merged
Conversation
An operator can ask their node what it has earned. The daemon keeps a forward-only settlement ledger (`settlement_ledger_v1` in `settle.redb`): one row per landed `redeemMany`, decoded from the receipt — gross, bytes and epoch from `FeeRouter.Settled`, the exact net from the USDC transfer to the operator, the block's timestamp. The redeemer writes the row when its receipt lands; the `PoolRedeemed` watcher backfills a row for a landing it never saw. The ledger drops with the other seller tables on a repoint. `admin_v1_earnings` sums the ledger over the last 24 hours, the last 7 days and the whole ledger (plus one `since` period), reports the last settlement in chain order, and the pending total as `owed − paid_cumulative` over the lanes with the redeemer's published next sweep. `LaneSnapshot` gains `unredeemed_micro_usdc`, which `node lanes` shows as `UNREDEEMED`. `decdn node earnings` renders the response, or with `--address` builds the same table from the chain alone: a windowed `FeeRouter.Settled` scan for the operator from the deployment's L2 block, net reconstructed from the `SharesUpdated` history, period cutoffs by binary search over block times. The window-halving primitives move from the node's poller into `decdn_incentive::log_scan` so both scans learn a provider's range cap the same way. `node status` appends an `earnings …` line and `setup` closes with `earned_so_far=` when a daemon answers. Closes #2598 Co-Authored-By: Claude Fable 5.1 <[email protected]>
… covers Review follow-ups on `decdn node earnings` (#2598): - A `redeemMany` that paid nothing lands with no `Settled` and no `PoolRedeemed`; the ledger now treats that as "nothing routed" at debug instead of warning, and any other receipt that yields no row is a typed `DecodeError` (undecodable `Settled` or `Transfer`, no log index, no `Settled` for this operator), logged and counted. - The row's block time comes from the receipt's logs when the RPC supplies it, else a retried header read; on the watcher's backfill a time the RPC cannot supply skips the row rather than stamping an old settlement into "last 24h". Two counters make a ledger that stops growing visible: `decdn_settlement_ledger_write_failures_total` and `decdn_settlement_ledger_skipped_rows_total`. - `has_settlement_tx` reads one block's rows, not the whole ledger, and the sink backfills after its watermark writes. - `admin_v1_earnings` carries named periods (`last_24h`, `last_7d`, `since_ledger_start`, optional `since`) instead of a labelled list, and `pending` splits what the next sweep can redeem (this operator's lanes with a live capability) from what is stranded. The CLI row label says "(ledger from <date>)" when a period starts before the ledger does. - Chain mode fails on a log that does not decode instead of printing a clean empty table, reads the fee split in force before the first in-range `SharesUpdated` with a block-tagged `getShares()`, checks the RPC's chain id and `--from-block` against head, throttles progress, and `scan_logs` retries a transient window failure with the last scanned block in its error. - `node status` prints `earnings=ok …` with an RFC 3339 token, or `earnings=unavailable reason=…`; `--since` refuses a bare integer before 2000 (a date without its dashes). - Docs: the recovery note no longer claims `settle.redb` holds only the ledger; the runbook gains the corrupt-row entry and the exact `--address` command for an old deployment. Co-Authored-By: Claude Fable 5.1 <[email protected]>
A `redeemMany` that paid nothing lands with no logs and gets no ledger row, so it must cost no header read: on a stalled RPC that read blocked the redeemer for the call timeout, three times over. The recorder now decodes first and stamps the time only when there is a row to stamp, and the backfill's receipt read retries like the header read. Also from the re-review: a settlement earlier in the same block as the first in-range `SharesUpdated` is priced under the split in force before it; `scan_logs` reports each retry to its caller (the CLI prints them) and warns through tracing; `decdn setup` prints `earned_so_far=unavailable reason=…` when a daemon answered with an error instead of silence; `blockchain.get_logs_max_block_span = 0` is refused in chain mode as the daemon refuses it; the earnings handler's log line no longer names the wrong store. Tests: the Landed arm of `submit_chunk` writes a row through the scripted transport; a zero-pay landing reads no header; `scan_rows` prices a pre-change settlement, in and before the change block, under the historical split; a known transaction's second backfill makes no request. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The settlement ledger's two redb read paths share one table opener and one row decoder; the recorder's two blocking ledger calls share one error flattening; the memory ledger's three lock sites share one; the earnings response's pending split, the CLI's pending lines, the chain scan's two progress closures and the civil-time hour arithmetic each have a named function. Output, wire shapes and signatures other crates use are unchanged. The retry message `scan_logs` logs and reports is redacted through `sanitize_err_chain`: a transport error can echo the RPC URL, and an RPC URL commonly carries an API key. Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Earnings attribution and historical pricing can be incorrect, while blocking RPC reads can stall scans and shared event processing.
5 open issues
Pin share pricing and fallback logs to the scanned snapshot · New Track operator identity when storing and aggregating receipts · New Prevent serial backfills from blocking shared event processing · New Add finite timeouts to get_logs attempts · New Republish next-sweep time after merging an earlier hint cutoff · New
What changed in this PR
Adds operator earnings reporting to the CLI, backed by a daemon settlement ledger or a chain-only scan, addressing #2598 without requiring a dashboard.
Changes:
- Adds
node earningswith period totals, JSON output, custom start dates and chain-only lookup. - Records settlements and exposes pending amounts, stranded value and sweep timing through admin RPC.
- Adds earnings summaries to status/setup, shared scan helpers, tests and operator documentation.
| File | Description |
|---|---|
| README.md | Adds earnings to the operator command examples. |
| docs/runbook.md | Documents ledger recovery and old-deployment lookup. |
| crates/node/tests/anvil_settlement_e2e.rs | Checks landed settlements and receipt backfill. |
| crates/node/src/settlement_ledger/tests.rs | Tests decoding, timestamps and recorder failures. |
| crates/node/src/settlement_ledger.rs | Decodes receipts and records settlement rows. |
| crates/node/src/runtime/mod.rs | Wires ledger and schedule handles into services. |
| crates/node/src/pool_store/tests.rs | Tests ledger persistence, ordering and corruption handling. |
| crates/node/src/pool_store.rs | Adds persistent settlement storage. |
| crates/node/src/payment_settlement/tests.rs | Tests schedule publication and landed ledger writes. |
| crates/node/src/payment_settlement.rs | Integrates recording, backfill and sweep schedules. |
| crates/node/src/metrics.rs | Adds ledger failure counters. |
| crates/node/src/lib.rs | Exposes the settlement ledger module. |
| crates/node/src/chain_events/multiplexed_poller/tests.rs | Updates the shared scan-helper import. |
| crates/node/src/chain_events/multiplexed_poller.rs | Uses shared range-rejection detection. |
| crates/node/src/chain_events/mod.rs | Re-exports shared scan helpers. |
| crates/node/src/chain_events/backfill.rs | Delegates windowing to the incentive crate. |
| crates/node/src/admin/tests.rs | Tests periods and pending/stranded totals. |
| crates/node/src/admin.rs | Implements earnings RPC and unredeemed lane values. |
| crates/incentive/src/store/tests.rs | Tests in-memory ledger behavior. |
| crates/incentive/src/store.rs | Defines settlement records and ledger interfaces. |
| crates/incentive/src/payment_pool/tests.rs | Checks settlement and transfer event signatures. |
| crates/incentive/src/payment_pool.rs | Adds the settlement event binding. |
| crates/incentive/src/log_scan/tests.rs | Tests adaptive scanning and retries. |
| crates/incentive/src/log_scan.rs | Provides reusable windowed log scanning. |
| crates/incentive/src/lib.rs | Exposes earnings, scanning and ledger APIs. |
| crates/incentive/src/erc20.rs | Adds the transfer event binding. |
| crates/incentive/src/earnings/tests.rs | Tests totals and latest-settlement selection. |
| crates/incentive/src/earnings.rs | Shares settlement aggregation between producers. |
| crates/common/src/cli/node.rs | Defines earnings command arguments. |
| crates/common/src/cli/mod.rs | Exports earnings arguments. |
| crates/common/src/admin/tests.rs | Updates lane serialization fixtures. |
| crates/common/src/admin.rs | Defines earnings RPC types and method. |
| crates/cli/tests/admin_rpc.rs | Tests earnings RPC responses and unavailable state. |
| crates/cli/src/known_chains.rs | Adds deployment L2 scan-start metadata. |
| crates/cli/src/commands/setup/tests.rs | Tests earnings in setup JSON. |
| crates/cli/src/commands/setup.rs | Includes earnings in setup’s closing output. |
| crates/cli/src/commands/node/tests.rs | Tests earnings rendering and summaries. |
| crates/cli/src/commands/node/earnings_chain/tests.rs | Tests historical pricing and scan coordinates. |
| crates/cli/src/commands/node.rs | Adds earnings dispatch, output and status integration. |
| crates/cli/src/commands/mod.rs | Registers shared date helpers. |
| crates/cli/src/commands/civil_time/tests.rs | Tests UTC formatting and date parsing. |
| crates/cli/src/commands/civil_time.rs | Provides date arithmetic and --since parsing. |
| crates/cli/src/commands/chain_ctx/tests.rs | Updates configuration fixtures. |
| crates/cli/src/commands/chain_ctx.rs | Exposes chain-only scan configuration. |
| crates/cli/src/commands/bundle_pull.rs | Shares byte-count formatting. |
| CONTRIBUTING.md | Documents L2 scan-start updates after redeployment. |
| CHANGELOG.md | Records earnings reporting and admin changes. |
Review effort: Balanced
Code coverage overviewLanguages: Rust Rust / code-coverage/cargo-llvm-cov
View coverage of the 10 most impacted files.
ℹ️ Calculations represent line coverage. Results may change as calculations are updated. Updated |
…ller's task From the PR review: - Each ledger row carries `FeeRouter.Settled.operator`, and the earnings figures sum only the current operator's rows. The ledger outlives `decdn node rotate-key eth`, which keeps the data directory, so an earlier address's rows stay in the file but out of the table, the "since" date and the last settlement. - The watcher's backfill runs on its own task behind a four-permit semaphore. The poller applies logs to every route in turn, so a receipt or header read that waits out its timeout no longer holds up the paid watermarks, the blacklist or the slash watcher. - A hint that pulls the next serve cutoff forward republishes the next sweep time. - Chain mode bounds every RPC read at 30 s (the read-only provider sets no request timeout), `scan_logs` bounds each `eth_getLogs` attempt and sends an elapsed deadline down the retry path, and the fallback `getShares()` is read at the scan's last block so a retune during the scan cannot price earlier rows. Co-Authored-By: Claude Fable 5.1 <[email protected]>
…mon's error Review round three on #2623. - `LedgerBackfills` owns the backfill tasks: a `JoinSet` behind the four-permit semaphore, reaped on every spawn (a panic is logged and counted as a skipped row) and drained by `PoolSettlementService::shutdown` within what is left of the shutdown deadline, so a stop mid-catch-up no longer loses the rows the poller's checkpoint has already moved past. Once the drain has begun a spawn is refused, logged and counted: the poller can still be applying a window while the service shuts down. A closed semaphore is logged and counted instead of returning silently. - `node status` and `setup` render a daemon's JSON-RPC error through `classify_client_error`, as its code and message, not the `ErrorObject` debug form. `setup` stays silent only on a refused connection; a timeout, a response that does not decode or an admin URL that does not resolve now print `earned_so_far=unavailable reason=…`. - The redeemer's own header read makes one attempt before the wall-clock stamp; the three attempts stay on the backfill path, where the fallback is no row. - `LaneState::unredeemed()` replaces the three `owed − paid_cumulative` copies in the admin surface and the rebind forfeit. - Chain mode: the `SharesUpdated` retry line carries the error and the delay like the `Settled` one, and a scan that gives up names the window span and the two levers. - Docs: `RedeemSchedule` and `PendingRedeem::next_sweep_at_unix` say a hint republishes; the pending figure's docs name the redeem floor; the runbook no longer points at a `decdn_pending_settle_*` metric or a `node pools` view that does not exist; the ledger trait says what the key guarantees under a reorg; the retry-delay and `--since` docs match the code; the CHANGELOG flags the `LaneSnapshot` field under Changed (BREAKING). - Tests: the hint republish, the backfill off-task run (three attempts at the call timeout on the paused clock), the drain (waits, aborts at the deadline, refuses a late spawn), the reap, `shutdown` draining a backfill, `earned_so_far` on an accepted-but-silent listener and on a refused one, the single header attempt, a settlement at the exact cutoff second on both producers, and `l2_start_block` above the manifest's L1 `deployBlock`. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Merged
7 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


What
An operator can ask their node what it has earned.
decdn node earningsprints one row per period (the last 24 hours, the last 7 days, and since the node's settlement ledger started) with the USDC the operator received, the bytes those settlements paid for and the settlement count, then the last settlement (time, tx, block), the pending line (what the lanes still owe and when the next redeem sweep is due) and a stranded line when value sits on lanes no sweep redeems.--jsonprints theadmin_v1_earningsresponse,--since <YYYY-MM-DD|unix>adds a period, and--address <0x…>builds the same table from the chain alone (no daemon, no pending line).Behind it:
settlement_ledger_v1insettle.redb): one row per landedredeemMany, decoded from the receipt — gross, bytes and epoch fromFeeRouter.Settled, the exact net from the USDC transfer to the operator, the block's timestamp. The redeemer writes the row when its receipt lands; thePoolRedeemedwatcher backfills a row for a landing it never saw. AredeemManythat paid nothing gets no row and costs no header read. Nothing is backfilled from before the ledger exists, so the bottom row readssince <date>, never "all time"; a period that starts earlier says "(ledger from )". The ledger drops with the other seller tables on aPaymentPoolrepoint.admin_v1_earnings: named periods, the last settlement in chain order, andpendingsplit into what the next sweep can redeem (this operator's lanes with a live capability) and what is stranded.LaneSnapshotgainsunredeemed_micro_usdc(owed − paid_cumulative), shown bynode lanesasUNREDEEMED. The redeemer publishes its sweep schedule.FeeRouter.Settledscan for the operator from the deployment's L2 block (l2_start_blockinknown_chains.rs; the manifest'sdeployBlockis an L1 number), the net reconstructed from theSharesUpdatedhistory (the split before the first in-range change read with a block-taggedgetShares()), period cutoffs by binary search over block times. A log that does not decode fails the command. The window-halving primitives move from the node's poller intodecdn_incentive::log_scan, with transient-failure retries; the CLI prints progress and retries to stderr.decdn_settlement_ledger_write_failures_totalanddecdn_settlement_ledger_skipped_rows_total.decdn node statusappendsearnings=ok …/earnings=unavailable reason=…;decdn setupcloses withearned_so_far=when a daemon answers.Closes #2598
Breaking
Pre-mainnet, admin wire only:
LaneSnapshotgains a field andadmin_v1_earningsis new. No storage, config or contract change; the new redb table is additive and absent until the first redeem lands after upgrade.Reviewer notes
Read first:
crates/node/src/settlement_ledger.rs(receipt decoder and the two writers), thencrates/node/src/admin.rsbuild_earnings_response/pending_redeem, thencrates/cli/src/commands/node/earnings_chain.rsfor the chain-only path.Stays unchanged on purpose:
Settled.amountis gross; the operator's net is the USDC transfer in the same receipt, and in chain mode the split in force at that log. The fee split is governance-tunable, so nothing hard-codes 60/30/10 (the anvil fixture deploys 90/0/10).settle.redbwith both pending-settle sets; the runbook gained an entry for a row that does not decode and the exact--addresscommand for an old deployment.Risk:
--addresson an RPC that capseth_getLogswindows (the free tiers do) is slow by nature;--from-blockshortens it and the scan error names the last scanned block.Five commits: the feature, then two rounds of review fixes (
/pr-review-toolkit:review-prwith all five agents, then the error-handling and test re-review), then the simplifier pass plus a redaction of the scan retry message, then a third review round: ledger backfills are held in aJoinSet(LedgerBackfills) that shutdown drains and that refuses a late spawn, so a stop mid-catch-up no longer loses rows;node statusandsetuprender a daemon's JSON-RPC error as its code and message, andsetupstays silent only on a refused connection; the redeemer's header read makes one attempt before the wall-clock stamp;LaneState::unredeemed(); theLaneSnapshotfield is flagged under Changed (BREAKING); the runbook no longer names metrics that do not exist. The coverage-start label gap is #2624.Verification
Always:
pre-commit run --all-files— passed (cargo-deny findings are the pre-existing non-blocking advisories)CARGO_BUILD_WARNINGS=deny cargo clippy --workspace --all-targets --all-features— cleancargo nextest run— 3721 passed across incentive, common, cli, node, e2e (one unrelated pre-existing loopback flake retried green)cargo nextest run -p decdn-node -p decdn-cli -p decdn-incentive -p decdn-common— 3691 passed; six of the new tests mutation-checked by hand (hint republish, drain body, drain call inshutdown, reap inspawn, single header attempt, reap-test race), every mutation killedOnly if touched:
cargo nextest run -p decdn-node --features anvil-e2e --test anvil_settlement_e2e— 4 passed; the settlement e2e asserts two ledger rows for two redeems,net == gross − bucketsunder the livegetShares(), and a backfilled row equal to the redeemer's rowCARGO_BUILD_WARNINGS=deny cargo doc --workspace --no-deps --document-private-items— clean.github/scripts/check-crate-edges.sh— no edge change (the lifted helpers live indecdn-incentive, already a dependency of bothnodeandcli)adr/appendix-observability.mdrow (the appendix lists a subset, likedecdn_watcher_persist_failures_total); devops dashboards untouched, a follow-up if an alert is wantedCHANGELOG.mdentry under Added🤖 Generated with Claude Code