Skip to content

feat(cli): decdn setup --pay-bond-with usdc — auto-swap USDC→TOKEN bond (#991) - #1091

Merged
alpergundogdu merged 19 commits into
mainfrom
claude/wonderful-golick-057e73
Jul 11, 2026
Merged

alpergundogdu merged 19 commits into
mainfrom
claude/wonderful-golick-057e73

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #991.

What

Adds an opt-in decdn setup --pay-bond-with usdc path so a node operator can onboard holding only USDC. In USDC mode, setup acquires exactly the TOKEN the capacity bond needs via an exact-out USDC→TOKEN swap on a config-selected DEX venue, then runs the existing bond flow. The default (--pay-bond-with token, or omitted) is byte-for-byte today's behavior.

The swap target is the top-up, not the full bond:

swap_out = max(0, requiredBond − heldTOKEN)

so an operator holding some TOKEN swaps only the remainder, and a re-run after a failed bond swaps ~nothing and just retries the bond (resumable).

Why

TOKEN is an illiquid project token while USDC is trivially acquirable. Today an operator must independently source TOKEN before setup can bond — a real friction wall. The cleanest fix needs no new on-chain contract; the swap is a standard self-custodial DEX call the operator signs.

Design decisions

  • Venue-neutral, both day one. One SwapVenue abstraction (in crates/incentive) with Uniswap V3 and Balancer V3 impls, selected by chain config — Uniswap on the Arb Sepolia testnet now, Balancer where it lands later. Mirrors the venue-neutral burner (Make BuybackBurner venue-neutral and add BuybackBurnerUniswapV3 #1000/feat(contracts): venue-neutral BuybackBurner + Uniswap V3 burner #1003).
  • Slippage bounded by --max-slippage-bps (default 300) via the swap's amountInMaximum + a deadline.
  • Price-impact gate: >300 bps prints a warning and requires an extra [y/N] (skipped by --yes). Advisory, never a hard block — an operator can pre-swap and bond manually anyway.
  • Bindings in incentive, orchestration in cli.
  • ADR 019 gets a short amendment recording the optional swap primitive.

How it's wired

  • crates/incentive: swap_math (pure top-up/slippage/impact), swap_venue (SwapVenue enum + from_config), swap_uniswap (exact-out SwapRouter02/QuoterV2/slot0 bindings), swap_balancer (Balancer V3 Router + Permit2).
  • crates/cli: --pay-bond-with / --max-slippage-bps / --swap-* flags + config, and the USDC-mode branch in setup. The swap executes only after the pre-flight all_ok gate, the register-divergence guard, terms acceptance, and the operator confirmation — so a doomed run never spends USDC first. Each venue owns its own approvals.

Reviewer notes

Verification

cargo build, cargo clippy --all-targets, cargo fmt -- --check, and cargo nextest run (2116/2116) all green.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • decdn setup now supports funding the capacity bond by first performing a USDC → TOKEN exact-out swap when using --pay-bond-with usdc, then executing the bond step.
    • Added USDC swap support with configurable --max-slippage-bps and selectable swap venue (Uniswap v3 or Balancer v3) plus related swap parameters.
    • decdn setup --json readiness output now includes an optional swap section (null when no swap is needed).
  • Bug Fixes
    • Improved swap/bond preflight and confirmation flow with advisory price-impact checks and safer retry behavior.

alpergundogdu and others added 10 commits July 9, 2026 13:56
…#991)

Part A: make decdn_incentive::swap_venue::ResolvedSwap the single
canonical type. chain_ctx::resolve_swap now builds and returns it
(imported, not a CLI-local duplicate), deleting the mirror struct.

Part B: add the missing Uniswap pool address so the price-impact gate
can actually fire. New --swap-pool-address flag + blockchain.swap_pool_address
config, threaded through ResolvedSwap.pool and parsed in from_config into
UniswapV3Venue.pool (bail on malformed; None leaves the gate inert).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Wire --pay-bond-with usdc into `decdn setup`: after the bond plan and
TOKEN balance are read, USDC mode quotes and (outside dry-run) executes
an exact-out USDC→TOKEN swap for the exact bond top-up, so the existing
bond flow finds TOKEN in the wallet. Adds the pure branch helpers
swap_preflight / impact_over_threshold (constants PRICE_IMPACT_LIMIT_BPS
= 300, SWAP_DEADLINE_SECS = 120), the SwapSummary struct, and the
confirm_impact / approve_if_needed / swap_deadline helpers. The
TOKEN-mode pre-flight is guarded to run only when not swapping, and the
--json summary gains a `swap` object (null in TOKEN mode). Preflight
gains a usdc_mode flag that waives the TOKEN-balance gate when funding
comes from the swap.

Precise-capture build_provider's return (`+ use<>`) so the wallet-filled
provider is genuinely 'static and can construct the DynProvider-backed
swap venue.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
UniswapV3Venue::swap_exact_out now performs its own direct-router ERC20
approval (allowance-check-then-approve, idempotent) instead of relying on
the caller. This makes the SwapVenue contract uniform: "call swap_exact_out;
it handles approvals." Balancer's method was already self-contained. Updates
the venue doc comments to reflect the new ownership.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
In live mode the USDC->TOKEN swap previously executed during the pre-flight
reads, before the all_ok gate, register-divergence guard, terms acceptance,
and the bond confirmation — so a doomed or declined run spent real USDC first.

Split run_usdc_swap into a read-only prepare_usdc_swap (quote + USDC-balance
pre-flight + advisory price-impact confirm, no tx) that returns a PreparedSwap,
and execute the swap in run() immediately before bond::execute, after every
abort gate has cleared. Dry-run still previews the swap without sending.

The bond confirmation now covers the USDC spend: confirm() gained a swap_max_in
param and prints a swap-and-bond prompt in USDC mode. --yes still skips it. The
"nothing was submitted" message is correct again — nothing is submitted at that
gate after the reorder.

Also: drop the caller-side approve_if_needed (and the now-unused helper); each
venue owns its approvals (see the incentive commit). Size the native-gas
pre-flight higher in USDC mode via USDC_MODE_EXTRA_GAS_UNITS (300_000) to cover
the extra approve+swap txs. Token-mode behavior is unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Copilot AI review requested due to automatic review settings July 9, 2026 15:00
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Adds venue-neutral USDC-to-TOKEN swap support for decdn setup, plus swap config, quoting, execution, JSON output, and ADR updates. Separately, build_provider now uses use<> to avoid over-capturing the signer lifetime.

Changes

USDC-funded bond swap

Layer / File(s) Summary
Swap math and venue abstraction contracts
crates/incentive/src/swap_math.rs, crates/incentive/src/swap_venue.rs
Adds swap math helpers and the venue-neutral swap abstraction with resolved configuration and test-only mock behavior.
Uniswap V3 exact-out venue implementation
crates/incentive/src/swap_uniswap.rs
Adds Uniswap V3 bindings, exact-out quote/swap logic, advisory spot-price computation, and tests for the venue implementation.
Balancer V3 exact-out venue implementation
crates/incentive/src/swap_balancer.rs
Adds Balancer V3 bindings, exact-out quote/swap logic with Permit2 approvals and allowance resets, and tests for the Balancer venue.
Crate module and re-export wiring
crates/incentive/src/lib.rs
Declares the new swap modules and re-exports their public swap types and helpers from the incentive crate root.
CLI swap flags and chain config resolution
crates/common/src/cli/setup.rs, crates/common/src/cli/mod.rs, crates/common/src/cli/node.rs, crates/common/src/config/types.rs, crates/common/src/config/mod.rs, crates/cli/src/commands/chain_ctx.rs
Adds swap-related CLI arguments, config fields, and swap resolution from flags and chain config, with tests for precedence and validation.
Setup command USDC swap orchestration
crates/cli/src/commands/setup.rs
Extends decdn setup with USDC-mode preflight, swap preparation and execution, confirmation text, JSON swap output, and tests for swap-specific summary and gating behavior.
ADR documentation for USDC bond funding
adr/019-node-onboarding.md
Documents the optional USDC swap funding path in ADR 019 Phase 2, including venue selection, slippage and deadline bounding, and failure and rerun semantics.

Estimated code review effort: 4 (Complex) | ~75 minutes

Provider return-type lifetime fix

Layer / File(s) Summary
build_provider lifetime capture update
crates/client-pull/src/provider.rs
Updates the build_provider signature to add use<> and leaves the wallet, URL parsing, and HTTP connection logic unchanged.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly states the CLI setup change and the new USDC auto-swap bond flow.
Linked Issues check ✅ Passed The PR implements the opt-in USDC→TOKEN exact-out swap flow, venue selection, slippage/deadline protection, resumability, and ADR note called for in #991.
Out of Scope Changes check ✅ Passed The supporting config, provider, and re-export changes appear necessary for the new swap flow rather than unrelated scope.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/wonderful-golick-057e73

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces support for optionally funding capacity bonds via exact-out USDC→TOKEN swaps on Uniswap V3 and Balancer V3 during node onboarding. Key changes include new CLI configuration options, swap pre-flight checks, and dedicated venue implementations. Feedback from the review highlights several improvements: validating that the swap recipient matches the provider's signer address for Balancer V3, checking if stdin/stdout are terminals before interactive prompts to avoid blocking, capping the maximum slippage to prevent frontrunning, and making post-swap cleanup resets best-effort so they do not block successful swaps.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread crates/incentive/src/swap_balancer.rs Resolved
Comment thread crates/cli/src/commands/setup.rs Resolved
Comment thread crates/cli/src/commands/setup.rs Resolved
Comment thread crates/cli/src/commands/setup.rs Resolved
Comment thread crates/incentive/src/swap_balancer.rs Resolved
@github-actions

github-actions Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 80.06% (was 80.32%, ▼ 0.26%) — 44420/55483 lines

File Coverage Lines Δ
crates/cli/src/commands/chain_ctx.rs 82.88% 455/549 ▲ +12.50%
crates/cli/src/commands/setup.rs 43.98% 427/971 ▼ 3.68%
crates/client-pull/src/provider.rs 0.00% 0/13 ● 0.00%
crates/common/src/cli/node.rs 100.00% 5/5 new
crates/common/src/config/mod.rs 97.01% 6622/6826 ● 0.00%
crates/incentive/src/swap_balancer.rs 59.50% 144/242 new
crates/incentive/src/swap_math.rs 100.00% 54/54 new
crates/incentive/src/swap_uniswap.rs 58.92% 142/241 new
crates/incentive/src/swap_venue.rs 87.50% 245/280 new
History
Commit Total Δ vs base
364f90d 81.37% ▼ 0.37%
aeecffa 81.35% ▼ 0.39%
07d7506 81.35% ▼ 0.39%
8a08b87 81.35% ▼ 0.39%
e7724ac 81.43% ▼ 0.31%
6015103 80.68% ▼ 0.28%
877d9ac (HEAD) 80.06% ▼ 0.26%

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.

Pull request overview

Adds an opt-in USDC-funded onboarding flow to decdn setup, letting operators auto-swap USDC→TOKEN (exact-out) for the bond top-up before proceeding with the existing bonding + registration flow. This fits into the broader onboarding stack (ADR 019) and reuses the repo’s venue-neutral DEX direction (Uniswap V3 now, Balancer V3 later).

Changes:

  • Introduces a venue-neutral swap abstraction in crates/incentive (quote + exact-out swap) with Uniswap V3 and Balancer V3 implementations plus pure swap math helpers.
  • Extends CLI/common args to support --pay-bond-with usdc, max slippage, and swap venue/address configuration; wires a resumable “quote early, swap only after abort gates + confirmation” path into setup.
  • Updates ADR 019 with the optional USDC swap step and its operational semantics.

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
crates/incentive/src/swap_venue.rs New venue-neutral swap abstraction + config parsing into Uniswap/Balancer venues
crates/incentive/src/swap_uniswap.rs Uniswap V3 exact-out quote + swap implementation (router + quoter + optional pool slot0)
crates/incentive/src/swap_balancer.rs Balancer V3 exact-out quote + swap implementation (router + Permit2 approval flow)
crates/incentive/src/swap_math.rs Pure math helpers for top-up, max-in with slippage, and price impact
crates/incentive/src/lib.rs Exposes new swap modules/types from the incentive crate
crates/common/src/cli/setup.rs Adds --pay-bond-with and --max-slippage-bps to setup args
crates/common/src/cli/node.rs Adds swap config flags (--swap-venue, router/quoter/usdc, fee tier, pool id/address)
crates/common/src/cli/mod.rs Re-exports PayBondWith from common CLI module
crates/client-pull/src/provider.rs Adjusts provider builder RPIT capture to ensure returned provider is 'static
crates/cli/src/commands/setup.rs Implements USDC-mode setup flow (quote, preflight, confirm, then execute swap before bond)
crates/cli/src/commands/chain_ctx.rs Resolves swap config from flags/config into ResolvedSwap
adr/019-node-onboarding.md Documents the new optional USDC swap step before bond approval/deposit

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/cli/src/commands/setup.rs Resolved
Comment thread crates/common/src/cli/node.rs Resolved
Comment thread crates/cli/src/commands/chain_ctx.rs Resolved
Comment thread crates/incentive/src/swap_uniswap.rs Resolved

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (5)
crates/incentive/src/swap_balancer.rs (2)

259-275: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Leg 1 approval isn't idempotent, unlike the Uniswap venue's pattern.

UniswapV3Venue::swap_exact_out skips re-approving when allowance(recipient, router) >= max_in (documented as making re-runs cheap and idempotent). BalancerV3Venue::swap_exact_out always sends the ERC20→Permit2 approve unconditionally, even if a sufficient allowance already stands from a prior partial run. This burns extra gas on every setup re-run and is inconsistent with the resumability goal called out elsewhere in this module and in the PR objectives.

♻️ Mirror the Uniswap venue's idempotent check
-        let approve_permit2_pending = usdc
-            .approve(self.permit2, max_in)
-            .send()
-            .await
-            .context("USDC approve(Permit2) transaction failed to send")?;
-        let approve_permit2_receipt = approve_permit2_pending
-            .get_receipt()
-            .await
-            .context("USDC approve(Permit2) sent but the receipt could not be fetched")?;
-        anyhow::ensure!(
-            approve_permit2_receipt.status(),
-            "USDC approve(Permit2) reverted (tx {})",
-            approve_permit2_receipt.transaction_hash
-        );
+        let current_allowance = usdc
+            .allowance(recipient, self.permit2)
+            .call()
+            .await
+            .context("failed to read USDC allowance for Permit2")?;
+        if current_allowance < max_in {
+            let approve_permit2_pending = usdc
+                .approve(self.permit2, max_in)
+                .send()
+                .await
+                .context("USDC approve(Permit2) transaction failed to send")?;
+            let approve_permit2_receipt = approve_permit2_pending
+                .get_receipt()
+                .await
+                .context("USDC approve(Permit2) sent but the receipt could not be fetched")?;
+            anyhow::ensure!(
+                approve_permit2_receipt.status(),
+                "USDC approve(Permit2) reverted (tx {})",
+                approve_permit2_receipt.transaction_hash
+            );
+        }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/incentive/src/swap_balancer.rs` around lines 259 - 275, The Leg 1
approval in `BalancerV3Venue::swap_exact_out` is unconditional and should mirror
the idempotent allowance check used by `UniswapV3Venue::swap_exact_out`. Before
calling `usdc.approve(self.permit2, max_in)`, query the current allowance for
the USDC token to `self.permit2` and skip the approval when it is already
sufficient, so reruns of `setup` remain cheap and resumable.

246-366: 🔒 Security & Privacy | 🔵 Trivial | 🏗️ Heavy lift

Standing USDC→Permit2 approval survives a mid-flow failure.

If the flow errors out after Leg 1 (ERC20 approve to Permit2) but before or during Leg 2, the swap, or the resets, the user's wallet is left with a standing ERC20 approval to Permit2 for up to max_in — the module's own "no standing allowance survives" invariant only holds on the happy path. The module doc already acknowledges this as a "best-effort" limitation given the non-atomic, multi-transaction nature of the flow. Given this is real user funds (self-custodial USDC), consider having the resumable setup re-run path detect and clean up a stale Permit2 approval left over from a previous failed attempt, so exposure doesn't linger indefinitely across failed runs.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/incentive/src/swap_balancer.rs` around lines 246 - 366, The mid-flow
failure path in swap_exact_out can leave a stale USDC→Permit2 approval behind,
so update the resumable setup/retry path to detect and clear any prior standing
approval before starting a new attempt. Use the existing swap_exact_out flow and
the setup rerun logic to check for an outstanding ERC20 allowance to Permit2,
and proactively reset it before proceeding so failed runs do not leave lingering
exposure.
crates/incentive/src/swap_venue.rs (1)

87-110: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Misleading field name: balancer_pool_id holds an address, not an id.

The doc comment itself flags this: Despite the field name, this is parsed as an Address, not a bytes32-style value. Since this is a fresh, not-yet-widely-consumed public struct, renaming to e.g. balancer_pool_address now avoids a confusing surface for downstream cli/config consumers before the API solidifies.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/incentive/src/swap_venue.rs` around lines 87 - 110, The public
ResolvedSwap field balancer_pool_id is misleading because it stores a Balancer
V3 pool address, not an id. Rename the field to balancer_pool_address in
ResolvedSwap and update all uses in from_config, swap_venue-related parsing, and
any downstream struct construction or access sites so the public API matches the
actual value type and avoids confusing cli/config consumers.
crates/incentive/src/swap_uniswap.rs (1)

219-280: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Thread _deadline into the Uniswap route. SwapRouter02::exactOutputSingle has no per-swap expiry, but multicall(uint256 deadline, bytes[] data) does enforce a global deadline for the bundled transaction. This path currently drops _deadline, so a stuck swap can still execute later than intended. Wrap the call in a deadline-carrying multicall or remove the parameter if expiry is handled elsewhere.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/incentive/src/swap_uniswap.rs` around lines 219 - 280, The
swap_exact_out flow in SwapRouter02 currently ignores the _deadline argument, so
the transaction can remain valid longer than intended. Update swap_exact_out to
pass the deadline through a deadline-enforcing multicall wrapper around
exactOutputSingle, using the existing SwapRouter02 and build_exact_output_params
flow, or remove _deadline only if another layer already enforces expiry.
crates/common/src/cli/setup.rs (1)

67-70: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Consider bounding --max-slippage-bps.

max_slippage_bps is a u16 with no upper-bound check; a value like 20000 (200%) would defeat the purpose of the slippage bound this flag documents ("Bounds amountInMaximum"). Adding a value_parser range keeps invalid input from ever reaching the swap math.

🛡️ Proposed fix
-    #[arg(long = "max-slippage-bps", value_name = "BPS", default_value_t = 300)]
+    #[arg(
+        long = "max-slippage-bps",
+        value_name = "BPS",
+        default_value_t = 300,
+        value_parser = clap::value_parser!(u16).range(0..=10_000)
+    )]
     pub max_slippage_bps: u16,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/common/src/cli/setup.rs` around lines 67 - 70, The
`SetupArgs::max_slippage_bps` CLI field accepts any `u16`, so invalid values can
bypass the intended slippage cap; add a bounded `value_parser` on the
`#[arg(...)]` for `--max-slippage-bps` to reject out-of-range input before it
reaches the swap logic. Keep the check aligned with the existing
`default_value_t` and the `Bounds amountInMaximum` behavior so the parser
enforces a sensible upper limit at the `max_slippage_bps` field definition.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/cli/src/commands/setup.rs`:
- Around line 274-305: The USDC swap preflight is running too early and is not
part of the dry-run gate, so it can bail or prompt before the report is printed.
Thread the result of prepare_usdc_swap() into Preflight/funding_ok() in
setup.rs, and make the dry-run path enforce that preflight only after the full
report logic has been reached. Keep the USDC-specific behavior isolated in
prepare_usdc_swap() and the Preflight struct/methods so USDC mode still skips
the token-balance check without blocking --dry-run.

In `@crates/common/src/cli/node.rs`:
- Around line 571-573: Update the help text for the swap_pool_id CLI option so
it describes an address instead of a bytes32 hex value. The field is the
swap_pool_id argument in the node CLI definition, and the wording should match
the Address parsing used by swap_venue::Balancer handling so users are guided to
the correct input format.

---

Nitpick comments:
In `@crates/common/src/cli/setup.rs`:
- Around line 67-70: The `SetupArgs::max_slippage_bps` CLI field accepts any
`u16`, so invalid values can bypass the intended slippage cap; add a bounded
`value_parser` on the `#[arg(...)]` for `--max-slippage-bps` to reject
out-of-range input before it reaches the swap logic. Keep the check aligned with
the existing `default_value_t` and the `Bounds amountInMaximum` behavior so the
parser enforces a sensible upper limit at the `max_slippage_bps` field
definition.

