Skip to content

feat(access-control): shared two-tier circuit breaker with timelocked unpause - #1990

Open
Mhidesav wants to merge 1 commit into
StellarDevHub:mainfrom
Mhidesav:fix/sc-074-circuit-breaker
Open

Mhidesav wants to merge 1 commit into
StellarDevHub:mainfrom
Mhidesav:fix/sc-074-circuit-breaker

Conversation

@Mhidesav

Copy link
Copy Markdown

Summary

This adds the reusable emergency circuit breaker the issue asks for in contracts/access_control/src/circuit_breaker.rs and wires it into the AMM and lending pool.

Plan: one shared breaker owns pause state, the guardian address, and the unpause timelock. A guardian (or the admin) pauses instantly; only the admin can schedule an unpause, and it cannot execute for 24 hours. Host contracts gate mutations through require_not_paused!() but deliberately leave depositor exit paths open. Per-contract error codes are preserved so the ABI does not silently change its failure surface.

Closes #1871

Issue: [SC-074] Contract Circuit-Breaker Emergency Pause Framework with Guardian Hierarchy


Root cause

The problem wasn't a missing if paused in one function — it was that three contracts each had a different, incomplete idea of what a pause is:

  1. access_control had no reusable breaker. Pause state lived in roles.rs under an AC_PAUSED key with pause/unpause helpers. pause accepted the admin or any address holding the Guardian role, but unpause was immediately executable by the admin. There was no timelock, no single designated guardian, and no way for a host contract to map the pause into its own error space. Because the pause flag lived in role storage, any contract using it also had to use access-control's role initialisation.
  2. The AMM duplicated its own breaker. amm/src/circuit_breaker.rs held a second pause flag and guardian slot. It correctly blocked swaps, liquidity additions and liquidity removals — but blocking removals contradicts the acceptance criterion that emergency withdrawals keep working during a pause. Worse, test_guardian_pause_blocks_amm_operations was missing its #[test] attribute, so the only pause test in the AMM never ran.
  3. The lending pool had no guardian tier at all. set_paused was admin-only and instant in both directions. emergency_withdraw existed but was admin-gated and transferred the user's collateral back to that user — so a depositor had no emergency exit during a pause, which is exactly when they need one.
  4. No shared timelock. Both contracts let the admin unpause immediately, so a compromised guardian could be countered only by a race, and an incident responder had no cooling-off window before funds started moving again.

The fix and why

1. New shared module: access_control::circuit_breaker

  • initialize(admin, guardian) — called from each host's initialize; the admin is the initial guardian. State lives in its own BreakerKey namespace, so it cannot collide with the host contract's storage and does not require access-control role initialisation.
  • pause(caller) — admin or guardian, authenticated, instant. Re-pausing clears any pending unpause, so a second incident cannot ride the first incident's unlock schedule.
  • propose_unpause(admin) -> u64 — admin only, requires the contract to actually be paused, stores now + 24h (UNPAUSE_TIMELOCK_SECONDS).
  • unpause(admin) — admin only, requires a proposal and a matured timelock; a guardian can never call it.
  • cancel_unpause(admin), unpause_unlock_at(), is_paused(), assert_not_paused().
  • Events for pause/unpause/guardian/propose/cancel.

roles::pause/unpause/is_paused were removed and lib.rs re-exports the breaker instead, so there is exactly one pause flag in the crate. The require_not_paused!() macro gained a second form that takes the host's error, e.g. require_not_paused!(&env, AmmError::ContractPaused), keeping AMM 409 and lending pool 14 unchanged.

Why a separate 24h timelock instead of reusing the 48h admin-handover delay? Admin handover is a governance action; resuming a paused market is incident response. 24 hours gives reviewers time to inspect the exploit while keeping recovery practical. It is a single named constant if maintainers want a different value.

Why not keep one pause flag per contract? That is the bug: three sources of truth and three different rule sets. The shared module is the only place the hierarchy is encoded, so the next contract gets pause/unpause semantics for free.

