Repository navigation
feat(cli): decdn setup --pay-bond-with usdc — auto-swap USDC→TOKEN bond (#991) - #1091
Conversation
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…#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]>
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]>
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds venue-neutral USDC-to-TOKEN swap support for ChangesUSDC-funded bond swap
Estimated code review effort: 4 (Complex) | ~75 minutes Provider return-type lifetime fix
Estimated code review effort: 2 (Simple) | ~10 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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.
Coverage reportTotal: 80.06% (was 80.32%, ▼ 0.26%) — 44420/55483 lines
History
|
There was a problem hiding this comment.
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 intosetup. - 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.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (5)
crates/incentive/src/swap_balancer.rs (2)
259-275: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winLeg 1 approval isn't idempotent, unlike the Uniswap venue's pattern.
UniswapV3Venue::swap_exact_outskips re-approving whenallowance(recipient, router) >= max_in(documented as making re-runs cheap and idempotent).BalancerV3Venue::swap_exact_outalways sends the ERC20→Permit2 approve unconditionally, even if a sufficient allowance already stands from a prior partial run. This burns extra gas on everysetupre-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 liftStanding 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 resumablesetupre-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 valueMisleading field name:
balancer_pool_idholds 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_addressnow avoids a confusing surface for downstreamcli/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 winThread
_deadlineinto the Uniswap route.SwapRouter02::exactOutputSinglehas no per-swap expiry, butmulticall(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 winConsider bounding
--max-slippage-bps.
max_slippage_bpsis au16with no upper-bound check; a value like20000(200%) would defeat the purpose of the slippage bound this flag documents ("BoundsamountInMaximum"). Adding avalue_parserrange 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
📒 Files selected for processing (12)
adr/019-node-onboarding.mdcrates/cli/src/commands/chain_ctx.rscrates/cli/src/commands/setup.rscrates/client-pull/src/provider.rscrates/common/src/cli/mod.rscrates/common/src/cli/node.rscrates/common/src/cli/setup.rscrates/incentive/src/lib.rscrates/incentive/src/swap_balancer.rscrates/incentive/src/swap_math.rscrates/incentive/src/swap_uniswap.rscrates/incentive/src/swap_venue.rs
…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]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
crates/cli/src/commands/chain_ctx.rs (1)
282-285: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse
pickforbalancer_pool_addressinstead of duplicating its logic.
pickalready 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 winConsider a
ValueEnumfor--swap-venueinstead of a free-form string.Typos in the venue name (e.g.
uniswapv3) currently pass clap parsing and only fail later duringresolve_swap/from_config. A#[derive(ValueEnum)]enum withuniswap-v3/balancer-v3variants 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
📒 Files selected for processing (6)
crates/cli/src/commands/chain_ctx.rscrates/cli/src/commands/setup.rscrates/common/src/cli/node.rscrates/incentive/src/swap_balancer.rscrates/incentive/src/swap_uniswap.rscrates/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
Review summaryReviewed 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 Lower-priority items verified but kept out of the inline set:
🤖 Generated with Claude Code |
altanoruc
left a comment
There was a problem hiding this comment.
Request changes before merge.
The current head has unresolved correctness issues in the new USDC path. The necessary fixes, in priority order:
- 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. - Eliminate the config-schema fork: add the new
swap_*fields todecdn_common::config::BlockchainConfig(or move them to a deliberately setup-only table). Otherwise a config that makesdecdn setupwork is rejected by the node/config validator because ofdeny_unknown_fields. - Replace the saturating
amount_out * 2^192 / price_x192calculation with full-width mul/div. For theusdc_is_token0ordering 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.
`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]>
|
Thanks @altanoruc — all three are real; fixed in 1. Allowance cleanup on all failure paths + reset leftover Uniswap allowance.
2. Config-schema fork. Added the seven 3. Coverage. Landed: both Uniswap ordering branches (Issue 3), common config parsing under 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. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
crates/common/src/config/types.rs (1)
219-249: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueFields correctly wired to satisfy
deny_unknown_fields.The new
swap_*/usdc_addressfields are additive, well-documented, and resolve the previously-flagged issue wheredecdn setup --pay-bond-with usdcconfigs failedBlockchainConfig'sdeny_unknown_fields.One minor observation:
swap_venueis a bareOption<String>(doc says "One ofuniswap-v3/balancer-v3") rather than a typed enum likelog_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
📒 Files selected for processing (4)
crates/common/src/config/mod.rscrates/common/src/config/types.rscrates/incentive/src/swap_balancer.rscrates/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
…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]>
Closes #991.
What
Adds an opt-in
decdn setup --pay-bond-with usdcpath so a node operator can onboard holding only USDC. In USDC mode,setupacquires 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:
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
setupcan 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
SwapVenueabstraction (incrates/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).--max-slippage-bps(default 300) via the swap'samountInMaximum+ a deadline.[y/N](skipped by--yes). Advisory, never a hard block — an operator can pre-swap and bond manually anyway.incentive, orchestration incli.How it's wired
crates/incentive:swap_math(pure top-up/slippage/impact),swap_venue(SwapVenueenum +from_config),swap_uniswap(exact-outSwapRouter02/QuoterV2/slot0bindings),swap_balancer(Balancer V3 Router + Permit2).crates/cli:--pay-bond-with/--max-slippage-bps/--swap-*flags + config, and the USDC-mode branch insetup. The swap executes only after the pre-flightall_okgate, 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
funding_ok()waiver reduces exactly to the oldtoken_ok()when not in USDC mode).max_slippage_bpssanity cap, cosmetics) noted for later.Verification
cargo build,cargo clippy --all-targets,cargo fmt -- --check, andcargo nextest run(2116/2116) all green.🤖 Generated with Claude Code
Summary by CodeRabbit
decdn setupnow 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.--max-slippage-bpsand selectable swap venue (Uniswap v3 or Balancer v3) plus related swap parameters.decdn setup --jsonreadiness output now includes an optionalswapsection (nullwhen no swap is needed).