In `@crates/incentive/src/swap_balancer.rs`:
- Around line 259-275: The Leg 1 approval in `BalancerV3Venue::swap_exact_out`
is unconditional and should mirror the idempotent allowance check used by
`UniswapV3Venue::swap_exact_out`. Before calling `usdc.approve(self.permit2,
max_in)`, query the current allowance for the USDC token to `self.permit2` and
skip the approval when it is already sufficient, so reruns of `setup` remain
cheap and resumable.
- Around line 246-366: The mid-flow failure path in swap_exact_out can leave a
stale USDC→Permit2 approval behind, so update the resumable setup/retry path to
detect and clear any prior standing approval before starting a new attempt. Use
the existing swap_exact_out flow and the setup rerun logic to check for an
outstanding ERC20 allowance to Permit2, and proactively reset it before
proceeding so failed runs do not leave lingering exposure.

In `@crates/incentive/src/swap_uniswap.rs`:
- Around line 219-280: The swap_exact_out flow in SwapRouter02 currently ignores
the _deadline argument, so the transaction can remain valid longer than
intended. Update swap_exact_out to pass the deadline through a
deadline-enforcing multicall wrapper around exactOutputSingle, using the
existing SwapRouter02 and build_exact_output_params flow, or remove _deadline
only if another layer already enforces expiry.

