Verified contractPartialUNLICENSED
Warehouse
Address0xbbbdd4ede4e81a1c63a609d6e6a8250ffef061e3
- Balance
0 ETH
- Transactions
196
- Compiler
solc 0.8.27
- Same code
1 more contract
Details
- Compiler
- solc 0.8.27+commit.40a35a09
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,362,481
- Creation transaction
- 0x0cdf54a2fb…f3a10091d3
92 files
The source code is large: one file is shown at a time. Choose a file in the list.
- src/Warehouse.solmain30.84 KB
- lib/openzeppelin-community-contracts/contracts/interfaces/IERC7540.sol7.33 KB
- lib/openzeppelin-community-contracts/contracts/interfaces/IERC7575.sol747 B
- lib/openzeppelin-community-contracts/contracts/token/ERC20/extensions/ERC7540.sol42.71 KB
- lib/openzeppelin-community-contracts/contracts/token/ERC20/extensions/ERC7540SyncDeposit.sol1.85 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/interfaces/IERC165.sol193 B
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/interfaces/IERC20.sol182 B
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol216 B
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/interfaces/IERC4626.sol12.21 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/token/ERC20/ERC20.sol10.8 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13.96 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/LowLevelCall.sol5.55 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/Memory.sol6.14 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/Pausable.sol2.71 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4.77 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/introspection/ERC165.sol879 B
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/math/Math.sol32.66 KB
- lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/access/AccessControl.sol7.05 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts/contracts/utils/Pausable.sol2.83 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol3.38 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol912 B
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol28.31 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol12.89 KB
- src/StabilityPool7540.sol36.31 KB
- src/StableReserveVault.sol11.71 KB
- src/Treasury.sol41.99 KB
- src/Vault.sol21.68 KB
- src/WarehouseDeployer.sol957 B
- src/WarehousePool.sol2.85 KB
- src/WarehouseSourceAuth.sol971 B
- src/WarehouseTreasury.sol33.19 KB
- src/WarehouseVault.sol9.07 KB
- src/interfaces/IArbBuyer.sol1.24 KB
- src/interfaces/ICollateralRegistry.sol692 B
- src/interfaces/IFacilityRegistry.sol2.03 KB
- src/interfaces/IFloorSettlementExecutor.sol1.37 KB
- src/interfaces/IGreaterMarketReference.sol1.34 KB
- src/interfaces/ILiquidationEngine.sol527 B
- src/interfaces/IOracleAdapter.sol3.7 KB
- src/interfaces/IPRUSD.sol365 B
- src/interfaces/ISettlementExecutor.sol862 B
- src/interfaces/ISettlementPool7540.sol1.06 KB
- src/interfaces/IStabilityPoolRegistry.sol1.31 KB
- src/interfaces/IStabilityPoolSettlementLedger.sol1.07 KB
- src/interfaces/ITreasury.sol2.39 KB
- src/interfaces/IVault.sol2.66 KB
- src/interfaces/IWarehouse.sol1.7 KB
- src/interfaces/IWarehouseCycleSource.sol638 B
- src/interfaces/IWarehouseRegistry.sol561 B
- src/libraries/FacilityDebtMath.sol1.44 KB
- src/libraries/FacilityStatusLib.sol1.26 KB
- src/libraries/RevenueSources.sol855 B
- src/libraries/Roles.sol7.74 KB
- src/libraries/SalePricing.sol1.19 KB
- src/libraries/SharePenalty7540.sol1.7 KB
- src/libraries/SrvLossMath.sol4.78 KB
- src/libraries/StableReserveMath.sol1.9 KB
- src/libraries/SupportedChains.sol1.17 KB
- src/libraries/TestDrain.sol1.45 KB
- src/libraries/TreasuryCow.sol23.14 KB
- src/libraries/TreasuryFold.sol15.24 KB
- src/libraries/TreasurySales.sol45.44 KB
- src/libraries/WarehouseSeizureMath.sol5.27 KB
- src/registries/CollateralRegistry.sol4.25 KB
- src/registries/FacilityRegistry.sol26.34 KB
- src/registries/PsmAssetRegistry.sol5.24 KB
- src/registries/StableReserveRegistry.sol13.56 KB
- src/registries/WarehouseRegistry.sol6.6 KB
- src/types/LotTypes.sol606 B
- src/types/ProtocolTypes.sol3.4 KB
src/Warehouse.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.27;
import {PricingEvidence, ISalePricingEvents} from "./libraries/SalePricing.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IWarehouse} from "./interfaces/IWarehouse.sol";
import {IGreaterMarketReference} from "./interfaces/IGreaterMarketReference.sol";
import {WarehousePool} from "./WarehousePool.sol";
import {WarehouseTreasury} from "./WarehouseTreasury.sol";
import {LotHandover} from "./types/LotTypes.sol";
import {WarehouseVault} from "./WarehouseVault.sol";
import {IStabilityPoolRegistry} from "./interfaces/IStabilityPoolRegistry.sol";
import {IFloorSettlementExecutor} from "./interfaces/IFloorSettlementExecutor.sol";
import {IPRUSD} from "./interfaces/IPRUSD.sol";
import {RevenueSources} from "./libraries/RevenueSources.sol";
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {IWarehouseCycleSource} from "./interfaces/IWarehouseCycleSource.sol";
import {Roles} from "./libraries/Roles.sol";
import {TestDrain} from "./libraries/TestDrain.sol";
import {SupportedChains} from "./libraries/SupportedChains.sol";
interface IWarehouseGreaterMarketBinding {
function greaterMarket() external view returns (address);
}
/// @notice The SP registry holds each SP's single sale route (task 0191).
interface IWarehouseSaleRoutes {
function saleRoute(uint256 poolId) external view returns (address);
}
interface IWarehouseVenueBinding {
function pool() external view returns (address);
function collateral() external view returns (address);
function prusd() external view returns (address);
}
/// @notice One collateral's warehouse: seized collateral and the obligation recorded against it, released
/// to the Stability Pool in atomic bites or handed to the Treasury on fold. Mainnet, Sepolia, Anvil.
/// @dev The immutable Vault authenticates provenance and supplies the split. Valuation is read-only.
contract Warehouse is IWarehouse, ReentrancyGuard, ERC165, ISalePricingEvents {
using SafeERC20 for IERC20;
uint256 private constant ONE = 1e18;
struct Terms {
uint256 minimumBite;
uint256 minimumCoverage;
uint256 marginFloor;
}
struct Clip {
uint256 debt;
uint256 collateral;
uint256 interest;
uint256 principal;
uint256 margin;
uint256 stop;
}
struct FacilityDebt {
uint256 principal;
uint256 interest;
bool seen;
}
IPRUSD public immutable prusd;
address public immutable operator;
uint256 public immutable minimumBite;
uint256 public immutable minimumCoverage;
uint256 public immutable marginFloor;
/// @notice One liquidation episode spans all seizures and bites until cleared or folded.
uint256 public liquidationCycleId;
bool public liquidationCycleOpen;
event LiquidationCycleOpened(uint256 indexed liquidationCycleId, uint256 indexed poolId);
event LiquidationCycleClosed(
uint256 indexed liquidationCycleId, uint256 indexed poolId, bool folded
);
mapping(uint256 => FacilityDebt) public facilityDebt;
uint256[] public facilities;
struct FoldedDebt {
uint256 principal;
uint256 interest;
}
/// @notice Each facility's share of the debt this warehouse has handed to the Treasury (audit
/// af273eaf399ef5d33ec86d70 M-4, DEF-227). Cumulative across takeovers. Record only: the takeover
/// frees no facility principal (0195, ADR-0001); the Treasury frees it per lot as the loan is paid off,
/// so this must never be used as a retirement source.
mapping(uint256 facilityId => FoldedDebt) public foldedFacilityDebt;
uint256 private residualCycle;
uint256 private residualAmount;
uint256 private residualStop;
error OnlyOperator();
error IllegalBite();
/// @dev Distinct from IllegalBite so the keeper can tell "should fold" from "cannot fold yet".
error NotFoldable();
error InvalidCycleBinding();
error CycleReceiptMismatch();
error CycleRecoveryPending();
/// @notice Per-facility split of what the Treasury takeover handed over (audit 438253e1c6429f27 HIGH-3,
/// DEF-221, DEF-227). Nothing is minted or burned and no facility principal is freed (0195): the
/// Treasury frees it per lot as the loan is paid off. A record, not a trigger for `recordRepay`.
event FacilityDebtFolded(
uint256 indexed facilityId,
uint256 indexed collateralId,
uint256 principal,
uint256 interest
);
event WarehouseFoldedToTreasury(
uint256 indexed collateralId,
uint256 indexed poolId,
uint256 collateral,
uint256 principal,
uint256 interest
);
event WarehouseCycleCompleted(
uint256 indexed cycle,
uint256 debt,
uint256 principal,
uint256 interest,
uint256 collateral,
uint256 cash,
uint256 tab,
uint256 stop
);
event FacilityDebtRetired(uint256 indexed facilityId, uint256 principal, uint256 interest);
struct Binding {
uint256 collateralId;
uint256 poolId;
address token;
uint8 decimals;
address vault;
address pool;
address treasury;
}
uint256 public immutable collateralId;
uint256 public immutable poolId;
IERC20 public immutable collateralToken;
uint8 public immutable collateralDecimals;
address public immutable vault;
address public immutable pool;
address public immutable treasury;
address public immutable registry;
uint256 public totalCollateral;
uint256 public totalPrincipal;
uint256 public totalInterest;
mapping(bytes32 seizureId => bool) public seizureRecorded;
/// @param registry_ the registry that owns this warehouse. Passed in because
/// the registry creates warehouses through its `WarehouseDeployer` (EIP-170), not directly.
constructor(
Binding memory b,
IPRUSD asset_,
address operator_,
Terms memory terms,
address registry_
) {
if (
b.collateralId == 0 || b.poolId == 0 || b.token.code.length == 0
|| b.vault.code.length == 0 || b.pool.code.length == 0
|| b.treasury.code.length == 0
) revert InvalidSeizure();
collateralId = b.collateralId;
poolId = b.poolId;
collateralToken = IERC20(b.token);
collateralDecimals = b.decimals;
vault = b.vault;
pool = b.pool;
treasury = b.treasury;
if (registry_ == address(0)) revert InvalidCycleBinding();
registry = registry_;
SupportedChains.check();
if (
operator_ == address(0) || terms.minimumBite == 0 || terms.minimumCoverage < ONE
|| terms.marginFloor > terms.minimumCoverage - ONE
) {
revert InvalidCycleBinding();
}
prusd = asset_;
operator = operator_;
minimumBite = terms.minimumBite;
minimumCoverage = terms.minimumCoverage;
marginFloor = terms.marginFloor;
}
function recordSeizure(
bytes32 seizureId,
address borrower,
uint256 facilityId,
uint256 collateralAmount,
uint256 principal,
uint256 interest
) external nonReentrant {
if (msg.sender != vault) revert OnlyVault();
if (
seizureId == bytes32(0) || borrower == address(0) || facilityId == 0
|| collateralAmount == 0 || principal + interest == 0
) revert InvalidSeizure();
if (seizureRecorded[seizureId]) revert SeizureAlreadyRecorded(seizureId);
uint256 beforeBalance = collateralToken.balanceOf(address(this));
if (beforeBalance < totalCollateral) revert CollateralDeficit();
seizureRecorded[seizureId] = true;
collateralToken.safeTransferFrom(vault, address(this), collateralAmount);
if (collateralToken.balanceOf(address(this)) != beforeBalance + collateralAmount) {
revert CollateralReceiptMismatch();
}
if (!liquidationCycleOpen) {
liquidationCycleId++;
liquidationCycleOpen = true;
emit LiquidationCycleOpened(liquidationCycleId, poolId);
}
totalCollateral += collateralAmount;
totalPrincipal += principal;
totalInterest += interest;
// Keep the combined debt representable, not only each component separately.
uint256 debt = totalPrincipal + totalInterest;
assert(debt != 0);
_afterSeizure(facilityId, principal, interest);
emit SeizureRecorded(
seizureId,
borrower,
facilityId,
collateralId,
collateralAmount,
principal,
interest,
totalCollateral,
totalPrincipal,
totalInterest
);
}
function totalDebt() external view returns (uint256) {
return totalPrincipal + totalInterest;
}
/// @notice Unsolicited collateral is not a seizure and creates no debt or withdrawal entitlement.
function collateralSurplus() external view returns (uint256) {
uint256 balance = collateralToken.balanceOf(address(this));
return balance > totalCollateral ? balance - totalCollateral : 0;
}
/// @inheritdoc IWarehouse
function valuation()
external
view
returns (uint256 priceUsd18, uint256 recordedValueUsd18, uint256 coverageWad)
{
if (_reentrancyGuardEntered()) revert ReentrancyGuardReentrantCall();
return _valuation();
}
function _valuation()
internal
view
returns (uint256 priceUsd18, uint256 recordedValueUsd18, uint256 coverageWad)
{
uint256 debt = totalPrincipal + totalInterest;
if (debt == 0) revert NoWarehouseDebt();
if (collateralToken.balanceOf(address(this)) < totalCollateral) revert CollateralDeficit();
if (collateralDecimals > 77) revert UnsupportedValuationDecimals();
// Reuse the set-once canonical reference; no independent warehouse price configuration.
address ref = IWarehouseGreaterMarketBinding(vault).greaterMarket();
if (ref.code.length == 0 || IWarehouseGreaterMarketBinding(treasury).greaterMarket() != ref)
{
revert GreaterMarketBindingInvalid();
}
bool valid;
(priceUsd18, valid) = IGreaterMarketReference(ref).greaterMarketPrice(collateralId);
if (!valid || priceUsd18 == 0) revert GreaterMarketInvalid(collateralId);
recordedValueUsd18 = Math.mulDiv(totalCollateral, priceUsd18, 10 ** collateralDecimals);
coverageWad = Math.mulDiv(recordedValueUsd18, 1e18, debt);
}
/// @notice This SP's sale route, read from the SP registry each time: the warehouse keeps no copy, so it and
/// the Treasury can never disagree about the route (task 0191).
function executor() public view returns (address) {
return IWarehouseSaleRoutes(address(WarehouseVault(vault).poolRegistry())).saleRoute(poolId);
}
/// @notice Registry route administration may proceed only between guarded executions.
function executionActive() external view returns (bool) {
return _reentrancyGuardEntered();
}
function supportsInterface(bytes4 id) public view override returns (bool) {
return id == type(IWarehouseCycleSource).interfaceId || super.supportsInterface(id);
}
/// @dev Excludes routing itself to avoid a registry -> warehouse -> registry recursion.
/// No cash/seed requirement: structural admission precedes first borrowing and funding.
function isCycleReady() external view returns (bool) {
return executor().code.length != 0
&& IAccessControl(address(prusd)).hasRole(Roles.BURNER_ROLE, address(this))
&& IAccessControl(treasury).hasRole(Roles.REVENUE_SOURCE_ROLE, address(this))
&& IAccessControl(pool).hasRole(Roles.WAREHOUSE_FUNDING_ROLE, address(this))
&& IAccessControl(pool).hasRole(Roles.SETTLEMENT_ROLE, address(this));
}
function _afterSeizure(uint256 fid, uint256 p, uint256 i) private {
FacilityDebt storage f = facilityDebt[fid];
if (!f.seen) {
f.seen = true;
facilities.push(fid);
}
f.principal += p;
f.interest += i;
}
function foldLotId() external view returns (bytes32) {
return keccak256(abi.encode(address(this), liquidationCycleId));
}
/// @notice Event-derived borrower accounting; v1 stored and updated borrower positions on chain.
function auditModelVersion() external pure returns (uint256) {
return 2;
}
function quote(uint256 maximum) public view returns (Clip memory c) {
(c,,) = _quote(maximum);
}
function _quote(uint256 maximum) private view returns (Clip memory c, uint256 g, uint256 w) {
(g,, w) = _valuation();
c.debt = _biteDebt(
maximum, WarehousePool(pool).workingCapital(), totalPrincipal + totalInterest
);
if (c.debt < minimumBite || w < minimumCoverage) revert IllegalBite();
c.collateral = Math.mulDiv(totalCollateral, c.debt, totalPrincipal + totalInterest);
if (c.collateral == 0) revert IllegalBite();
c.interest = Math.min(c.debt, totalInterest);
c.principal = c.debt - c.interest;
c.margin = Math.max(marginFloor, (w - ONE) / 2);
uint256 cost =
Math.mulDiv(c.debt, 10 ** collateralDecimals, c.collateral, Math.Rounding.Ceil);
c.stop = Math.mulDiv(cost, ONE + c.margin, ONE, Math.Rounding.Ceil);
}
/// @dev Largest affordable bite with both a minimum bite and a zero-or-minimum remainder.
/// Zero means no feasible bite. Subtraction follows the bounds checks to avoid underflow.
function _biteDebt(uint256 maximum, uint256 cash, uint256 debt) private view returns (uint256) {
uint256 bite = Math.min(maximum, Math.min(cash, debt));
if (bite < minimumBite) return 0;
uint256 left = debt - bite;
if (left == 0 || left >= minimumBite) return bite;
uint256 reduced = debt - minimumBite;
return reduced >= minimumBite ? reduced : 0;
}
function residualQuote() external view returns (uint256, uint256, uint256) {
return (residualCycle, residualAmount, residualStop);
}
function cycle(uint256 maximum, bytes calldata data) external nonReentrant {
uint256 bite = _cycle(maximum, data);
WarehouseTreasury(treasury).settleCycleCash(poolId, liquidationCycleId, bite);
_closeClearedCycle();
}
/// @notice Optional atomic unwind, strictly after the pool has consumed the bite settlement.
function cycleWithRecovery(
uint256 maximum,
bytes calldata data,
address asset,
address recoveryExecutor,
uint256 recoveryMaximum,
bytes calldata recoveryData
)
external
nonReentrant
returns (uint256 sold, uint256 backingIn, uint256 minted, uint256 repaid)
{
uint256 bite = _cycle(maximum, data);
WarehouseTreasury t = WarehouseTreasury(treasury);
// Task 0294: next to a configured CoW seller the bite's recovery sells only what the Treasury still holds.
uint256 amount =
Math.min(recoveryMaximum, t.recoverableCycleCollateral(poolId, liquidationCycleId));
if (amount != 0) {
(sold, backingIn, minted, repaid) = t.recoverCollateral(
collateralId, liquidationCycleId, asset, recoveryExecutor, amount, recoveryData
);
}
// Recovery first combines retained cash with the new mint for arb, then repays TAB.
// Still settle when there was no recovery inventory or no fill, including the final bite.
t.settleCycleCash(poolId, liquidationCycleId, bite);
_closeClearedCycle();
}
/// @notice Clear after the last bite once the linked SP's TAB is paid or recovery is exhausted.
/// @dev Outstanding includes old TAB and queued claims; remaining collateral keeps its attribution.
function canCloseClearedCycle() public view returns (bool) {
WarehouseTreasury t = WarehouseTreasury(treasury);
return liquidationCycleOpen && totalPrincipal + totalInterest == 0
&& (t.outstanding(pool) == 0 || t.cycleCollateral(poolId, liquidationCycleId) == 0);
}
/// @notice Finish a cleared cycle after asynchronous recovery. No price or keeper assertion is used.
function closeClearedCycle(uint256 expectedCycleId) external nonReentrant {
if (expectedCycleId != liquidationCycleId || !canCloseClearedCycle()) {
revert CycleRecoveryPending();
}
_closeLiquidationCycle(false);
}
function _closeClearedCycle() private {
if (canCloseClearedCycle()) _closeLiquidationCycle(false);
}
function _closeLiquidationCycle(bool folded) private {
liquidationCycleOpen = false;
WarehouseTreasury(treasury).closeLiquidationCycle(poolId, liquidationCycleId);
emit LiquidationCycleClosed(liquidationCycleId, poolId, folded);
}
/// @notice Close a warehouse that can never be bitten again, handing the whole remaining position to
/// the bound Treasury (`docs/scenarios/warehouse-liquidation-v2.md` section 6, task 0181).
/// @dev Fold does NOT refill the pool: the pool's working capital only returns when the Treasury sells,
/// and its TAB is a separate claim this never touches.
/// The whole trigger is enforced on chain by `_foldConditionHolds`: coverage below W_min or dust
/// debt folds at once; a pool that can fund a dust-free bite refuses; a short pool folds when no TAB
/// is owed or no unwind is in flight (`_unwindInFlight`). Refusals revert `NotFoldable`.
/// ASSUMES the collateral transfers exactly the amount sent. A fee-on-transfer token would make the
/// strict receipt check below revert every time. Such tokens are inadmissible by rule
/// (`docs/security/token-admission-checks.md`, DEF-226, DEF-231), and the check stays as a tripwire.
function fold() external nonReentrant {
if (msg.sender != operator) revert OnlyOperator();
_checkBindings();
uint256 principal = totalPrincipal;
uint256 interest = totalInterest;
uint256 collateralHeld = totalCollateral;
if (principal + interest == 0 || collateralHeld == 0) revert NotFoldable();
if (!_foldConditionHolds(principal + interest)) revert NotFoldable();
// Effects before interactions: the ledger closes first, so a reverting transfer rolls it all back.
totalCollateral = 0;
totalPrincipal = 0;
totalInterest = 0;
LotHandover[] memory h = new LotHandover[](facilities.length);
for (uint256 j; j < facilities.length; j++) {
uint256 fid = facilities[j];
FacilityDebt storage f = facilityDebt[fid];
h[j] = LotHandover(fid, f.principal, f.interest);
// Recorded BEFORE the rows are cleared, in state and in the event. The facility's principal is NOT
// freed here (0195, ADR-0001): the vault keeps counting it until the Treasury pays the lot off.
if (f.principal != 0 || f.interest != 0) {
FoldedDebt storage d = foldedFacilityDebt[fid];
d.principal += f.principal;
d.interest += f.interest;
emit FacilityDebtFolded(fid, collateralId, f.principal, f.interest);
}
f.principal = 0;
f.interest = 0;
}
// Size the sweep by the ACTUAL balance, never by the ledger. The Treasury pulls this warehouse's
// whole balance, so approving only the ledger amount would let anyone permanently block a fold by
// sending the warehouse one wei of collateral. Donated dust follows the position to the Treasury,
// which is the party bearing the loss.
uint256 sweep = collateralToken.balanceOf(address(this));
if (sweep < collateralHeld) revert CycleReceiptMismatch();
collateralToken.forceApprove(treasury, sweep);
uint256 taken = WarehouseTreasury(treasury).assumeFoldedWarehouse(collateralId, h);
collateralToken.forceApprove(treasury, 0);
if (taken != sweep || collateralToken.balanceOf(address(this)) != 0) {
revert CycleReceiptMismatch();
}
emit WarehouseFoldedToTreasury(collateralId, poolId, sweep, principal, interest);
_closeLiquidationCycle(true);
}
/// @dev Only the short-pool branch waits for an unwind already in flight.
///
/// - "W below W_min folds": coverage collapse is durable, so it never waits.
/// - "Dust folds": remaining debt below the minimum bite can never be bitten.
/// - A pool that CAN fund a dust-free bite must be bitten, never folded.
/// - If the pool funds the minimum but no dust-free bite exists, fold (WF_MIN_LIQ).
/// - With no TAB owed to this pool, recovery cannot refill it: fold (Waterfall rules section 7).
/// - "A short pool waits only on an unwind in flight": it "never waits for future deposits or
/// future revenue", only for an unwind already under way.
function _foldConditionHolds(uint256 debt) private view returns (bool) {
(uint256 priceUsd18,, uint256 w) = _valuation();
if (w < minimumCoverage) return true;
if (debt < minimumBite) return true;
uint256 cash = WarehousePool(pool).workingCapital();
if (cash >= minimumBite) return _biteDebt(type(uint256).max, cash, debt) == 0;
return WarehouseTreasury(treasury).outstanding(pool) == 0 || !_unwindInFlight(priceUsd18);
}
/// @dev Spec section 6: an unwind is in flight "iff the Treasury holds this warehouse's collateral
/// whose next marginal sale clears tolerance, or holds undeposited stablecoin from it, or holds
/// minted PRUSD not yet paid against the TAB".
///
/// For a pool still owed TAB, DELIBERATELY STRICTER THAN THE SPEC on the first leg. Whether the next marginal sale clears
/// tolerance depends on live venue depth against the recovery floor, which the keeper determines
/// off-chain and this contract cannot evaluate. So ANY held inventory for this collateral counts
/// as in flight. That errs towards waiting, and waiting is the reversible state: the spec itself
/// says a calm stall "may wait indefinitely by design", whereas a fold is one-way with no unfold.
/// It does not strand the motivating case, which folds on the coverage branch above.
///
/// Except dust (task 0316, Bevan 27 October): held inventory worth less than one minimum bite at the
/// market price is not in flight. No solver fills it, so waiting on it never ends; the same yardstick
/// makes debt below one minimum bite fold at once. The fold carries that remainder into the lot.
///
/// The second and third legs read the Treasury's tally of recovery PRUSD not yet paid against
/// the TAB. They must never read a token balance: anyone can send the Treasury PRUSD, so a
/// balance read would let one wei block the fold forever (DEF-225, proven by
/// `test/WarehouseFoldRecovery.t.sol`). Recovery sells, deposits, mints and repays inside one
/// call, so undeposited stablecoin never survives between transactions and needs no separate leg.
function _unwindInFlight(uint256 priceUsd18) private view returns (bool) {
WarehouseTreasury t = WarehouseTreasury(treasury);
uint256 held = t.seizedInventory(collateralId);
// Rounded up: at the threshold the error leans towards waiting, the reversible state.
if (
held != 0
&& Math.mulDiv(held, priceUsd18, 10 ** collateralDecimals, Math.Rounding.Ceil)
>= minimumBite
) return true;
return t.recoveryUnpaid(poolId) != 0;
}
function _cycle(uint256 maximum, bytes calldata data) private returns (uint256 id) {
if (msg.sender != operator) revert OnlyOperator();
_checkBindings();
(Clip memory c, uint256 g, uint256 w) = _quote(maximum);
WarehousePool sp = WarehousePool(pool);
WarehouseTreasury t = WarehouseTreasury(treasury);
uint256 initialCash = prusd.balanceOf(address(this));
sp.fundWarehouseCycle(c.debt);
if (prusd.balanceOf(address(this)) != initialCash + c.debt) {
revert CycleReceiptMismatch();
}
id = sp.cycleId();
_retire(c);
if (c.interest != 0) {
bytes32 operation = keccak256(abi.encode(address(this), id));
t.beginRecord(operation);
IERC20(address(prusd)).safeTransfer(treasury, c.interest);
t.finalizeRecord(operation, RevenueSources.INTEREST, c.interest);
}
if (c.principal != 0) prusd.burn(address(this), c.principal);
(uint256 cash, uint256 tab) = _sell(c, id, initialCash, data, g, w);
IERC20(address(prusd)).forceApprove(treasury, cash);
t.recordSettlement(pool, id, c.debt, cash, tab);
IERC20(address(prusd)).forceApprove(treasury, 0);
sp.recordSettlementProceeds(cash, tab);
if (sp.settlementPending() || prusd.balanceOf(address(this)) != initialCash) {
revert CycleReceiptMismatch();
}
emit WarehouseCycleCompleted(
id, c.debt, c.principal, c.interest, c.collateral, cash, tab, c.stop
);
}
function _sell(
Clip memory c,
uint256 id,
uint256 initialCash,
bytes calldata data,
uint256 g,
uint256 w
) private returns (uint256 cash, uint256 tab) {
uint256 initialCollateral = collateralToken.balanceOf(address(this));
address venue = executor();
collateralToken.safeTransfer(venue, c.collateral);
PricingEvidence.record(
venue,
address(collateralToken),
address(prusd),
c.stop,
c.collateral,
PricingEvidence.Quote(g, 0, 0, w)
);
IFloorSettlementExecutor(venue)
.executeAtFloor(address(collateralToken), c.collateral, c.stop, data);
uint256 remaining =
collateralToken.balanceOf(address(this)) - (initialCollateral - c.collateral);
if (remaining > c.collateral) revert CycleReceiptMismatch();
uint256 venueCash = prusd.balanceOf(address(this)) - initialCash;
emit ISalePricingEvents.SaleMeasured(venue, c.collateral - remaining, venueCash);
if (
venueCash
< Math.mulDiv(
c.collateral - remaining, c.stop, 10 ** collateralDecimals, Math.Rounding.Ceil
)
) revert CycleReceiptMismatch();
if (remaining != 0) {
residualCycle = id;
residualAmount = remaining;
residualStop = c.stop;
collateralToken.forceApprove(treasury, remaining);
(, tab) = WarehouseTreasury(treasury).purchaseWarehouseResidual();
collateralToken.forceApprove(treasury, 0);
residualAmount = 0;
residualStop = 0;
}
if (collateralToken.balanceOf(address(this)) != initialCollateral - c.collateral) {
revert CycleReceiptMismatch();
}
cash = prusd.balanceOf(address(this)) - initialCash;
if (cash + tab < Math.mulDiv(c.debt, ONE + c.margin, ONE, Math.Rounding.Ceil)) {
revert CycleReceiptMismatch();
}
}
function _checkBindings() private view {
WarehouseVault v = WarehouseVault(vault);
IStabilityPoolRegistry r = v.poolRegistry();
if (
executor() == address(0) || r.poolForCollateral(collateralId) != poolId
|| r.getPool(poolId).pool != pool || !r.getPool(poolId).active
|| WarehouseTreasury(treasury).settlementSource(pool) != address(this)
|| address(WarehousePool(pool).settlementLedger()) != treasury
|| WarehousePool(pool).asset() != address(prusd)
) revert InvalidCycleBinding();
}
/// @dev Quote determines the aggregate interest-first split. Attribute each component pro rata to
/// facilities. Borrower allocation is reconstructed off chain from seizures and these events.
function _retire(Clip memory c) private {
uint256 principalSeen;
uint256 interestSeen;
for (uint256 j; j < facilities.length; ++j) {
uint256 fid = facilities[j];
FacilityDebt storage f = facilityDebt[fid];
uint256 p = _portion(c.principal, principalSeen, f.principal, totalPrincipal);
uint256 i = _portion(c.interest, interestSeen, f.interest, totalInterest);
principalSeen += f.principal;
interestSeen += f.interest;
f.principal -= p;
f.interest -= i;
if (p == 0 && i == 0) continue;
WarehouseVault(vault).retireWarehouseDebt(fid, p, i);
emit FacilityDebtRetired(fid, p, i);
}
assert(principalSeen == totalPrincipal && interestSeen == totalInterest);
totalCollateral -= c.collateral;
totalPrincipal -= c.principal;
totalInterest -= c.interest;
}
/// @dev Cumulative floors conserve every wei; each row receives its floor or ceil quota.
function _portion(uint256 amount, uint256 seen, uint256 weight, uint256 total)
private
pure
returns (uint256)
{
if (amount == 0) return 0;
return Math.mulDiv(amount, seen + weight, total) - Math.mulDiv(amount, seen, total);
}
/// @notice Task 0300 test-deployment teardown: sends `amount` of `token` to the caller, no accounting update.
/// This contract has no role table; the Treasury's TEST_DRAIN_ROLE decides.
function drain(address token, uint256 amount) external {
TestDrain.requireTreasuryRole(treasury);
TestDrain.send(token, amount);
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"lib/openzeppelin-community-contracts/contracts/:@openzeppelin/contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/",
"lib/openzeppelin-community-contracts/contracts/:@openzeppelin/contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"@openzeppelin/community-contracts/=lib/openzeppelin-community-contracts/contracts/",
"@openzeppelin7540/contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/contracts/",
"composable-cow/=lib/composable-cow/src/",
"lib/composable-cow/:@openzeppelin/=lib/composable-cow/lib/@openzeppelin/",
"lib/composable-cow/:@openzeppelin/=lib/composable-cow/lib/@openzeppelin/",
"cowprotocol/=lib/composable-cow/lib/cowprotocol/src/",
"safe/=lib/composable-cow/lib/safe/contracts/",
"@axelar-network/axelar-gmp-sdk-solidity/=lib/openzeppelin-community-contracts/lib/axelar-gmp-sdk-solidity/",
"@openzeppelin-contracts/=lib/openzeppelin-community-contracts/lib/@openzeppelin-contracts/",
"@openzeppelin/=lib/composable-cow/lib/@openzeppelin/",
"@zk-email/contracts/=lib/openzeppelin-community-contracts/lib/zk-email-verify/packages/contracts/",
"@zk-email/email-tx-builder/=lib/openzeppelin-community-contracts/lib/email-tx-builder/packages/contracts/",
"ds-test/=lib/composable-cow/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"murky/=lib/composable-cow/lib/murky/src/",
"openzeppelin-community-contracts/=lib/openzeppelin-community-contracts/contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"openzeppelin/=lib/composable-cow/lib/@openzeppelin/contracts/",
"wormhole-solidity-sdk/=lib/openzeppelin-community-contracts/lib/wormhole-solidity-sdk/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.