2. AMM integration

  • initialize seeds the shared breaker; set_guardian now delegates to it.
  • pause / propose_unpause / cancel_unpause / unpause / unpause_unlock_at replace set_paused (breaking ABI — see risks).
  • Swap and add_liquidity gates use the shared macro with AmmError::ContractPaused.
  • remove_liquidity is intentionally no longer pause-gated so LPs can exit during an incident. The existing rolling 10%-per-24h outflow budget still applies, so a pause cannot be used to drain the pool in one transaction.
  • The local AMM circuit_breaker.rs is now only the outflow budget, documented as such.

3. Lending pool integration

  • initialize seeds the shared breaker; new set_guardian, pause, propose_unpause, cancel_unpause, unpause, unpause_unlock_at. paused() reads the shared state.
  • Every existing check_not_paused() call now routes through the shared macro, so deposits, borrows, collateral withdrawals, liquidations, flash loans and staking are covered without touching each entrypoint.
  • emergency_withdraw is now depositor-callable and pause-exempt, but only for collateral that does not back an outstanding borrow in that token. A borrower with debt gets LPError::DebtOutstanding (15) instead of walking away from the loan. Unstaking and reward claims were already pause-exempt and stay that way.

4. Docs

docs/contracts/SC-023-CIRCUIT-BREAKER.md now describes the shared breaker, the per-contract exemptions and the new error codes. The deployment checklist's rollback command uses the new pause entrypoint.

Files changed

File Change
contracts/access_control/src/circuit_breaker.rs new shared two-tier breaker
contracts/access_control/src/lib.rs module wiring, new error codes, macro error arm
contracts/access_control/src/roles.rs pause/unpause removed (single source of truth)
contracts/access_control/src/test.rs breaker surface + 6 tests
contracts/amm/src/lib.rs, circuit_breaker.rs, test.rs shared breaker, emergency liquidity exit, tests
contracts/lending_pool/src/lib.rs, Cargo.toml shared breaker, depositor emergency withdrawal, new error, tests
docs/contracts/SC-023-CIRCUIT-BREAKER.md, docs/deployment/DEPLOYMENT_CHECKLIST.md behaviour + runbook

How it was tested

New regression tests:

access_control (6)

  • guardian pauses instantly, but neither guardian nor admin can unpause without a proposal
  • admin can only unpause after the 24h timelock; unpause_unlock_at is exposed and cleared afterwards
  • re-pausing by the guardian invalidates a pending unpause
  • non-guardian cannot pause (300)
  • cannot propose an unpause while running (310)
  • only the admin can rotate the guardian (300)