In `@crates/incentive/src/swap_venue.rs`:
- Around line 87-110: The public ResolvedSwap field balancer_pool_id is
misleading because it stores a Balancer V3 pool address, not an id. Rename the
field to balancer_pool_address in ResolvedSwap and update all uses in
from_config, swap_venue-related parsing, and any downstream struct construction
or access sites so the public API matches the actual value type and avoids
confusing cli/config consumers.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 8a139f4f-2f5e-4b87-92d1-3f57c8419626

📥 Commits

Reviewing files that changed from the base of the PR and between 15ec8a3 and 364f90d.

📒 Files selected for processing (12)
  • adr/019-node-onboarding.md
  • crates/cli/src/commands/chain_ctx.rs
  • crates/cli/src/commands/setup.rs
  • crates/client-pull/src/provider.rs
  • crates/common/src/cli/mod.rs
  • crates/common/src/cli/node.rs
  • crates/common/src/cli/setup.rs
  • crates/incentive/src/lib.rs
  • crates/incentive/src/swap_balancer.rs
  • crates/incentive/src/swap_math.rs
  • crates/incentive/src/swap_uniswap.rs
  • crates/incentive/src/swap_venue.rs

Comment thread crates/cli/src/commands/setup.rs Resolved
Comment thread crates/common/src/cli/node.rs Resolved
alpergundogdu and others added 4 commits July 9, 2026 16:19
…991)

