4 Commits

Author SHA1 Message Date
48e21c3ab6 fix: clamp protocolReserves on full bad-debt write-off to prevent vault insolvency/DoS
A bad-debt write-off in QieForgeVault.liquidate() shrank totalDebtPrincipal
(the vault's real backing) without ever touching the separate, already-
realized protocolReserves bucket. With a real nonzero reserveFactorBps
(every real deploy uses one), a position whose entire debt is written off
could leave protocolReserves larger than totalDebtPrincipal + idle balance
combined, making totalAssets()'s subtraction underflow-revert forever and
permanently freezing every lender's deposit()/withdraw(). liquidate() now
clamps protocolReserves down to the vault's actual post-write-off backing,
taking only the excess beyond lenders' own cushion out of realized
treasury revenue.

Verified via 2 new Foundry regression tests (62 -> 64/64 pass, zero
regressions) and live on real deployed bytecode: a new one-command demo
(scripts/bad-debt-reserve-clamp-demo.sh) against a disposable anvil, and
re-proven on the persistent self-hosted chain (130.61.180.42:8647) via a
throwaway vault, tx 0xc4cdb5cb99a1340586eecee63be8d10bf6c673a6613cfead6a4cef3f9adaae08.

A second, distinct division-by-zero edge case in deposit() (when
totalAssets()==0 but shares are still outstanding) was found live while
building the demo and is intentionally left for a future pass.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 09:57:04 +03:00
366e8c2845 feat: aggregate borrow cap on QieForgeVault, independent of per-position LTV
Per-position ltvBps was the only check on how much a vault could lend
out in aggregate -- a well-collateralized borrower (or several) could
grow totalDebtPrincipal arbitrarily large with nothing else gating it,
even though real risk management (oracle feed liquidity depth, how much
collateral could actually be sold to cover simultaneous liquidations)
bounds how large a single market can safely get. Adds an immutable
borrowCap (0 = unlimited, exact pre-existing behavior) that borrow()
checks against aggregate debt, same primitive Compound/Aave's per-market
borrow caps already ship.

- 5 new regression tests (sentinel disables feature, exact boundary,
  aggregate across multiple borrowers, interest accrual never blocked):
  57 -> 62/62 pass, zero regressions.
- New one-command scripts/borrow-cap-demo.sh proves the real boundary
  against real deployed bytecode on a disposable anvil.
- Verified live on the persistent self-hosted demo chain
  (http://130.61.180.42:8647) against a separate throwaway vault so the
  public demo's own position was never touched: borrow() landing exactly
  on a 1,000 TUSD cap succeeded (tx 0xc71dd5c4...), the next unit over
  reverted with the real BorrowCapExceeded custom error.
- Redeployed the public demo with a real 100,000 TUSD cap and surfaced
  it on /vault via a new "Borrow cap" stat, no wallet required.
2026-10-29 09:35:15 +03:00
f8ee6e5254 feat: severity-scaled liquidation incentive curve on QieForgeVault
Before this, liquidate() paid every liquidator the exact same flat
liquidationBonusBps regardless of how underwater a position was -- no
extra incentive to rush the positions most likely to become unrecoverable
bad debt over barely-underwater ones. Added an immutable
liquidationBonusMaxBps + _dynamicLiquidationBonusBps(hf): the bonus
linearly interpolates from the base rate (healthFactor == 1.0) up to the
max (healthFactor <= 0.5), clamped at both ends. Setting max == base
disables the curve entirely (flat, the exact pre-existing behavior) --
every pre-existing liquidation test passes unchanged under that default.
Exposed liquidationBonusBpsFor(user) for bots/dashboards to read the real
current rate without simulating liquidate().

Found and fixed a real bug within this same pass: liquidate()'s forward
seize calculation picked up the new dynamic bonus, but the same
function's collateral-exhausted branch still back-calculated
coveredValueUsd off the old flat rate -- the two would have silently
diverged for exactly the case most likely to hit that branch.

Verified two ways: forge test adds 5 regression tests (constructor
validation, flat-curve backward compatibility, exact closed-form
interpolation/clamp-to-max math, a real liquidate() seizing the predicted
amount) -- 52 -> 57/57 pass, zero regressions. Live on the persistent
self-hosted demo chain (130.61.180.42:8647): deployed a separate vault,
read liquidationBonusBpsFor at three real price points (500/757/2000bps
exactly matching the closed-form math), then executed a real liquidate()
tx seizing exactly 400 WQIE at the clamped 20% max bonus.

Redeployed the live public demo (DeployDemo.s.sol now passes
liquidationBonusMaxBps too) and updated the 5 affected
NEXT_PUBLIC_QIE_FORGE_* Vercel address env vars -- in the process found
and fixed a real latent bug where `echo | vercel env add` had been baking
a trailing newline into every one of those address values, breaking
vault-position reads until re-added with `printf '%s'`. Re-verified /,
/swap, /pool, /vault all 200, /api/quote and /api/vault-position match
every prior documented demo number exactly, plus the new
liquidationBonusBps field. Re-ran scripts/liquidation-bot-demo.sh
end-to-end against the updated deploy script: real on-chain bonus came
back as 5.60% (above the 5% floor, correctly reflecting a barely-
underwater 0.98 health factor), not the old flat 5%.

Surfaced the new per-user bonus on the frontend's vault-position API and
VaultCard (a real risk-dashboard improvement: "Liquidation bonus right
now" next to health factor, shown once a position is actually
underwater).

npm test (33/33), next build, npx eslint . all clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 09:06:57 +03:00
145990ba17 feat: add a one-command liquidation bot demo against real deployed bytecode
Judges can't see a real mainnet liquidation (no funded deployer wallet
in this environment), so scripts/liquidation-bot-demo.sh deploys the
real QieForgeFactory/Router/OracleAdapter/Vault to a disposable local
anvil devnet, crashes the collateral price via the mock oracle feed,
and runs a real viem-based bot that detects the now-unhealthy position
and executes an actual liquidate() transaction — proving the full
liquidation path end-to-end against real bytecode, not a mock. Verified
live twice: 20000 TUSD debt repaid, 428571.43 WQIE seized (bonus
included), health factor 0.98 -> infinity, forge test still 46/46.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-29 06:26:15 +03:00