AMM (rewritten + new)

  • test_guardian_pause_blocks_swaps_but_allows_liquidity_exit (previously missing #[test], so it never ran): guardian pause blocks swaps/adds; remove_liquidity still succeeds; the guardian cannot unpause; the admin must propose and wait; after the timelock swaps work again.

Lending pool (3)

  • paused_contract_rejects_deposit updated to the new pause entrypoint
  • guardian pause blocks depositing/withdrawing but emergency_withdraw still pays out; guardian cannot unpause; admin unpause only after the timelock
  • emergency_withdraw_rejected_with_outstanding_debt (15)

Commands run locally from contracts/ (Rust 1.100.0, soroban-sdk 28):

cargo fmt --check                        # pass
cargo clippy --workspace --all-targets   # exit 0 (pre-existing warnings only)
cargo test --workspace                   # exit 0
  access-control: 14 passed
  amm:            37 passed (+ integration/fuzz harnesses)
  lending-pool:   44 passed (+ fuzz harness)

The WASM artifact step still cannot run in this environment (soroban-sdk 28 requires stellar-cli for the wasm target); that CI step is continue-on-error. There is no UI here — verification is against the Soroban test host, no testnet deployment was performed.


Risks and trade-offs (critical path: auth / fund movement)

  • Breaking ABI. set_paused(caller, bool) is gone from both the AMM and lending pool, replaced by pause, propose_unpause, unpause and cancel_unpause. Any deployment script, keeper, frontend or indexer calling the old selector will fail until updated. I updated the in-repo runbook; off-repo callers need a follow-up.
  • Upgrade hazard (the one I'd flag to maintainers first). Existing deployments store the pause flag under the old contract-local key. The shared breaker initialises to not paused, so a contract that is paused at upgrade time would come back unpaused. There is no deployed instance in this repo, but a real upgrade must either migrate the flag or pause immediately after upgrading, before traffic resumes.
  • 24-hour unpause is deliberate. Resuming is slower than pausing. That asymmetry is the point, but it is a product decision maintainers may want to tune.
  • Guardian compromise. A compromised guardian can pause (denial of service) but cannot unpause; the admin can always cancel_unpause and re-pause. A compromised admin can do both after the timelock — that is unavoidable without a multisig council, which is out of scope.
  • AMM emergency exit is rate-limited. LPs can always call remove_liquidity while paused, but the pre-existing 10%-per-24h outflow budget still applies, so a very large LP may not exit in one transaction. That limiter exists to stop a drained pool and was intentionally left in place.
  • Lending-pool emergency exit checks debt per token. A depositor with debt in a different asset can still emergency-withdraw unencumbered collateral. Fully safe exit would need a per-user total-debt index; I left that as a follow-up rather than expanding storage in this change.
  • Repayments remain pause-gated in the lending pool (unchanged). That means borrowers cannot proactively de-risk during a pause, though liquidations are also paused, so no position is liquidated in that window.

Follow-ups worth filing separately

  1. Migrate SmartVault to the shared breaker. It still has its own breaker where a guardian can unpause, which contradicts the framework's invariant. Same for the bonding-curve pause switch.
  2. Add an upgrade migration that translates the legacy PAUSED keys into the shared breaker so a paused contract cannot resume silently on upgrade.
  3. Track total per-user debt in the lending pool to make emergency_withdraw safe across collateral tokens.
  4. Allow repay while paused so borrowers can reduce risk during an incident.
  5. Rename amm/src/circuit_breaker.rs to outflow.rs now that it only holds the rolling budget.
  6. Environment: the repo's pre-commit fails because prettier is missing from the pnpm install, and pre-push fails on the frontend tsconfig target: "ES5" error. Both are pre-existing and unrelated; this commit/push used the documented --no-verify bypass after confirming the Rust gates pass.

Reviewer checklist

  • Single reusable implementation, no duplicated pause flags in the two integrated contracts
  • Guardian pause is instant; unpause is admin-only and timelocked
  • Per-contract error codes preserved via the macro's error arm
  • Emergency exits work while paused and cannot be used to escape debt or drain the pool
  • Regression tests fail against the previous implementation and pass now
  • fmt, clippy, and full workspace tests pass

… unpause

- add a reusable circuit_breaker module: guardian or admin pauses instantly,
  admin-only unpause requires a 24h proposal, and guardians can never unpause
- integrate the AMM and lending pool, mapping pause rejections into each
  contract's existing error space
- keep emergency exits open while paused: AMM liquidity removal and lending
  pool emergency_withdraw (unencumbered collateral only)
- fix the AMM pause test that was missing #[test] and add regression coverage

Closes StellarDevHub#1871
@vercel

vercel Bot commented Nov 25, 2026

Copy link
Copy Markdown

@Mhidesav is attempting to deploy a commit to the Ayomide Adeniran's projects Team on Vercel.

A member of the Team first needs to authorize it.

@drips-wave

drips-wave Bot commented Nov 25, 2026

Copy link
Copy Markdown

@Mhidesav Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

This branch has not been deployed

No deployments
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.

[SC-074] Contract Circuit-Breaker Emergency Pause Framework with Guardian Hierarchy

1 participant