Skip to content

feat(cli): decdn node earnings prints settled and owed USDC per period - #2623

Merged
thiras merged 6 commits into
mainfrom
feat/node-earnings
Oct 25, 2026
Merged

thiras merged 6 commits into
mainfrom
feat/node-earnings

Conversation

@thiras

@thiras thiras commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What

An operator can ask their node what it has earned. decdn node earnings prints 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. --json prints the admin_v1_earnings response, --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:

  • A forward-only settlement ledger in the daemon (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. A redeemMany that paid nothing gets no row and costs no header read. Nothing is backfilled from before the ledger exists, so the bottom row reads since <date>, never "all time"; a period that starts earlier says "(ledger from )". The ledger drops with the other seller tables on a PaymentPool repoint.
  • admin_v1_earnings: named periods, the last settlement in chain order, and pending split into what the next sweep can redeem (this operator's lanes with a live capability) and what is stranded. LaneSnapshot gains unredeemed_micro_usdc (owed − paid_cumulative), shown by node lanes as UNREDEEMED. The redeemer publishes its sweep schedule.
  • Chain mode: a windowed FeeRouter.Settled scan for the operator from the deployment's L2 block (l2_start_block in known_chains.rs; the manifest's deployBlock is an L1 number), the net reconstructed from the SharesUpdated history (the split before the first in-range change read with a block-tagged getShares()), 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 into decdn_incentive::log_scan, with transient-failure retries; the CLI prints progress and retries to stderr.
  • Two counters, decdn_settlement_ledger_write_failures_total and decdn_settlement_ledger_skipped_rows_total. decdn node status appends earnings=ok … / earnings=unavailable reason=…; decdn setup closes with earned_so_far= when a daemon answers.

Closes #2598

Breaking

Pre-mainnet, admin wire only: LaneSnapshot gains a field and admin_v1_earnings is 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), then crates/node/src/admin.rs build_earnings_response / pending_redeem, then crates/cli/src/commands/node/earnings_chain.rs for the chain-only path.

Stays unchanged on purpose:

  • Settled.amount is 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).
  • The pending figure applies the planner's two local predicates (provider, capability expiry) but not the pool-state ones, so it is an upper bound; the DTO doc says so.
  • The ledger shares settle.redb with both pending-settle sets; the runbook gained an entry for a row that does not decode and the exact --address command for an old deployment.

Risk: --address on an RPC that caps eth_getLogs windows (the free tiers do) is slow by nature; --from-block shortens it and the scan error names the last scanned block.

Five commits: the feature, then two rounds of review fixes (/pr-review-toolkit:review-pr with 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 a JoinSet (LedgerBackfills) that shutdown drains and that refuses a late spawn, so a stop mid-catch-up no longer loses rows; node status and setup render a daemon's JSON-RPC error as its code and message, and setup stays silent only on a refused connection; the redeemer's header read makes one attempt before the wall-clock stamp; LaneState::unredeemed(); the LaneSnapshot field 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 — clean
  • cargo nextest run — 3721 passed across incentive, common, cli, node, e2e (one unrelated pre-existing loopback flake retried green)
  • Round three: 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 in shutdown, reap in spawn, single header attempt, reap-test race), every mutation killed
  • PR title uses an allowed type and a lowercase-initial subject

Only 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 − buckets under the live getShares(), and a backfilled row equal to the redeemer's row
  • CARGO_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 in decdn-incentive, already a dependency of both node and cli)
  • Metric names: two new counters; no adr/appendix-observability.md row (the appendix lists a subset, like decdn_watcher_persist_failures_total); devops dashboards untouched, a follow-up if an alert is wanted
  • CHANGELOG.md entry under Added

🤖 Generated with Claude Code

thiras and others added 4 commits October 25, 2026 22:29
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]>
Copilot AI balanced review requested due to automatic review settings October 25, 2026 21:03

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Earnings attribution and historical pricing can be incorrect, while blocking RPC reads can stall scans and shared event processing.

5 open issues
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 earnings with 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

Comment thread crates/node/src/admin.rs Resolved
Comment thread crates/node/src/payment_settlement.rs Resolved
Comment thread crates/incentive/src/log_scan.rs Resolved
Comment thread crates/node/src/payment_settlement.rs Resolved
@github-code-quality

github-code-quality Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Code coverage overview

Languages: Rust

Rust / code-coverage/cargo-llvm-cov

main 49526d0 feat/node-earnings 1e2cd2e +/-
77% 77% 0%
View coverage of the 10 most impacted files.
File main 49526d0 feat/node-earnings 1e2cd2e +/-
crates/node/src...t_settlement.rs 77% 76% -1%
crates/client/src/lib.rs 89% 89% 0%
crates/node/src/pool_store.rs 81% 83% +2%
crates/cli/src/...ommands/node.rs 60% 63% +3%
crates/incentive/src/store.rs 75% 80% +5%
crates/cli/src/...rnings_chain.rs 0% 72% +72%
crates/node/src...ement_ledger.rs 0% 86% +86%
crates/incentiv...src/log_scan.rs 0% 96% +96%
crates/cli/src/...s/civil_time.rs 0% 100% +100%
crates/incentiv...src/earnings.rs 0% 100% +100%

ℹ️ Calculations represent line coverage. Results may change as calculations are updated.


Updated October 25, 2026 22:49 UTC

…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]>
@thiras
thiras merged commit 74951f2 into main Oct 25, 2026
34 checks passed
@thiras
thiras deleted the feat/node-earnings branch October 25, 2026 22:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cli: decdn node earnings prints settled and owed USDC per period

2 participants