Skip to content

Cap max fee at 5% to prevent collateral rug via fee manipulation#3

Merged
anderdc merged 1 commit into
testfrom
fee-cap-5pct
Mar 26, 2026
Merged

Cap max fee at 5% to prevent collateral rug via fee manipulation#3
anderdc merged 1 commit into
testfrom
fee-cap-5pct

Conversation

@LandynDev

Copy link
Copy Markdown
Collaborator

Previously fee_divisor minimum was 2 (allowing up to 50% fee on miner collateral per swap). Now enforced at minimum 20 (max 5%) in both the contract and CLI.

Previously fee_divisor minimum was 2 (allowing up to 50% fee on miner
collateral per swap). Now enforced at minimum 20 (max 5%) in both the
contract and CLI.

@anderdc anderdc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

@anderdc anderdc merged commit eeb3313 into test Mar 26, 2026
2 checks passed
@anderdc anderdc deleted the fee-cap-5pct branch March 26, 2026 01:59
anderdc pushed a commit that referenced this pull request Mar 26, 2026
Previously fee_divisor minimum was 2 (allowing up to 50% fee on miner
collateral per swap). Now enforced at minimum 20 (max 5%) in both the
contract and CLI.
anderdc pushed a commit that referenced this pull request Apr 28, 2026
Lays the on-chain foundation for the propose/challenge/finalize extension
flow without any method bodies yet — pure type-level scaffolding so later
slices can land methods incrementally.

  types.rs:    PendingExtension { submitter, target_block, proposed_at }
  errors.rs:   7 new variants (ProposalAlreadyPending, ChallengeWindow*, etc.)
  events.rs:   6 new events split per side (Reservation/Timeout × Proposed/
               Challenged/Finalized) — clean per-entity schemas for indexers
  lib.rs:      CHALLENGE_WINDOW_BLOCKS=8, MAX_EXTENSION_BLOCKS=250,
               two new Mappings (pending_reservation_extensions,
               pending_timeout_extensions), default-init in new()