Cross-crate fix wave for external review feedback on the USDC bond-funding
swap path. The from_config signature change is atomic across incentive
(venues) and cli (call site), so both land together.

incentive:
- from_config gains `payer: Address`, threaded into both UniswapV3Venue and
  BalancerV3Venue (new struct field + `new` param).
- UniswapV3Venue::swap_exact_out reads `allowance(self.payer, router)` rather
  than `allowance(recipient, router)` — the router pulls USDC from the payer,
  which equals recipient only when they coincide. exactOutputSingle still
  honors an arbitrary recipient.
- BalancerV3Venue::swap_exact_out rejects `recipient != self.payer` up front:
  Balancer V3 has no recipient slot (output settles to the signer), so a
  divergent recipient would silently misroute. Adds a unit test for this.
- The two post-swap allowance resets (Permit2 approve→0, USDC approve→0) are
  now best-effort: the swap already succeeded, so a failed reset warns via
  tracing and continues instead of aborting onboarding / misreporting a swap
  failure. The approve/swap legs still propagate errors.

cli (setup):
- Pass `operator` (= signer address) as the payer at the from_config call site.
- confirm / confirm_impact return false up front when stdin or stdout is not a
  TTY, so a redirected run fails fast instead of blocking on an invisible
  prompt (outcome unchanged: it already read EOF → abort).