Compiles with two expected dead-code warnings on the constants — methods
that use them land in slice #3.
LandynDev pushed a commit that referenced this pull request May 1, 2026
… cap + legacy delete (#234)

* extension: add chain-aware target helper for optimistic extensions

Adds EXTENSION_PADDING_SECONDS, EXTENSION_BUCKET_BLOCKS, MAX_EXTENSION_BLOCKS
to constants.py and compute_extension_target() to chains.py. Validators will
use this to compute the target reserved_until block from observed source-chain
confirmations + padding, rounded up to a bucket so independent validator
views converge. Pure helper — no callers yet (slice 1 of the redesign).

* contract: add types/events/errors/storage for optimistic extensions

Lays the on-chain foundation for the propose/challenge/finalize extension
flow without any method bodies yet — pure type-level scaffolding so later
slices can land methods incrementally.

  types.rs:    PendingExtension { submitter, target_block, proposed_at }
  errors.rs:   7 new variants (ProposalAlreadyPending, ChallengeWindow*, etc.)
  events.rs:   6 new events split per side (Reservation/Timeout × Proposed/
               Challenged/Finalized) — clean per-entity schemas for indexers
  lib.rs:      CHALLENGE_WINDOW_BLOCKS=8, MAX_EXTENSION_BLOCKS=250,
               two new Mappings (pending_reservation_extensions,
               pending_timeout_extensions), default-init in new()

Compiles with two expected dead-code warnings on the constants — methods
that use them land in slice #3.

* contract: optimistic propose/finalize/challenge for reservation extensions

Adds the three single-validator extension methods + a getter, sitting
alongside the existing vote_extend_reservation (deletion deferred to a
later slice when the validator client is migrated).

  propose_extend_reservation(miner, from_tx_hash, target_block)
  challenge_extend_reservation(miner)
  finalize_extend_reservation(miner)
  get_pending_reservation_extension(miner) -> Option<PendingExtension>

Validator-only auth on all three. Pre-checks: NoReservation, InvalidTarget
(target <= current), ExtensionTooLong (> MAX_EXTENSION_BLOCKS),
TargetNotForward (<= reserved_until), ProposalAlreadyPending. Challenge
window closed/open guards on challenge/finalize. Finalize handles the
mid-flight reservation-clear race by dropping the proposal silently
rather than reviving stale state.

No contract-level unit tests — the codebase tests the contract via the
alw-utils E2E suites. Coverage for these methods comes when slice #6
adds the client wrappers and a new E2E suite exercises the optimistic
flow end-to-end.

* contract: optimistic propose/finalize/challenge for timeout extensions

Mirror of the reservation-extension trio, keyed by swap_id and updating
SwapData.timeout_block. Same window/cap semantics; same defensive handling
in finalize for the swap-cleared / status-changed mid-flight race.

  propose_extend_timeout(swap_id, target_block)
  challenge_extend_timeout(swap_id)
  finalize_extend_timeout(swap_id)
  get_pending_timeout_extension(swap_id) -> Option<PendingExtension>

Both propose and finalize require swap.status == Fulfilled (matching the
existing vote_extend_timeout guard — timeout extensions are specifically
for the post-fulfillment confirmation wait). vote_extend_timeout stays
in place; deletion deferred to the slice that migrates the validator client.

Wasm artifact 54.8K (+11% vs pre-extension baseline).

* contract_client: selectors + readers + write wrappers for optimistic extensions

Bridges the Python validator/CLI side to the new contract methods landed
in slices 3+4. Sits alongside vote_extend_* — those don't get deleted
until the watcher in a later slice fully replaces the call sites.

  classes.py:        new PendingExtension dataclass
  contract_client.py: 6 selectors + 6 arg schemas + 7 error variants
                      + _decode_pending_extension SCALE helper
                      + 2 readers (get_pending_{reservation,timeout}_extension)
                      + 6 write wrappers (propose/challenge/finalize × 2)
  test_contract_client.py: 14 tests covering selector pinning, arg encoding,
                           Option<PendingExtension> decode, error variant indices

* validator: OptimisticExtensionWatcher decision class

New module allways/validator/optimistic_extensions.py implementing the
per-decision primitives for the optimistic propose/challenge/finalize flow.
Stateless across calls — every method takes its inputs as parameters and
queries the contract for current pending state. Forward-loop wiring lands
in slice #8; this slice ships the class + unit tests on its own so the
forward-loop slice can be reviewed in isolation.

Six methods, mirrored across reservation and timeout sides:
  maybe_propose_*    — submits propose if no pending and target advances
  maybe_challenge_*  — challenges if target > expected + bucket tolerance,
                       skips own proposals
  maybe_finalize_*   — finalizes once challenge window has elapsed

Contract-rejection handling matches existing convention: rejects from the
contract (ProposalAlreadyPending, ChallengeWindowOpen, etc.) are debug-logged
as expected races, not warnings — losing a propose race in a multi-validator
setup is normal.

17 unit tests via mocked contract_client + wallet — no chain dependency.

* contract: extension cap + drop legacy vote_extend_* (slices 9/§13)

Adds reservation_extension_count + swap_extension_count storage maps with
MAX_EXTENSIONS_PER_RESERVATION / _PER_SWAP = 2 caps enforced at propose
time and incremented on finalize; reset on reservation/swap end.
Surfaces both via get_reservation_extension_count /
get_swap_extension_count readers and adds MaxExtensionsExceeded error.

Removes the legacy quorum extension path entirely:
vote_extend_reservation, vote_extend_timeout, REQ_EXTEND/REQ_EXTEND_TIMEOUT
constants, VoteType::ExtendTimeout, and the no-longer-emitted
ReservationExtended / SwapTimeoutExtended events. Mirrors the deletes in
contract_client (selectors, arg-types, wrappers).

Validator-side wiring + tier dispatch lands in the next commit.

* validator: optimistic extensions wired with tiered escalation (slices 8/§13)

Wires OptimisticExtensionWatcher into forward.py: try_extend_reservation
and extend_fulfilled_near_timeout dispatch propose/challenge/finalize on
the watcher; finalize is unconditional, propose/challenge fire on tx
visibility with the watcher enforcing per-tier evidence rules.

Tiered escalation per §13: tier 0 buys time for one chain block on
visibility alone (compute_extension_target_tier1); tier 1 demands ≥1
confirmation and uses the chain-aware full-confirmation target; tier ≥
cap is refused locally to match contract enforcement.

Event-driven cache: ContractEventWatcher writes through
ReservationExtensionFinalized → state_store.update_reserved_until and
TimeoutExtensionFinalized → swap_tracker.update_timeout_block. forward
loop now syncs events before purge so the just-bumped deadline isn't
swept at the stale value (replaces commit 1b942e8 polling hack).

Cleans up everything tied to the legacy quorum extend path:
extend_reservation_voted_at + refresh_cached_reserved_until,
SwapTracker.extend_timeout_voted_at + helpers, voting.extend_swap_timeout,
axon_handlers.scale_encode_extend_hash_input.

376 unit tests pass (5 new tier-specific cases in test_optimistic_extensions).

* style: auto-fix pre-commit hooks

* audit fixes: stale-reservation guard + tx_hash length check + event-loop isolation

Three issues caught in the pre-merge audit:

1. finalize_extend_reservation could resurrect a dead reservation when
   propose lands within ~window blocks of reserved_until. The challenge
   window of 8 blocks pushes finalize past expiry; the existing
   "reservations.get(miner) is None" guard only catches the explicit-clear
   case (vote_initiate, cancel), not natural expiry. Add a
   reservation.reserved_until < current_block check that drops the pending
   entry + extension count and returns NoReservation. Asymmetric with
   finalize_extend_timeout — late finalize on the timeout side is the
   intended behavior (it saves the swap from a near-deadline timeout vote);
   late finalize on a reservation has no analogous user-protection role.

2. forward.py wasn't validating from_tx_hash length before passing to the
   contract's `Hash` (32 bytes) parameter. The SCALE encoder for the
   'hash' arg type silently pads/truncates anything else, which would
   emit a propose event with a wrong topic value. Add a len == 32 guard
   that bails with a debug log when the conversion produces a non-32-byte
   payload.

3. event_watcher.process_block let exceptions from apply_event propagate up
   to sync_to, which terminates the for-loop before the cursor advances.
   Next sync re-replays every successful apply_event in the same block,
   double-applying busy deltas. Pre-existing exposure (insert_swap_outcome
   on SQLite errors); the new ReservationExtensionFinalized /
   TimeoutExtensionFinalized branches widened the surface. Wrap the
   apply_event call in try/except + warning so a single bad event doesn't
   break the cursor invariant.

Selectors unchanged. 377 unit tests pass.

* refactor: collapse tier-1 extension helper into unified compute_extension_target

The tier-1 helper was just compute_extension_target with remaining=1, and
EXTENSION_TIER1_PADDING_SECONDS duplicated EXTENSION_PADDING_SECONDS. Switch
the unified function to take remaining_blocks directly and have callers pick
the value per tier (1 for tier-1, max(0, min_conf - observed) for tier-2).

* docs: drop planning-doc references from code comments

Comments shouldn't point at local planning docs that may be renamed,
deleted, or never shared. Reword the comments to stand on their own.

* CLI: surface optimistic extension state and fix probe-replaced bound

view_swap/view_reservation now show extension count and any pending
proposal (target, finalizable-in, submitter); view_contract surfaces the
challenge window and per-reservation/swap caps; view_validators clarifies
that consensus quorum applies to reserve/initiate/confirm/timeout, not
extensions.

probe_pending_reservation no longer bounds growth on the contract's
reservation_ttl — once optimistic extensions are the source of
reserved_until growth, the relevant ceiling is
MAX_EXTENSIONS_PER_RESERVATION * MAX_EXTENSION_BLOCKS. The old check
misclassified a legitimate BTC tier-0 extension (~180 blocks) as
``replaced`` on short-ttl setups.

* style: auto-fix pre-commit hooks

---------

Co-authored-by: anderdc <me@alexanderdc.com>
anderdc added a commit that referenced this pull request Jun 22, 2026
…vation, admin cancels, shared validation

- consolidate tunables.rs into constants.rs (economic-levers section)
- open_or_request: gate on 1.10x required_collateral at pool entry so an
  under-collateralized miner can't strand a user at vote_initiate (#1)
- vote_deactivate: forbid deactivating a busy miner (busy => active invariant),
  so resolve_pool never arms a reservation on an inactive miner (#3)
- restore admin cancel_pool / cancel_reservation, clearing busy_until (#4)
- admin setters reject contradictory min/max bounds (#6)
- set_quote charges the churn fee on creation too, closing the
  remove_quote + set_quote dodge (#7)
- validate.rs: shared Config-field validators used by initialize + setters so
  the two write paths can't diverge (#8)
- DEFAULT_FULFILLMENT_TIMEOUT_SECS = 14400 (4h) canonical deploy default
- tests: 12 new (entry gate, busy deactivation, cancels, bounds, quote fee);
  LiteSVM 67/67, e2e.sh 24/24
LandynDev pushed a commit that referenced this pull request Jun 22, 2026
* fix(solana): PR review — entry over-collateral gate, busy-lock deactivation, admin cancels, shared validation

- consolidate tunables.rs into constants.rs (economic-levers section)
- open_or_request: gate on 1.10x required_collateral at pool entry so an
  under-collateralized miner can't strand a user at vote_initiate (#1)
- vote_deactivate: forbid deactivating a busy miner (busy => active invariant),
  so resolve_pool never arms a reservation on an inactive miner (#3)
- restore admin cancel_pool / cancel_reservation, clearing busy_until (#4)
- admin setters reject contradictory min/max bounds (#6)
- set_quote charges the churn fee on creation too, closing the
  remove_quote + set_quote dodge (#7)
- validate.rs: shared Config-field validators used by initialize + setters so
  the two write paths can't diverge (#8)
- DEFAULT_FULFILLMENT_TIMEOUT_SECS = 14400 (4h) canonical deploy default
- tests: 12 new (entry gate, busy deactivation, cancels, bounds, quote fee);
  LiteSVM 67/67, e2e.sh 24/24

* refactor(solana): separate subnet-revenue Treasury PDA from the collateral Vault

Collateral and subnet revenue no longer share an account. The Vault holds ONLY
miner collateral (trustless — leaves only via the owning miner's withdraw or a
slash to the wronged user); a new Treasury PDA holds ONLY subnet income.

- new Treasury { total, bump } PDA (seeds [b"treasury"]); Vault loses treasury_total
- confirm 1% fee, reservation fee, and quote churn fee all accrue to the Treasury
- timeout slash still pays the user from the Vault (never the treasury)
- withdraw_treasury drains the Treasury PDA (admin-only, caller-chosen recipient)
- split invariants: vault.lamports == rent + total_collateral;
  treasury.lamports == rent + total

Anti-flash fee follows the #488 mechanism (creation free; charge on remove_quote):
- set_quote creation is free again; updates still pay the decaying churn fee
- remove_quote charges the same decaying fee -> Treasury, closing the
  remove+recreate dodge without taxing first-time quotes

Tests updated for the split + new fee semantics. LiteSVM 67/67, e2e.sh 24/24.

* fix(solana): address pre-PR code-review findings

- cancel_reservation: require an active reservation (reserved_until != 0) so it
  can't clear busy_until on a miner whose pool is still open — that could let the
  miner be deactivated mid-contest and resolve_pool match a removed miner against
  a user (fund-safety regression caught in review)
- resolve_pool: restore the inactive-miner backstop (reset pool, never arm a
  reservation or busy lock for an inactive miner)
- vote_initiate: defensive active-miner check before initiating
- remove_quote: document the deliberate "removal can cost the churn fee" stance
- fix stale vault->treasury doc comments (confirm_swap, set_quote, lib, constants)
- tests: cancel_reservation open-pool rejection + treasury lamport conservation

LiteSVM 68/68, e2e.sh 24/24.

* refactor(solana): drop cancel_pool/cancel_reservation; rely on TTL self-expiry

No permanent stuck state exists: resolve_pool is permissionless (always progresses
an open pool) and a reservation's reserved_until is always now + reservation_ttl,
so a miner abandoned in a reservation self-frees at the TTL. The admin cancel ops
were only early-clear accelerators and were the sole paths that cleared busy_until
manually — the exact footgun behind the fund-safety bug. Removing them restores a
clean busy => active invariant without a resolve_pool backstop.

- remove cancel_pool / cancel_reservation instructions, their events + tests
- resolve_pool: no active check (documented invariant); vote_initiate keeps its
  defensive active check as the funds-commit backstop

LiteSVM 65/65, e2e.sh 24/24.
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.

2 participants