- Cap `--max-slippage-bps` at 10000 (100%) on the USDC-mode path only; a
  fat-finger like 65535 otherwise set a ~7.5x spend ceiling. Token mode is
  untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ent Balancer approve (#991)

- Uniswap swap_exact_out now submits exactOutputSingle through
  SwapRouter02.multicall(uint256 deadline, bytes[] data) so the swap
  expires if it cannot land in time (was silently dropping _deadline).
- Balancer Leg-1 ERC20 approve(permit2, max_in) is now idempotent: it
  reads the payer's standing Permit2 allowance first and skips the approve
  when it already covers max_in, mirroring the Uniswap venue.
- Refresh the stale swap_uniswap module doc: the slot0 price-impact read
  runs when --swap-pool-address is configured (inert otherwise).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…id to --swap-balancer-pool (#991)

- ResolvedSwap.quoter is now Option<String>: Balancer quotes through its
  own router and needs no quoter, so resolve_swap no longer errors when it
  is absent. from_config requires it only for the uniswap-v3 venue.
- Rename the Balancer flag --swap-pool-id -> --swap-balancer-pool (config
  key swap_pool_id -> swap_balancer_pool) and the ResolvedSwap field
  balancer_pool_id -> balancer_pool_address; the value is an Address, not a
  bytes32 id (Balancer V3 addresses pools directly). Clarify that
  --swap-pool-address is the Uniswap V3 TOKEN/USDC slot0 pool.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The USDC bond-funding preflight used to run a hard ensure!(swap_preflight)
and a stdin confirm_impact prompt inside prepare_usdc_swap, so
--pay-bond-with usdc --dry-run could abort early or block on a prompt
instead of printing the full preview; funding_ok() also waived USDC
sufficiency entirely in USDC mode.

- prepare_usdc_swap records usdc_ok = swap_preflight(usdc_balance, max_in)
  on PreparedSwap instead of bailing, and drops the confirm_impact block.
- Preflight gains usdc_funding_ok: Option<bool>; funding_ok() is now
  usdc_funding_ok.unwrap_or_else(|| token_ok()). run() threads the swap
  verdict in before the all_ok() gates, so dry-run and live both enforce
  USDC funding, and dry-run prints the full report first with no prompt.
- The advisory price-impact confirm moves into the live swap-execute
  block (only reachable after every abort gate), so no USDC is spent until
  the operator clears it. Token-mode is unchanged (usdc_funding_ok stays
  None -> funding_ok() == token_ok()).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (2)
crates/cli/src/commands/chain_ctx.rs (1)

282-285: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reuse pick for balancer_pool_address instead of duplicating its logic.

pick already implements flag>config precedence with cloning; the inline .clone().or_else(...) here duplicates that exact pattern instead of calling it.

♻️ Proposed refactor
-        balancer_pool_address: chain
-            .swap_balancer_pool
-            .clone()
-            .or_else(|| bc.and_then(|b| b.swap_balancer_pool.clone())),
+        balancer_pool_address: pick(&chain.swap_balancer_pool, |b| {
+            b.swap_balancer_pool.clone()
+        }),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/cli/src/commands/chain_ctx.rs` around lines 282 - 285, The
balancer_pool_address assignment in the chain context builder duplicates the
flag-over-config precedence already handled by pick. Replace the inline
clone/or_else logic with a call to pick, using the same chain.swap_balancer_pool
and bc.and_then(|b| b.swap_balancer_pool.clone()) sources so the behavior stays
identical and the precedence logic remains centralized in pick.
crates/common/src/cli/node.rs (1)

551-553: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider a ValueEnum for --swap-venue instead of a free-form string.

Typos in the venue name (e.g. uniswapv3) currently pass clap parsing and only fail later during resolve_swap/from_config. A #[derive(ValueEnum)] enum with uniswap-v3/balancer-v3 variants would reject invalid values at CLI-parse time and self-document the accepted set.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/common/src/cli/node.rs` around lines 551 - 553, The `swap_venue` CLI
option currently accepts any string, so invalid venue names slip through until
`resolve_swap`/`from_config`; replace the free-form `Option<String>` on
`swap_venue` in `node.rs` with a `#[derive(ValueEnum)]` enum that only exposes
the supported values (`uniswap-v3` and `balancer-v3`). Update the parsing in the
`Node` CLI struct to use that enum so clap rejects typos at input time and the
accepted set is self-documented.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/cli/src/commands/chain_ctx.rs`:
- Around line 282-285: The balancer_pool_address assignment in the chain context
builder duplicates the flag-over-config precedence already handled by pick.
Replace the inline clone/or_else logic with a call to pick, using the same
chain.swap_balancer_pool and bc.and_then(|b| b.swap_balancer_pool.clone())
sources so the behavior stays identical and the precedence logic remains
centralized in pick.

In `@crates/common/src/cli/node.rs`:
- Around line 551-553: The `swap_venue` CLI option currently accepts any string,
so invalid venue names slip through until `resolve_swap`/`from_config`; replace
the free-form `Option<String>` on `swap_venue` in `node.rs` with a
`#[derive(ValueEnum)]` enum that only exposes the supported values (`uniswap-v3`
and `balancer-v3`). Update the parsing in the `Node` CLI struct to use that enum
so clap rejects typos at input time and the accepted set is self-documented.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 0c05a663-328c-4539-bdd9-edd0b80cfc85

📥 Commits

Reviewing files that changed from the base of the PR and between aeecffa and 07d7506.

📒 Files selected for processing (6)
  • crates/cli/src/commands/chain_ctx.rs
  • crates/cli/src/commands/setup.rs
  • crates/common/src/cli/node.rs
  • crates/incentive/src/swap_balancer.rs
  • crates/incentive/src/swap_uniswap.rs
  • crates/incentive/src/swap_venue.rs
🚧 Files skipped from review as they are similar to previous changes (4)
  • crates/incentive/src/swap_venue.rs
  • crates/incentive/src/swap_uniswap.rs
  • crates/incentive/src/swap_balancer.rs
  • crates/cli/src/commands/setup.rs

Comment thread crates/cli/src/commands/chain_ctx.rs Resolved
Comment thread crates/incentive/src/swap_balancer.rs Resolved
Comment thread crates/incentive/src/swap_uniswap.rs Resolved
Comment thread crates/cli/src/commands/setup.rs Resolved
Comment thread crates/cli/src/commands/setup.rs Resolved
Comment thread crates/cli/src/commands/chain_ctx.rs Resolved
Comment thread crates/cli/src/commands/setup.rs Resolved
Comment thread crates/cli/src/commands/setup.rs Resolved
Comment thread crates/incentive/src/swap_uniswap.rs Resolved
Comment thread crates/cli/src/commands/setup.rs Resolved
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Review summary

Reviewed at high effort (8 finder angles → adversarial verification). 10 inline comments posted — the top correctness findings, headed by: the swap config keys being unparseable by the node's own config loader, a U256 saturation bug that makes the price-impact gate misfire for any top-up ≥ ~18.4 TOKEN when USDC sorts first, and the confirm() TTY guard changing default token-mode behavior despite the PR's unchanged-behavior claim.

Lower-priority items verified but kept out of the inline set:

  • Dangling doc reference — swap_balancer.rs:54 cites "the task-6 report per the honesty clause", a session artifact not in the repo. Keep the ABI-provenance warning, drop the report reference.
  • Balancer venue gating — the self-declared extrapolated/unverified exact-out ABI is freely selectable via swap_venue = "balancer-v3" with no warning; consider refusing or warn-gating it until verified against a real deployment.
  • Prompt duplication — confirm / confirm_impact / terms::prompt_yes_no are three parallel [y/N] implementations that already disagree on accepted answers; extract one shared helper.
  • Balancer tx count — the ERC20 approve-exact + unconditional post-swap resets make every swap a 5-tx sequence and render the skip-if-sufficient check dead; the permit2 reset also only buys ~120s vs the allowance's own expiry.
  • Duplication — the send→receipt→ensure(status) triple appears 7× across the two venues; ResolvedSwap is stringly-typed and the USDC address is parsed twice; unconnected_provider() test fixture is defined twice.
  • Sequential RPCs — prepare_usdc_swap's balance+quote and Uniswap's quoter+slot0 are independent calls awaited serially; also consider re-quoting after the interactive prompts so a stale max_in doesn't revert after approvals are mined.
  • Preflight shape [your call] — the tri-state usdc_funding_ok: Option<bool> (None silently falls back to token_ok()) is easy to mis-assign; a funding-strategy enum would make the gate un-waivable.

🤖 Generated with Claude Code

@altanoruc altanoruc left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Request changes before merge.

The current head has unresolved correctness issues in the new USDC path. The necessary fixes, in priority order:

  1. Make allowance cleanup safe on all failure paths and reset the Uniswap router allowance after a successful exact-out swap. Today a failed/reverted swap can leave a standing USDC approval; Uniswap also retains the unused portion of amountInMaximum.
  2. Eliminate the config-schema fork: add the new swap_* fields to decdn_common::config::BlockchainConfig (or move them to a deliberately setup-only table). Otherwise a config that makes decdn setup work is rejected by the node/config validator because of deny_unknown_fields.
  3. Replace the saturating amount_out * 2^192 / price_x192 calculation with full-width mul/div. For the usdc_is_token0 ordering it overflows at realistic TOKEN quantities, fabricates extreme price impact, and can abort a healthy onboarding flow.

Please add regression coverage for the failed-approval/swap cleanup path, common config parsing, and both Uniswap token-ordering branches. The remaining unresolved threads should also be addressed before this path is enabled.

alpergundogdu and others added 2 commits July 9, 2026 19:25
`decdn setup --pay-bond-with usdc` reads its swap coordinates from the
`[blockchain]` TOML section, but `decdn_common::config::BlockchainConfig`
carries `#[serde(deny_unknown_fields)]` and lacked those keys — so a config
that makes `setup` work was rejected by `decdn-node` and `decdn config
validate`, forking the schema.

Add the seven CLI-consumed swap fields as `Option`s matching
`cli::commands::chain_ctx::FileBlockchain` (`swap_venue`,
`swap_router_address`, `swap_quoter_address`, `usdc_address`,
`swap_fee_tier`, `swap_balancer_pool`, `swap_pool_address`). They are read
by the CLI, not the node runtime, so they only need to parse. Nine
exhaustive `BlockchainConfig` test literals gain `..Default::default()`.

Regression: `blockchain_swap_fields_parse_under_deny_unknown_fields` asserts
a `[blockchain]` TOML with all seven fields deserializes and round-trips.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Balancer swap_exact_out now pulls Leg 2 (Permit2->Router approve) into the
captured swap_result Result so it no longer early-returns on failure: once
Leg 1's USDC->Permit2 approval stands (fresh or via the idempotent skip),
any subsequent failure (Leg 2 approve, the swap send, or an on-chain revert)
still runs both best-effort allowance resets before returning the error,
closing the between-legs cleanup gap the human reviewer flagged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu

Copy link
Copy Markdown
Contributor Author

Thanks @altanoruc — all three are real; fixed in c09975e+e7724ac (full workspace green, 2126 tests, clippy/fmt clean).

1. Allowance cleanup on all failure paths + reset leftover Uniswap allowance.
Both venues now capture the swap Result without early-returning and then run their allowance reset(s) unconditionally (best-effort — a failed reset logs tracing::warn! and never masks the swap error):

  • Uniswap: resets USDC.approve(router, 0) after the swap, so the unused amountInMaximum − actual no longer stands after a success, and the full max_in no longer stands after a revert.
  • Balancer: Leg 2 (Permit2→router) was moved inside the captured block alongside the swap, so once Leg 1 (USDC→Permit2) stands — freshly approved or via the idempotent skip — a Leg-2 failure, swap-send failure, or on-chain revert all fall through to resetting both legs before the error propagates.

2. Config-schema fork. Added the seven swap_* fields to decdn_common::config::BlockchainConfig (it has deny_unknown_fields), so a [blockchain] config that drives decdn setup is no longer rejected by the node / decdn config validate. Regression: blockchain_swap_fields_parse_under_deny_unknown_fields.

3. spot_in_from_sqrt overflow. Replaced the saturating_mul(1<<192) (which saturated to U256::MAX for any realistic bond and fabricated extreme impact) with full-width U512 intermediates, narrowing back with a saturating conversion. Both token-ordering branches now compute the correct spot; the multiplies use saturating_mul so the function stays total. Regression tests cover both orderings at the ~10 Gbps tier (795_000e18), asserting correct non-saturated values (198_750e18 / 3_180_000e18).

Coverage. Landed: both Uniswap ordering branches (Issue 3), common config parsing under deny_unknown_fields (Issue 2), and best-effort/no-panic behavior of the reset helpers against an unconnected provider (Issue 1). Honest gap: a true end-to-end cleanup test (Leg 1 approves, Leg 2/swap reverts on-chain, resets observed) needs an anvil/mock harness the incentive crate doesn't have yet — I structured the code so cleanup always runs and unit-tested the helpers, but did not fake an e2e assertion. Happy to add one if you'd like a mock-provider harness introduced.

All resolved review threads from the bot reviewers were also addressed. The one standing item unchanged is the Balancer V3 exact-out ABI verification, which is gated on that venue existing on a live chain (Uniswap V3 is the testnet venue) — noted in the PR description.

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
crates/common/src/config/types.rs (1)

219-249: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Fields correctly wired to satisfy deny_unknown_fields.

The new swap_*/usdc_address fields are additive, well-documented, and resolve the previously-flagged issue where decdn setup --pay-bond-with usdc configs failed BlockchainConfig's deny_unknown_fields.

One minor observation: swap_venue is a bare Option<String> (doc says "One of uniswap-v3 / balancer-v3") rather than a typed enum like log_level: Option<LogLevel> elsewhere in this same struct. That defers validation of typos/unknown venues to the CLI resolver layer instead of catching them at deserialization. Not a blocker since the field is documented as CLI-consumed only, but worth considering for a future pass if venue values proliferate.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/common/src/config/types.rs` around lines 219 - 249, The `swap_venue`
field in `BlockchainConfig` is still a raw `Option<String>`, so invalid venue
values are only caught later in the CLI instead of at config deserialization
like `log_level: Option<LogLevel>`. Consider introducing a typed enum for the
supported venues (for example, the same way other config fields use enums),
updating `swap_venue` to use that type, and adjusting any serde/docs/CLI mapping
in the `swap_venue`/`swap_router_address`/`swap_quoter_address` path so typos
are rejected earlier.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@crates/common/src/config/types.rs`:
- Around line 219-249: The `swap_venue` field in `BlockchainConfig` is still a
raw `Option<String>`, so invalid venue values are only caught later in the CLI
instead of at config deserialization like `log_level: Option<LogLevel>`.
Consider introducing a typed enum for the supported venues (for example, the
same way other config fields use enums), updating `swap_venue` to use that type,
and adjusting any serde/docs/CLI mapping in the
`swap_venue`/`swap_router_address`/`swap_quoter_address` path so typos are
rejected earlier.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 758d1edc-efc3-45cf-939a-9949e73459bb

📥 Commits

Reviewing files that changed from the base of the PR and between 8a08b87 and e7724ac.

📒 Files selected for processing (4)
  • crates/common/src/config/mod.rs
  • crates/common/src/config/types.rs
  • crates/incentive/src/swap_balancer.rs
  • crates/incentive/src/swap_uniswap.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/incentive/src/swap_balancer.rs
  • crates/incentive/src/swap_uniswap.rs

alpergundogdu and others added 2 commits July 10, 2026 14:29
…ck-057e73

# Conflicts:
#	crates/cli/src/commands/chain_ctx.rs
Addresses the remaining unresolved correctness threads on PR #1091:

- setup confirm/impact prompts: drop the stdin-OR-stdout TTY guard that
  silently declined `echo y | decdn setup …`; read stdin unconditionally so a
  piped answer is honored (`--yes` stays the documented non-interactive path).
- native-gas pre-flight: size the USDC swap gas after the swap plan is known —
  0 when no swap runs (TOKEN mode / resumable re-run), else a per-venue
  constant (`SwapVenue::swap_gas_units`, Balancer > Uniswap) instead of one
  flat +300k decided from the flag alone.
- --swap-venue vs config: when the flag overrides a different config venue, no
  longer inherit that venue's router/quoter/pool/fee from config (which would
  approve USDC to the wrong router) — require them from flags.
- failed quote: record a FAILED `swap` pre-flight check and continue to the
  readiness report / --json object (new `SwapPrep::QuoteFailed`) instead of
  aborting mid-pre-flight with no report — the realistic no-pool-yet state.
- price-impact warning: print the advisory unconditionally when the threshold
  trips; `--yes` skips only the [y/N] confirmation, not the notice.
- Uniswap price impact: gross the fee-exclusive slot0 spot up by the pool fee
  (`fee_inclusive_spot_in`) so the fee tier isn't counted as phantom impact.
- --json summary: report `token_ok` from funding semantics in USDC mode so a
  successful swap-funded run isn't flagged underfunded; `funding_ok` remains
  the canonical gate.

Adds regression tests for the fee gross-up, the venue/address mismatch
resolution, and the funding-aware summary field.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alpergundogdu
alpergundogdu requested a review from altanoruc July 11, 2026 09:12
@alpergundogdu
alpergundogdu merged commit e7922d8 into main Jul 11, 2026
22 checks passed
@alpergundogdu
alpergundogdu deleted the claude/wonderful-golick-057e73 branch July 11, 2026 09:26
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: auto-swap USDC → TOKEN bond during decdn setup via the live DEX pool (Uniswap V3 / Balancer V3)

3 participants