Verified contractPartialUNLICENSED
FLAMM
Address0xa07fd7e4cf0c10ec118586dbd39f8189165cfa46
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- Language
- solidity
- Optimization
- Yes, 100 runs
- EVM version
- cancun
- Via IR
- yes
- License
- UNLICENSED
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,475,524
- Creation transaction
- 0xc39f685bd3…fd9b0b6c87
- Libraries
- src/core/flamm/FLAMM.sol:FLAMMLane0x0445…374dacsrc/core/flamm/FLAMM.sol:FLAMMOpsLib0x1efd…5aea4fsrc/core/flamm/FLAMM.sol:FLAMMFlowLib0x5f1d…cb5caesrc/core/flamm/FLAMM.sol:FLAMMGateLib0x399e…7f82besrc/core/flamm/FLAMM.sol:FLAMMAdmitLib0x3182…49f294src/core/flamm/FLAMM.sol:FLAMMClaimLib0x1d7d…d0b523src/core/flamm/FLAMM.sol:FLAMMFenceLib0xf57d…c2a554src/core/flamm/FLAMM.sol:FLAMMFloatLib0xaa8c…08f6e2src/core/flamm/FLAMM.sol:FLAMMQuoteLib0xb890…466268src/core/flamm/FLAMM.sol:FLAMMTopUpLib0x8ee4…d506e4src/core/flamm/FLAMM.sol:FLAMMPolicyLib0x788c…1b963dsrc/core/flamm/FLAMM.sol:FLAMMSharedLib0x8784…4db256src/core/flamm/FLAMM.sol:FLAMMMaintainLib0xdde6…e26d55
52 files
The source code is large: one file is shown at a time. Choose a file in the list.
- src/core/flamm/FLAMM.solmain55.93 KB
- lib/openzeppelin-contracts-compat/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts-compat/contracts/token/ERC20/IERC20.sol2.77 KB
- lib/openzeppelin-contracts-compat/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/openzeppelin-contracts-compat/contracts/utils/math/Math.sol12.51 KB
- lib/openzeppelin-contracts-compat/contracts/utils/math/SafeCast.sol35.08 KB
- lib/openzeppelin-contracts-upgradeable-compat/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable-compat/contracts/token/ERC20/ERC20Upgradeable.sol12.23 KB
- lib/openzeppelin-contracts-upgradeable-compat/contracts/utils/ContextUpgradeable.sol1.19 KB
- src/core/PriceFeed.sol19.12 KB
- src/core/flamm/FLAMMAdmitLib.sol38.79 KB
- src/core/flamm/FLAMMBlindLib.sol60.72 KB
- src/core/flamm/FLAMMClaimLib.sol49.63 KB
- src/core/flamm/FLAMMClaimVault.sol1.65 KB
- src/core/flamm/FLAMMFenceLib.sol72.81 KB
- src/core/flamm/FLAMMFloatLib.sol62.2 KB
- src/core/flamm/FLAMMFlowLib.sol54.32 KB
- src/core/flamm/FLAMMGateLib.sol93.55 KB
- src/core/flamm/FLAMMKeptLib.sol45.86 KB
- src/core/flamm/FLAMMLane.sol70.59 KB
- src/core/flamm/FLAMMLawLib.sol61.53 KB
- src/core/flamm/FLAMMMaintainLib.sol42.7 KB
- src/core/flamm/FLAMMOpsLib.sol32.2 KB
- src/core/flamm/FLAMMPolicyLib.sol39.79 KB
- src/core/flamm/FLAMMQuoteLib.sol17 KB
- src/core/flamm/FLAMMRoute.sol16.45 KB
- src/core/flamm/FLAMMSettleLib.sol43.2 KB
- src/core/flamm/FLAMMSharedLib.sol13.11 KB
- src/core/flamm/FLAMMStore.sol137.17 KB
- src/core/flamm/FLAMMSwapLib.sol55.76 KB
- src/core/flamm/FLAMMTopUpLib.sol52.56 KB
- src/core/mm/MMRouterAdminLib.sol24.07 KB
- src/core/mm/MMRouterLib.sol72.71 KB
- src/core/mm/VenueAccountBase.sol15.61 KB
- src/core/mm/VenueReads.sol2.05 KB
- src/interfaces/core/IDepositAllowlist.sol1.06 KB
- src/interfaces/core/IEverlongCore.sol889 B
- src/interfaces/core/IPriceFeed.sol3.71 KB
- src/interfaces/core/flamm/IFLAMM.sol52.68 KB
- src/interfaces/core/flamm/IFLAMMHooks.sol8.36 KB
- src/interfaces/core/flamm/IHookCapabilities.sol2.63 KB
- src/interfaces/core/flamm/IPairHook.sol14.14 KB
- src/interfaces/core/mm/IAccountDeployer.sol3.04 KB
- src/interfaces/core/mm/IFinancingAccount.sol47.32 KB
- src/interfaces/core/mm/IHeldRepay.sol2.61 KB
- src/interfaces/core/mm/IMMRouter.sol70.37 KB
- src/interfaces/utils/integrations/IAggregatorV3Interface.sol818 B
- src/libraries/Constants.sol2.11 KB
- src/libraries/DelayLib.sol11.22 KB
- src/libraries/ReentrancyGuardLib.sol2.52 KB
- src/libraries/SafeTransferLib.sol5.11 KB
- src/propamm/libraries/PropAMMLaneLib.sol2.31 KB
src/core/flamm/FLAMM.sol
// SPDX-License-Identifier: UNLICENSED
// Copyright (c) 2025-2026 Everlong Labs Limited
pragma solidity ^0.8.26;
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {
FLAMMStore, InvalidConfig, PauseSet, PerformanceFeeSet, PerformanceFeeScheduled, ProtocolFeeSet,
NoPerformanceFeeScheduled, HookSetNotReady, PriceUnchecked, GuardianMayOnlyTighten, MintProRataCapSet, NoBand,
AlreadyBootstrapped, VenueFrozen, InvalidAmount, AdmissionCancelled
} from "src/core/flamm/FLAMMStore.sol";
import {FLAMMGateLib} from "src/core/flamm/FLAMMGateLib.sol";
import {FLAMMLane} from "src/core/flamm/FLAMMLane.sol";
import {FLAMMFlowLib} from "src/core/flamm/FLAMMFlowLib.sol";
import {FLAMMQuoteLib} from "src/core/flamm/FLAMMQuoteLib.sol";
import {FLAMMOpsLib} from "src/core/flamm/FLAMMOpsLib.sol";
import {FLAMMAdmitLib} from "src/core/flamm/FLAMMAdmitLib.sol";
import {FLAMMMaintainLib} from "src/core/flamm/FLAMMMaintainLib.sol";
import {FLAMMFloatLib} from "src/core/flamm/FLAMMFloatLib.sol";
import {FLAMMFenceLib} from "src/core/flamm/FLAMMFenceLib.sol";
import {FLAMMClaimLib} from "src/core/flamm/FLAMMClaimLib.sol";
import {FLAMMTopUpLib} from "src/core/flamm/FLAMMTopUpLib.sol";
import {FLAMMPolicyLib} from "src/core/flamm/FLAMMPolicyLib.sol";
import {FLAMMSharedLib} from "src/core/flamm/FLAMMSharedLib.sol";
import {NonReentrant, ReentrancyGuardLib} from "src/libraries/ReentrancyGuardLib.sol";
import {IFLAMM} from "src/interfaces/core/flamm/IFLAMM.sol";
/// @notice The pool: ERC-4626-shaped shares over its pool asset, a book of every token it lists (held, lent, posted
/// as collateral or owed), financed just in time on its credit pairs through the shared Router. Custody, NAV,
/// hard risk, access control and the lock live here; pricing policy lives in the hook set. Bodies run in
/// linked libraries over one storage namespace. The pool's owner is the curator, the owner of its core: the
/// role `src/propamm` and `src/periphery/door` call the operator. A beacon proxy whose beacon is the Factory:
/// one delayed implementation change moves every pool.
/// @dev Not a whole pool on its own. `FLAMMFront` serves `swap`, the cheap lane's `fillFromFront`, `laneStateOf` and
/// `lane`, `poke` and `recenter`, routes the swap's quotes and request (`previewSwap`, `pairRequest`), the
/// switches and the records' views (`switches`, `paused`, `tokenConfig`, `pairConfig`, `position`,
/// `collateralReserve`, `pending`) to their libraries, and hands it every other call. This contract serves the
/// shares, the proportional flows and the fees, which mint and burn them, the pool's identity and facts, and the
/// entries that take a struct or an enum, each checked here and handed on as it stands to its library
/// ({_forward}). Its fallback hands every other call to the library its dispatch table names for the selector
/// ({route}): the setters, the dials, the hook set's cancel, the trade masks, the pending table's cancel and the
/// retirements; the cheap lane's settings, the float actions, the protocol's spread fee and the operator's
/// share; the fences of venues and of tokens' custody, and their claims; the keeper's collateral maintainer.
/// Every routed writing entry checks its own caller and holds the pool's lock, in its library; a view does neither.
contract FLAMM is ERC20Upgradeable, NonReentrant {
/// @dev The pool's storage (`FLAMMStore.s`).
function _s() private pure returns (FLAMMStore.S storage) {
return FLAMMStore.s();
}
// ------------------------------------------------------------------ construction
/// @dev This implementation's own address, which {fullImplementation} names (`FLAMMFront` routes the call here).
address private immutable SELF;
/// @dev Records this implementation's address and locks its initializers: only a proxy holds a pool's state.
constructor() {
SELF = address(this);
_disableInitializers();
}
/// @notice The pool implementation `FLAMMFront` deploys and routes to: this contract.
function fullImplementation() external view returns (address) {
return SELF;
}
/// @notice Proxy initializer; the Factory calls it from the proxy constructor and is bound as `factory`.
/// @dev The ten arguments, in order: the core, the pool asset (token 0), the Router, the price feed, the deposit
/// allowlist (zero: anyone enters), the share name, the share symbol, the pool-wide `FLAMMStore.PoolInit`, the
/// `FLAMMStore.TokenInit` list from token 1 on and the `FLAMMStore.PairInit` list of credit pairs, which
/// `initializeHooks` lists at the Router from the same inputs. All but the two strings stay unnamed here: the
/// pool hands its calldata as it stands to `FLAMMAdmitLib.initializePool`, whose signature names them.
function initialize(
address,
address,
address,
address,
address,
string calldata name_,
string calldata symbol_,
FLAMMStore.PoolInit calldata,
FLAMMStore.TokenInit[] calldata,
FLAMMStore.PairInit[] calldata
) external initializer {
__ERC20_init(name_, symbol_);
_forward(address(FLAMMAdmitLib), FLAMMAdmitLib.initializePool.selector);
}
/// @notice Installs the genesis hook set, lists `initialize`'s tokens and pairs at the Router, and admits the
/// genesis venues (Factory only, once, before `bootstrap`).
function initializeHooks(
IFLAMM.HookSet calldata,
IFLAMM.VenueInit[] calldata,
FLAMMStore.TokenInit[] calldata,
FLAMMStore.PairInit[] calldata
) external onlyFactory {
_forward(address(FLAMMAdmitLib), FLAMMAdmitLib.initializeHooks.selector);
}
/// @notice As `IFLAMM.poolCodeVersion`: the Factory takes a new implementation only where this is strictly higher.
function poolCodeVersion() external pure virtual returns (uint32) {
return 2;
}
// ------------------------------------------------------------------ hook-set ceremony (curator, delayed, paused)
/// @notice The curator schedules a set, which executes after `governanceDelaySec` while paused; a reschedule
/// replaces the pending set and restarts the delay. While the band's ceiling admits no band or a raise to
/// it is scheduled, even one that cannot land before the set, the set waits
/// `FLAMMStore.MIN_BAND_DELAY_SEC` at least, as the band's removal does (`FLAMMOpsLib.hookSetDue`, which
/// `pendingHookSet` reports). At the schedule and at the execution alike, on a pool with no band the set's
/// swap hook must declare `HOOK_CAP_UNPRICED`, and while a pair that owes the pool asset or posts another
/// token is listed, `HOOK_CAP_TWO_SIDED`.
function scheduleHookSet(IFLAMM.HookSet calldata) external onlyCurator nonReentrant {
_forward(address(FLAMMOpsLib), FLAMMOpsLib.scheduleHookSet.selector);
}
/// @notice Installs the scheduled set, which the caller passes again: any other set reverts `NoHookSetScheduled`.
function executeHookSet(IFLAMM.HookSet calldata) external onlyCurator nonReentrant {
_forward(address(FLAMMOpsLib), FLAMMOpsLib.executeHookSet.selector);
}
/// @notice As `IFLAMM.bootstrap`.
/// @dev Once: the dead shares it mints never burn, so the supply is zero only before it.
function bootstrap(uint256 assets, address to) external onlyFactory nonReentrant returns (uint256 shares) {
if (totalSupply() != 0) revert AlreadyBootstrapped();
shares = FLAMMMaintainLib.bootstrap(_s(), assets, to);
_mint(address(0xdead), FLAMMStore.MINIMUM_SHARES);
shares -= FLAMMStore.MINIMUM_SHARES;
_mint(to, shares);
}
/// @notice The operator's seed of token `token` alone, for a book of more than the pool asset: `assets` into
/// custody, minting `to` the shares they buy at NAV, the fee skimmed first. Only until the pool first
/// opens, for good (`FLAMMStore.S.opened`, {_update}), and while `to` holds every share but the dead ones
/// (`DepositNotPermitted` otherwise): every live share was then minted to `to` and none has ever moved, so
/// the price moves value between no two holders. Any transfer of shares to another address opens the
/// pool, a whole stake's too, so shares lent to the operator, or placed in an escrow or a vault, end the
/// seed whoever lends them and for however long; so does a mint to a second holder, a fee's included. A
/// pool whose other holders have all left takes no seed again, and a pool that waits for its deposit
/// basket to take an entry (`FLAMMGateLib.basketGated`) is no exception: opened before its seed of token
/// 1, it records no basket and takes no pro-rata entry, so its operator seeds token 1 before any share
/// leaves them. Seeded with the hook's stable leg on the bootstrap's pool asset (its book at its anchor
/// and coordinate, `EverlongHook.bookFor`), the pool opens with that leg held, not virtual. Not while a
/// fence holds a pool part (`VenueFrozen`, {partedFences}), as no entry: NAV leaves the part out. On a
/// pool whose cheap lane is on the seed restarts the fee mark at the deposit basket it records
/// (`FLAMMLane`), so it mints to the operator alone (`InvalidConfig` otherwise): the mark restarts only
/// while the operator is the one address that holds a stake, and no other has since the bootstrap.
function seedLeg(uint8 token, uint256 assets, address to) external onlyCurator nonReentrant returns (uint256 shares) {
FLAMMStore.S storage $ = _s();
// no seed of a token whose custody a fence holds out (the book holds none of it till the fence's lift but what
// exits bring in against a kept share's debt), and on a cheap-lane pool none to anyone but the curator, whose
// fee mark it restarts
if (FLAMMFenceLib.isOut($, token) || $.swapBits & FLAMMStore.SWAP_LANE != 0 && to != msg.sender) {
revert InvalidConfig();
}
if (partedFences() != 0) revert VenueFrozen();
_skim();
shares = FLAMMMaintainLib.seed(_s(), token, assets, to, totalSupply(), balanceOf(to));
_mint(to, shares);
_basket();
}
// ------------------------------------------------------------------ auth and guards
/// @dev The Factory that created the pool (`NotFactory`).
modifier onlyFactory() {
FLAMMStore.requireFactory(_s());
_;
}
/// @dev The curator (`NotCurator`).
modifier onlyCurator() {
FLAMMStore.requireCurator(_s());
_;
}
/// @dev The curator or the pool's guardian (`NotGuardianOrCurator`).
modifier curatorOrGuardian() {
_curatorOrGuardian();
_;
}
/// @dev Keeper, curator or the pool's controller hook.
modifier maintainer() {
FLAMMStore.requireKeeperOrCurator(_s(), true);
_;
}
/// @dev Whether the caller is the guardian, not the curator; `NotGuardianOrCurator` for any other.
function _curatorOrGuardian() private view returns (bool guardian) {
return FLAMMStore.curatorOrGuardian(_s());
}
/// @dev Runs `lib`'s entry `sel`, whose parameters are this call's own, on this call's arguments as they stand, so
/// the pool hands on what its own entry decoded; returns what it returns and bubbles its revert. The entries
/// that take a struct or an enum come this way, after this contract's check of their caller and under its
/// lock: a library's selector for one differs from the pool's, so the dispatch table, which hands a call on
/// under its own selector, cannot route them.
function _forward(address lib, bytes4 sel) private returns (bytes memory ret) {
assembly ("memory-safe") {
let m := mload(0x40)
mstore(m, sel)
calldatacopy(add(m, 4), 4, sub(calldatasize(), 4))
let ok := delegatecall(gas(), lib, m, calldatasize(), 0, 0)
let n := returndatasize()
ret := m
mstore(ret, n)
returndatacopy(add(ret, 0x20), 0, n)
if iszero(ok) { revert(add(ret, 0x20), n) }
mstore(0x40, add(add(ret, 0x20), and(add(n, 31), not(31))))
}
}
/// @dev No entry at a frozen venue mark (`FLAMMGateLib.frozen`): its figures are no price to enter at, and the
/// thaw's first skim would charge the entrant for gains made before it entered; nor while a venue fence holds
/// a pool part, written off or not ({partedFences}), a slot both retired and idle (`FLAMMGateLib.isFrozen`),
/// as no entry takes its slice there and NAV after a write-off leaves out a part every share owns (a token's
/// part is read with the entry guards' word, `FLAMMFlowLib`). Only a pool with a gated venue or such a slot
/// asks; read after the skim, which abstains at a frozen venue mark.
function _notFrozen() private view {
FLAMMStore.S storage $ = _s();
(uint256 retired, uint256 idle) = ($.retiredVenues, $.idleVenues);
if (($.gatedVenues & ~(retired | idle)) | (retired & idle) != 0 && FLAMMGateLib.isFrozen($)) {
revert VenueFrozen();
}
}
/// @dev After the curator's seed on a pool whose cheap lane is on: the deposit basket, afresh
/// (`FLAMMLane.recordBasket`).
function _basket() private {
FLAMMStore.S storage $ = _s();
if ($.swapBits & FLAMMStore.SWAP_LANE != 0) FLAMMLane.recordBasket($, totalSupply());
}
/// @dev The pool's dispatch table. Every call no entry here serves goes, with its own calldata, to the one library
/// {route} names for its selector, and a selector the table does not hold reverts with no data. A row names a
/// library's entry by its own selector, so the table holds an entry only where the library declares it, and
/// no call reaches a library's other code: the helpers that take the pool's storage as an argument, and the
/// ones another library calls. Each routed writing entry checks its own caller and holds the pool's lock.
fallback() external {
address lib = route(msg.sig);
assembly ("memory-safe") {
if iszero(lib) { revert(0, 0) }
let m := mload(0x40)
calldatacopy(m, 0, calldatasize())
let ok := delegatecall(gas(), lib, m, calldatasize(), 0, 0)
returndatacopy(m, 0, returndatasize())
if iszero(ok) { revert(m, returndatasize()) }
return(m, returndatasize())
}
}
/// @dev The library that serves selector `sig`, zero where none does: one comparison and an early return per row,
/// as `FLAMMFront.route`. No row's selector is an entry's of this contract or of `FLAMMFront`, which would
/// hide it, and no selector stands in two rows. A routed entry pays a comparison per row above its own and a
/// call into its library, which checks its caller: a setter, or a caller its check refuses, pays a few
/// thousand gas more than a check in this contract would. Setters are rare, and no swap or fill routes
/// through this table. `IFLAMMRouted` declares the routed entries no other interface of the pool does.
function route(bytes4 sig) internal view returns (address) {
// the keeper's calls, first: a row costs the rows before it one comparison each
if (sig == FLAMMFloatLib.refill.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.flush.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.flushPair.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.refillFloat.selector) return address(FLAMMFloatLib);
if (sig == FLAMMTopUpLib.maintainCollateral.selector) return address(FLAMMTopUpLib);
if (sig == FLAMMPolicyLib.setDials.selector) return address(FLAMMPolicyLib);
// the cheap lane's settings, the float and the fees
if (sig == FLAMMFloatLib.collectSpreadFee.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.initLane.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.initLaneTokens.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setLanePairs.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setTokenOutflowCaps.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.laneTokens.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.syncListings.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setPairHook.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.pairHook.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setStrictMode.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setCreditPath.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setOutflowCaps.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setIdleFloor.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.idleFloor.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setLocalRefill.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.localRefill.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.custodyBlind.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.lanePauser.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setSpreadFeeRates.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.syncFeeKinds.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.feeRates.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.cancelPerformanceFee.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.setOperatorShareBp.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.executeOperatorShare.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.cancelOperatorShare.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.operatorShare.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.basket.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.basketTokens.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.collectOperatorFee.selector) return address(FLAMMFloatLib);
if (sig == FLAMMFloatLib.operatorFeeOwed.selector) return address(FLAMMFloatLib);
// the bounds where legs share one reserve's cash
if (sig == FLAMMSharedLib.sharedUnits.selector) return address(FLAMMSharedLib);
if (sig == FLAMMSharedLib.releaseRoom.selector) return address(FLAMMSharedLib);
if (sig == FLAMMSharedLib.heldLegsCheck.selector) return address(FLAMMSharedLib);
// the fences and their claims
if (sig == FLAMMFenceLib.fenceVenue.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.probeFence.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.fenceToken.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.writeOff.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.abandonFence.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.liftFence.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.liftToken.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.claimVault.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.mates.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.fencedVenues.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.fences.selector) return address(FLAMMFenceLib);
if (sig == FLAMMFenceLib.fenceOf.selector) return address(FLAMMFenceLib);
if (sig == FLAMMClaimLib.settleClaim.selector) return address(FLAMMClaimLib);
if (sig == FLAMMClaimLib.transferClaim.selector) return address(FLAMMClaimLib);
if (sig == FLAMMClaimLib.transferClaims.selector) return address(FLAMMClaimLib);
if (sig == FLAMMClaimLib.unwindFence.selector) return address(FLAMMClaimLib);
if (sig == FLAMMClaimLib.drawParked.selector) return address(FLAMMClaimLib);
if (sig == FLAMMClaimLib.claimOf.selector) return address(FLAMMClaimLib);
if (sig == FLAMMClaimLib.parkedOf.selector) return address(FLAMMClaimLib);
if (sig == FLAMMClaimLib.claimAmounts.selector) return address(FLAMMClaimLib);
if (sig == FLAMMClaimLib.previewClaims.selector) return address(FLAMMClaimLib);
// the policy setters and the delayed changes
if (sig == FLAMMPolicyLib.setTokenConfig.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setMinSupplyBatch.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setTokenSupplyCap.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setFeeBounds.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setPairCaps.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setOracleBand.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setMaxDrawnTokens.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setVenueFlags.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setVenueCaps.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setFeatures.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setBandAndFeeCeilings.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setCollateralReserve.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.setTradePairs.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.executeTradePairs.selector) return address(FLAMMPolicyLib);
if (sig == FLAMMPolicyLib.cancelTradePairs.selector) return address(FLAMMPolicyLib);
// the hook set, the pending table and the retirements
if (sig == FLAMMOpsLib.cancelHookSet.selector) return address(FLAMMOpsLib);
if (sig == FLAMMOpsLib.pendingHookSet.selector) return address(FLAMMOpsLib);
if (sig == FLAMMOpsLib.hookContext.selector) return address(FLAMMOpsLib);
if (sig == FLAMMAdmitLib.cancel.selector) return address(FLAMMAdmitLib);
if (sig == FLAMMAdmitLib.retirePair.selector) return address(FLAMMAdmitLib);
if (sig == FLAMMAdmitLib.retireVenue.selector) return address(FLAMMAdmitLib);
return address(0);
}
/// @dev Every move of shares. A credit that makes an address a holder opens the pool for good
/// (`FLAMMStore.S.opened`), which ends the seed ({seedLeg}), where it is a transfer, of any size (part of a
/// stake or all of it, a loan, an escrow, a hand-off, a holder's whole balance to themselves), or a mint while
/// any share past the dead ones is held elsewhere (an entry, a fee's mint to another receiver). So while the
/// pool is closed one address at most holds a share past the dead ones, every such share was minted to it,
/// and none has moved. The dead shares' mint, the first, finds nothing held elsewhere, and a credit to the
/// dead address finds it a holder already. A burn, a credit of nothing and a credit to a holder read no flag,
/// and an open pool reads no supply.
function _update(address from, address to, uint256 value) internal override {
super._update(from, to, value);
if (value != 0 && to != address(0) && balanceOf(to) == value) {
FLAMMStore.S storage $ = _s();
// a sum past the word would wrap small and open the pool, the safe way; no supply comes near it
unchecked {
if (!$.opened && (from != address(0) || value + FLAMMStore.MINIMUM_SHARES < totalSupply())) {
$.opened = true;
}
}
}
}
/// @dev Both parts of the fee are struck at the supply before either mint. `marked`: the skim read the fee mark (or
/// the pool has no supply), which a rate rise requires.
function _skim() private returns (bool marked) {
address to;
uint256 fee;
address protocolTo;
uint256 protocolFee;
(marked, to, fee, protocolTo, protocolFee) = FLAMMMaintainLib.crystallize(_s(), totalSupply());
if (fee != 0) _mint(to, fee);
if (protocolFee != 0) _mint(protocolTo, protocolFee);
}
// ------------------------------------------------------------------ identity and facts
/// @notice Token 0, the pool asset: the unit of shares and NAV.
function asset() public view returns (address) {
return _s().poolAsset;
}
/// @notice Token 1, the numeraire, which the periphery binds.
function loanAsset() external view returns (address) {
return _s().tokens[1].token;
}
/// @notice How many tokens the pool lists, the pool asset included.
function tokenCount() external view returns (uint256) {
return _s().tokenCount;
}
/// @notice How many credit pairs the pool lists, retired ones included.
function pairCount() external view returns (uint256) {
return _s().pairCount;
}
/// @notice The shared Router that holds the pool's venues.
function router() external view returns (address) {
return address(_s().router);
}
/// @notice The USD feed the pool prices on.
function priceFeed() external view returns (address) {
return address(_s().priceFeed);
}
/// @notice The pool's core, which names its curator (`owner`), guardian, keeper and fee receiver.
function core() external view returns (address) {
return address(_s().core);
}
/// @notice The allowlist an entry's receiver must pass; zero: anyone enters.
function depositAllowlist() external view returns (address) {
return _s().allowlist;
}
/// @notice The Factory that created the pool, its beacon.
function factory() external view returns (address) {
return _s().factory;
}
/// @notice The installed hook set: the swap hook and the optional controller.
function hooks() external view returns (IFLAMM.HookSet memory) {
FLAMMStore.S storage $ = _s();
return IFLAMM.HookSet($.invariantHook, $.controllerHook);
}
/// @notice As `IFLAMM.retiredVenues`: the slots every walk of the venues skips, the fenced ones among them
/// (`FLAMMFenceLib.fencedVenues` tells them apart).
function retiredVenues() external view returns (uint256) {
return _s().retiredVenues;
}
/// @notice As `IFLAMM.totalAssets`: it refuses an unchecked price and, while a fee rate and a band are on, an
/// unread fee mark (`PriceUnchecked`), and a frozen venue mark (`VenueFrozen`), as both conversions do.
function totalAssets() public view returns (uint256) {
ReentrancyGuardLib._readGuard();
return FLAMMGateLib.totalAssets(_s());
}
/// @notice The pool-wide policy; per-token and per-pair policy live on `tokenConfig` and `pairConfig`.
function limits() external view returns (IFLAMM.Limits memory) {
FLAMMStore.S storage $ = _s();
// the fee mark as the pool carries it, divided by the share scale, which is one at least on a pool
uint256 peak = $.peakSharePriceWad;
uint256 scale = $.shareScale;
assembly ("memory-safe") {
peak := div(peak, scale)
}
return IFLAMM.Limits(
$.maxPriceAgeSec,
$.feeFloorWad,
$.feeCapWad,
$.performanceFeeBp,
uint128(peak),
$.maxPerformanceFeeBp,
$.protocolFeeBp,
$.pendingPerformanceFeeBp,
$.performanceFeeExecutableAt,
$.mintProRataCap
);
}
/// @notice As `IFLAMM.ceilings`.
function ceilings()
external
view
returns (uint64 bandWad, uint64 feeCapWad, uint64 pendingBandWad, uint64 pendingFeeCapWad, uint48 executableAt)
{
FLAMMStore.S storage $ = _s();
(bandWad, feeCapWad) = ($.bandCeilingWad, $.feeCapCeilingWad);
(pendingBandWad, pendingFeeCapWad, executableAt) =
($.pendingBandCeilingWad, $.pendingFeeCapCeilingWad, $.ceilingsExecutableAt);
}
// ------------------------------------------------------------------ ERC-4626 conversions
/// @notice As `IFLAMM.convertToShares`: at NAV, excluding fees; reverts as `totalAssets` does.
function convertToShares(uint256 assets) external view returns (uint256) {
return FLAMMQuoteLib.convert(_s(), assets, totalSupply(), true);
}
/// @notice As `IFLAMM.convertToAssets`: at NAV, excluding fees; reverts as `totalAssets` does.
function convertToAssets(uint256 shares) external view returns (uint256) {
return FLAMMQuoteLib.convert(_s(), shares, totalSupply(), false);
}
// ------------------------------------------------------------------ proportional flows
/// @notice As `IFLAMM.depositProRata`.
function depositProRata(
uint256 poolAssets,
address receiver,
uint256[] calldata maxLoanAssetIn,
uint256[] calldata minLoanAssetOut,
uint256 minSharesOut,
uint256 deadline
) external nonReentrant returns (uint256 shares, uint256 loanAssetIn, uint256 loanAssetOut) {
_skim();
_notFrozen();
(shares, loanAssetIn, loanAssetOut) = FLAMMFlowLib.depositProRata(
_s(), poolAssets, receiver, maxLoanAssetIn, minLoanAssetOut, minSharesOut, deadline, totalSupply()
);
_mint(receiver, shares);
}
/// @notice As `IFLAMM.mintProRata`. While a fee rate is on it needs a skim that read the fee mark (`PriceUnchecked`
/// otherwise). The supply after it is capped by `mintProRataCap` (zero, as at birth, closes it).
function mintProRata(
uint256 shares,
address receiver,
uint256[] calldata maxIn,
uint256[] calldata minOut,
uint256 deadline
) external nonReentrant returns (uint256[] memory tokenIn, uint256[] memory tokenOut) {
bool marked = _skim();
_notFrozen();
(tokenIn, tokenOut) = FLAMMFlowLib.mint(_s(), shares, receiver, maxIn, minOut, deadline, totalSupply(), marked);
_mint(receiver, shares);
}
/// @notice As `IFLAMM.redeemProRata`. It refuses a `receiver` that is zero, the pool itself or the void
/// (`InvalidAmount`), as the swap refuses its `to`, so no exit pays its holdings back past custody for the
/// next caller, nor records its claims to the pool or to the void, whose part the fence's accounts hold
/// apart.
function redeemProRata(
uint256 shares,
address receiver,
address owner,
uint256[] calldata maxIn,
uint256[] calldata minOut,
uint256 deadline
) external nonReentrant returns (uint256[] memory tokenIn, uint256[] memory tokenOut) {
if (receiver == address(0) || receiver == address(this) || receiver == FLAMMFenceLib.VOID) revert InvalidAmount();
FLAMMStore.S storage $ = _s();
// the venues an exit reads again and again, accrued first (`FLAMMGateLib.accrueRead`)
FLAMMGateLib.accrueRead($, 0);
_skim();
uint256 supply = totalSupply();
bool parted;
uint256[] memory cuts;
(tokenIn, tokenOut, parted, cuts) =
FLAMMFlowLib.redeem($, shares, receiver, owner, maxIn, minOut, deadline, supply, balanceOf(owner));
// its share of each fence that holds a pool part stays there, its receiver's claim: read where a marker says a
// fence may hold one, a slot both retired and idle (the exit's own read of the Router's word) or a token's open
// record (`FLAMMStore.SWAP_FENCE`, the exit's own read of the first word), less what the exit paid from its
// claim on a token's record (`cuts`, `FLAMMKeptLib.fromRecord`), recorded whenever it paid any
if (parted || cuts.length != 0) FLAMMFenceLib.recordClaims($, receiver, shares, supply, cuts);
if (msg.sender != owner) _spendAllowance(owner, msg.sender, shares);
_burn(owner, shares);
}
/// @notice As `IFLAMM.previewDepositProRata`: at the supply after the fee the flow crystallizes first; it quotes
/// the legs, not whether the flow executes.
function previewDepositProRata(uint256 poolAssets)
external
view
returns (uint256 shares, IFLAMM.VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut)
{
ReentrancyGuardLib._readGuard();
(shares, legs, tokenIn, tokenOut) = FLAMMQuoteLib.previewDeposit(_s(), poolAssets, totalSupply());
FLAMMSharedLib.heldLegsCheck(legs);
}
/// @notice As `IFLAMM.previewMintProRata`: at the supply after the fee the flow crystallizes first; it quotes the
/// legs, not whether the flow executes.
function previewMintProRata(uint256 shares)
external
view
returns (IFLAMM.VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut)
{
ReentrancyGuardLib._readGuard();
(legs, tokenIn, tokenOut) = FLAMMQuoteLib.previewShares(_s(), shares, totalSupply(), true);
FLAMMSharedLib.heldLegsCheck(legs);
}
/// @notice As `IFLAMM.previewRedeemProRata`: at the supply after the fee the flow crystallizes first; it quotes the
/// legs, not whether the flow executes.
function previewRedeemProRata(uint256 shares)
external
view
returns (IFLAMM.VenueLeg[] memory legs, uint256[] memory tokenIn, uint256[] memory tokenOut)
{
ReentrancyGuardLib._readGuard();
return FLAMMQuoteLib.previewShares(_s(), shares, totalSupply(), false);
}
// ------------------------------------------------------------------ the observation and the protocol's spread fee
/// @notice The spread fee the pool owes in token `t`, native units (`FLAMMStore.feeOwed`): the hook fills' record
/// and, for token 1 on a pool whose cheap lane is on, the accrual in `laneWord`, the whole record, which
/// holds the operator's share owed with the protocol's part (`FLAMMFloatLib.operatorFeeOwed`; the
/// protocol's is this less that, but while the token's fence holds the record, which can leave this under
/// that until the fence's lift restores it). Custody keeps it as far as it holds it, none of it the pool's
/// own; `FLAMMFloatLib.collectSpreadFee` pays the protocol's and `FLAMMFloatLib.collectOperatorFee` the
/// operator's, token by token.
function spreadFeeOwed(uint8 t) external view returns (uint256) {
return FLAMMStore.feeOwed(_s(), t);
}
// ------------------------------------------------------------------ the trade masks
/// @notice The pairs that trade now, bit `16 * i + j` for a swap of token `i` for token `j`: those both a hook of
/// the pool prices (`hookPairs`, asked at a hook's installation, a pair hook's removal, a token's listing,
/// the listings' resync and an opening of the cheap lane's pairs) and the curator lets trade
/// (`curatorPairs`); then the curator's scheduled mask and when anyone may apply it, zero when none or past
/// its window (`FLAMMStore.executionWindow`), where it has lapsed. While a token's fence record is open,
/// `curatorPairs` also shows the trade bits its fence closed, which its lift restores
/// (`FLAMMStore.S.fenceTrades`) and `tradable` leaves out.
function tradablePairs()
external
view
returns (uint256 tradable, uint256 hookPairs, uint256 curatorPairs, uint256 pendingPairs, uint48 executableAt)
{
FLAMMStore.S storage $ = _s();
(hookPairs, curatorPairs) = ($.hookPairs & ~FLAMMStore.HOOK_PAIRS_SPLIT, $.tradePairs);
(tradable, pendingPairs, executableAt) = (hookPairs & curatorPairs, $.pendingTradePairs, $.tradePairsExecutableAt);
if (block.timestamp > executableAt + FLAMMStore.executionWindow($.governanceDelaySec)) {
(pendingPairs, executableAt) = (0, 0);
}
if ($.swapBits & FLAMMStore.SWAP_FENCE != 0) curatorPairs |= $.fenceTrades;
}
// ------------------------------------------------------------------ fee
/// @notice As `IFLAMM.skimPerformanceFee`: mints the curator's part to the core's fee receiver and the protocol's
/// to the Factory's `protocolFeeReceiver`; permissionless. With both parts off it still raises the fee
/// mark.
function skimPerformanceFee() external nonReentrant {
_skim();
}
/// @notice The curator's rate, at most `maxPerformanceFeeBp`. A cut, or the current rate, applies at once and
/// clears a scheduled rise, which the curator or the guardian may also drop on its own
/// (`FLAMMFloatLib.cancelPerformanceFee`); a rise is scheduled for `governanceDelaySec` from now, replacing
/// one already scheduled, and anyone executes it then (`executePerformanceFee`). A due rise does not lapse:
/// it stays scheduled until executed, cut, cancelled or replaced. A pool with no market band charges no fee
/// and takes no rise: one is refused when scheduled (`NoBand`), and one scheduled before the band went
/// waits for a band, as its skim reads no fee mark.
/// @dev Every applied change skims at the old rates before it writes. A rise lands only on a skim that read the fee
/// mark and while no fence holds a pool part, written off or not ({partedFences}: the part's return is charged
/// when it comes back, so a rise before it would reach gains made before the rise), else it reverts
/// `PriceUnchecked` and stays scheduled, so a new rate never reaches a gain the skim left uncharged; a cut, or
/// the current rate, always lands.
function setPerformanceFeeBp(uint16 feeBp) external onlyCurator nonReentrant {
FLAMMStore.S storage $ = _s();
if (feeBp > $.maxPerformanceFeeBp) revert InvalidConfig();
if (feeBp <= $.performanceFeeBp) {
_setPerformanceFee(feeBp);
return;
}
if ($.noBand) revert NoBand();
uint48 due = uint48(block.timestamp + $.governanceDelaySec);
($.pendingPerformanceFeeBp, $.performanceFeeExecutableAt) = (feeBp, due);
emit PerformanceFeeScheduled(feeBp, due);
}
/// @notice Applies the curator's scheduled rise once its delay has passed, after a skim at the old rates;
/// permissionless. Reverts `HookSetNotReady` before then, as an early admission does, and `PriceUnchecked`
/// while that skim cannot read the fee mark (NAV unchecked, the price over `uint128`, no market band) or a
/// fence holds a pool part, written off or not: the rise stays scheduled.
function executePerformanceFee() external nonReentrant {
FLAMMStore.S storage $ = _s();
uint48 due = $.performanceFeeExecutableAt;
if (due == 0) revert NoPerformanceFeeScheduled();
if (block.timestamp < due) revert HookSetNotReady();
_setPerformanceFee($.pendingPerformanceFeeBp);
}
/// @dev Skims at the old rates first, then writes `feeBp` and clears any scheduled rise.
function _setPerformanceFee(uint16 feeBp) private {
bool marked = _skim();
FLAMMStore.S storage $ = _s();
if ((!marked || partedFences() != 0) && feeBp > $.performanceFeeBp) revert PriceUnchecked();
($.performanceFeeBp, $.pendingPerformanceFeeBp, $.performanceFeeExecutableAt) = (feeBp, 0, 0);
emit PerformanceFeeSet(feeBp);
}
/// @notice As `IFLAMM.setProtocolFeeBp`. A pool whose cheap lane is on pays the protocol its spread fee instead
/// (`FLAMMFloatLib.setSpreadFeeRates`), so its high-water rate stays zero: a nonzero one is refused there.
/// A rise waits as the curator's does, while a fence holds a pool part ({partedFences}); a cut lands.
/// @dev The Factory, its only caller, caps the rate at `FLAMMStore.MAX_PROTOCOL_FEE_BP`.
function setProtocolFeeBp(uint16 feeBp) external onlyFactory nonReentrant {
FLAMMStore.S storage $ = _s();
if (feeBp != 0 && $.swapBits & FLAMMStore.SWAP_LANE != 0) revert InvalidConfig();
bool marked = _skim();
if ((!marked || partedFences() != 0) && feeBp > $.protocolFeeBp) revert PriceUnchecked();
$.protocolFeeBp = feeBp;
emit ProtocolFeeSet(feeBp);
}
/// @notice As `IFLAMMFence.partedFences`: the fences holding a pool part, written off or not, bit `i` for venue `i`
/// (its slot retired and idle), bit `32 + t` for token `t`'s custody (read while a token's record is open,
/// `FLAMMStore.SWAP_FENCE`, as such a token's is), bit `48 + i` for venue `i`'s kept share
/// (`FLAMMStore.KEPT_SHIFT`, which NAV counts behind the senior claims). While it is not zero the entries
/// refuse (`VenueFrozen`),
/// no fee rate rises and no fee mints, and NAV, where it reads (after the write-off), is a lower bound that
/// leaves those parts out though every share owns its slice of them: a flow that hands shares over at NAV
/// waits too. Zero: NAV, where it reads, is exact. Served here, with no lock read, so the periphery reads
/// it at one call's cost.
function partedFences() public view returns (uint256 parts) {
FLAMMStore.S storage $ = _s();
uint256 w = $.fenceWord;
parts = $.retiredVenues & $.idleVenues | ((w >> FLAMMStore.KEPT_SHIFT) & FLAMMStore.FENCE_VENUES) << 48;
if ($.swapBits & FLAMMStore.SWAP_FENCE != 0) parts |= ((w >> FLAMMStore.PARTED_TOKENS_SHIFT) & 0xffff) << 32;
}
// ------------------------------------------------------------------ controls
/// @notice Guardian or curator pauses; only the curator unpauses. On a pool whose cheap lane is on the two pauses
/// are apart (`FLAMMLane.setLanePause`): the guardian in office lifts the guardian's, and the curator only
/// once the guardian that set it has been rotated out, which on a pool whose core is a `DelayedAuthority`
/// waits that authority's `DELAY` (at least `governanceDelaySec`); no protocol role lifts it
/// (`GuardianPauseStands`). The curator's stays the curator's to lift, and the pool stays paused while
/// either stands. The one setter outside the pool's lock, so a pause lands even from inside a flow's
/// callback.
/// @dev While paused a swap runs only on the hook pair, where its input is owed (the covering swap) or its output
/// is no live pair's debt and backs no debt, and it never borrows, rotates or lends: on a pool that owes token
/// 1 its buys run and its sells stop, mirrored on one that owes the pool asset. No swap past the hook pair
/// runs. Deposits, `poke`, `recenter` and a custody-blind pool's refill stop too; redemptions,
/// `maintainCollateral`, `proveDebtFree`, `collectSpreadFee`, cancels, dial cuts and the emergency path never.
/// A cheap fill's bid on the hook pair stops; its ask, as a buy, runs, but on a custody-blind pool
/// (`FLAMMStore.CUSTODY_BLIND`), where both sides stop. No cheap fill past the hook pair runs (`FLAMMRoute`).
function setPaused(bool p) external {
FLAMMStore.S storage $ = _s();
if ($.swapBits & FLAMMStore.SWAP_LANE != 0) p = FLAMMLane.setLanePause($, p);
else if (p) _curatorOrGuardian();
else FLAMMStore.requireCurator($);
$.paused = p;
emit PauseSet(p, msg.sender);
}
/// @notice Two-phase (curator), through the pending table: the first call schedules the token, the identical call
/// within one day (or `governanceDelaySec`, if longer) after `governanceDelaySec` lists it; past that window it lapses, and the
/// next identical call schedules it again. `cancel` withdraws it. A curator must not list a second address
/// of a ledger the pool already lists: each leg's custody reads as past the other's (`IFLAMM.swap`).
function addToken(FLAMMStore.TokenInit calldata) external onlyCurator nonReentrant {
_forward(address(FLAMMAdmitLib), FLAMMAdmitLib.addToken.selector);
}
/// @notice Two-phase (curator), as `addToken`, waiting `governanceDelaySec` and at least
/// `FLAMMStore.MIN_BAND_DELAY_SEC`, so a holder who objects to a pool that turns two-sided is out before it
/// lands. Any two listed tokens may pair, each pair of tokens in each role once, retired ones included. A
/// pair that owes the pool asset or posts another token needs a swap hook that declares
/// `HOOK_CAP_TWO_SIDED`.
function addPair(FLAMMStore.PairInit calldata) external onlyCurator nonReentrant {
_forward(address(FLAMMAdmitLib), FLAMMAdmitLib.addPair.selector);
}
/// @notice Two-phase (curator), as `addToken`; scheduling returns `type(uint16).max`. With no market band the pool
/// reads no price, so it admits a venue only with its borrowing off. A kind whose capabilities break the
/// pool's admission rules (`IFinancingAccount` ADMISSION) is refused when the schedule executes, not when
/// it is scheduled: its account exists only then. The execution clears the slot's first probe read
/// (`FLAMMFenceLib.probeFence`), which a venue retired there may have left, so it counts for no venue
/// admitted after it, and drops the slot's scheduled raise of its caps and switch-on of its switches
/// (`FLAMMPolicyLib.setVenueCaps`, `setVenueFlags`, keyed by the slot in the pending table), so a loosening
/// scheduled for a venue retired there never lands on the venue admitted after it.
/// @dev A slot the Router reuses is a retired one, and the retirement closed any fence record there
/// (`FLAMMFenceLib.onRetire`): the clear touches no open record. It sits here, not in `FLAMMAdmitLib`, whose
/// code keeps no room for it; the genesis venues take fresh slots, where no read can sit.
function addVenue(IFLAMM.VenueInit calldata) external onlyCurator nonReentrant returns (uint16 id) {
id = abi.decode(_forward(address(FLAMMAdmitLib), FLAMMAdmitLib.addVenueScheduled.selector), (uint16));
if (id != type(uint16).max) {
FLAMMStore.S storage $ = _s();
$.fences[id].probeAt = 0;
_dropArmed($, FLAMMPolicyLib.SET_VENUE_CAPS, id);
_dropArmed($, FLAMMPolicyLib.SET_VENUE_FLAGS, id);
}
}
/// @dev Drops the loosening scheduled under setter `sel` for venue slot `id` (`FLAMMLane.capDue`'s key: the
/// call's first two words), where one is.
function _dropArmed(FLAMMStore.S storage $, bytes4 sel, uint16 id) private {
bytes32 key = keccak256(abi.encode(sel, id));
bytes32 armed = $.capRaises[key];
if (armed == 0) return;
delete $.capRaises[key];
if ($.pending[armed] != 0) {
delete $.pending[armed];
emit AdmissionCancelled(armed, msg.sender);
}
}
/// @notice The Router's four cascade orders for this pool, each listing every live, unfenced venue once
/// (`IMMRouter.setPriorities`, `BadPriorities` otherwise); the keeper's, the curator's or the controller
/// hook's.
function setPriorities(uint16[] calldata borrow_, uint16[] calldata supply_, uint16[] calldata withdraw_, uint16[] calldata repay_)
external
maintainer
nonReentrant
{
_s().router.setPriorities(borrow_, supply_, withdraw_, repay_);
}
/// @notice Turns the Router's re-check of each borrow slice in `fund` on (the default) or off for this pool. Off
/// saves gas on the swaps that borrow; a deposit's legs and a refinance keep their checks. The guardian may
/// only turn it on, and on a pool whose cheap lane is on the curator's turn-off waits the pool's delay
/// (`FLAMMLane.capDue`), which a turn-on drops.
function setFundRecheck(bool on) external nonReentrant {
FLAMMStore.S storage $ = _s();
if (_curatorOrGuardian() && !on) revert GuardianMayOnlyTighten();
if (FLAMMLane.capDue($, on, abi.encode(this.setFundRecheck.selector, on)) != 0) return;
$.router.setFundRecheck(on);
}
/// @notice The supply `mintProRata` may lift the pool to, in shares: zero, as at birth, closes that entry, and
/// `type(uint128).max` leaves it uncapped. The guardian may only lower it; on a pool whose cheap lane is on
/// the curator's raise waits the pool's delay (`FLAMMLane.capDue`). Each slice rounds every leg up, a
/// pool-asset leg of a few base units by up to one, which a hook that sizes its book on the pool asset
/// (`EverlongHook` does) reads as stable it does not hold: keep the entry closed on such a book.
function setMintProRataCap(uint128 cap) external nonReentrant {
FLAMMStore.S storage $ = _s();
bool raise = cap > $.mintProRataCap;
if (_curatorOrGuardian() && raise) revert GuardianMayOnlyTighten();
if (FLAMMLane.capDue($, !raise, abi.encode(this.setMintProRataCap.selector, cap)) != 0) return;
$.mintProRataCap = cap;
emit MintProRataCapSet(cap);
}
/// @notice Sets the debt-free flag of each token a fresh read of the Router shows the pool owing nothing
/// (`FLAMMStore.TokenCfg.debtFree`): a lender-side repay or liquidation can end a debt without the flow
/// whose read would set it; on a pool whose cheap lane is on, also the proof of each live pair the read
/// shows owing nothing (`FLAMMLane.proveDebtFree`). Permissionless, never paused or feature-gated, and
/// under the lock, so no read lands inside a flow.
function proveDebtFree() external nonReentrant {
FLAMMStore.S storage $ = _s();
if ($.swapBits & FLAMMStore.SWAP_LANE != 0) FLAMMLane.proveDebtFree($);
else FLAMMGateLib.proveDebtFree($);
}
/// @notice The custody maintenance path (`FEATURE_MAINTENANCE`): `TopUp` posts `amount` of venue `a`'s collateral
/// token at it, a token the pool owes nowhere (`NothingToMaintain` otherwise), at a venue that takes a post
/// now where its kind can refuse one (`VenueFrozen` otherwise: an exit during a freeze would forfeit it),
/// `Release` releases `amount` of collateral token `a`, at a frame's account no further than the frame
/// spares over its venues' triggers while one of them lacks (`RoomExhausted` past it), `Refinance` and
/// `MigrateSupply` move `amount` of debt or supply from venue `a` to `b`, a debt's share of `a`'s
/// collateral with it, out of a frame's account or into one only where the frame stays over its venues'
/// triggers (`RoomExhausted` otherwise).
/// @dev `kind` is ABI `uint8`; an out-of-range value reverts with empty data, before authorization.
function maintain(IFLAMM.MaintainKind, uint16, uint16, uint256) external maintainer nonReentrant {
_forward(address(FLAMMMaintainLib), FLAMMMaintainLib.maintain.selector);
}
/// @notice The market band's switch: `off` drops it (`bandWad` zero), else `bandWad`, in (0, 10 %], is attached to
/// a pool with none. A band in force moves through `setTokenConfig`.
/// @dev - Dropping it is the curator's, under a band ceiling that admits no band (`setBandAndFeeCeilings`, whose
/// raise to it waits ten days at least), and only with no debt, no fence holding a pool part
/// ({partedFences}), every pair's switch off, two tokens and a hook that declares it prices without a
/// reference.
/// - While a fee rate is on, the drop needs its skim to have read the fee mark (`PriceUnchecked` otherwise: a
/// stale or refused feed while the pool holds token 1, a frozen venue mark), so the gain made under the band
/// is charged before the pool stops reading a price, whose next attach restarts the mark past it.
/// - Attaching one is a tightening, the curator's or the guardian's, at once: the prices are admitted now,
/// every live pair's pin is held within what the band and the protocol's part keep (`InvalidConfig`
/// otherwise, as a wider band through `setTokenConfig`), and the fee mark restarts at the share price it
/// finds, so with a fee rate on it refuses (`VenueFrozen`) while a venue's figures are a frozen venue mark,
/// which is no price to restart the fee mark at, or while a fence holds a pool part, written off or not
/// ({partedFences}), whose return would read as a gain; with both rates off the fee mark waits for the first
/// skim that reads it, which moves it before any rise applies.
/// - With no band the pool's swaps and flows read no price, it charges no performance fee and takes no rise of
/// either rate, admits no third token and keeps every switch off; token 1's band reads zero exactly then.
function setMarketBand(bool off, uint64 bandWad) external nonReentrant {
bool g = _curatorOrGuardian();
bool marked = _skim();
FLAMMOpsLib.setMarketBand(_s(), off, bandWad, g, marked, totalSupply());
}
/// @notice The emergency path (curator or guardian; never paused), on venue `id`'s account, in its own tokens:
/// `Repay` repays `assets` of its debt token from custody, pulling any shortfall from the caller as a
/// donation; `TopUp` posts its collateral token at a live venue, a token the pool owes nowhere
/// (`NothingToMaintain` otherwise), never where an exit would forfeit the post (`VenueFrozen`: a gated
/// venue that allows no action and owes no more than a lender's rounding), and at a fenced venue, where
/// it is the curator's alone, it pulls part of the post from the caller in the collateral token, within
/// the caller's allowance to the pool (`FLAMMMaintainLib.emergency`); `WithdrawSupplied` recalls supply;
/// `WithdrawCollateral` needs a debt-free venue and, at a frame's account, every other venue there
/// debt-free too (the caller repays them first).
/// @dev `kind` is ABI `uint8`; an out-of-range value reverts with empty data.
function emergency(IFLAMM.EmergencyKind, uint16, uint256) external curatorOrGuardian nonReentrant {
_forward(address(FLAMMMaintainLib), FLAMMMaintainLib.emergency.selector);
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/core/flamm/FLAMM.sol": {
"FLAMMLane": "0x0445133358bc93e430f49c9076494cebed374dac",
"FLAMMOpsLib": "0x1efd99a7885eb85d17916d8420a4c0cf385aea4f",
"FLAMMFlowLib": "0x5f1d865d4250613afe1f58841ae26550d3cb5cae",
"FLAMMGateLib": "0x399eb30ce9ea526d5ea51afcb41e976daf7f82be",
"FLAMMAdmitLib": "0x3182c93ccfaa859d1cdc2254b9125c829249f294",
"FLAMMClaimLib": "0x1d7d0998111f88972c095cab6e28b9d3f2d0b523",
"FLAMMFenceLib": "0xf57d4876bbaff4725f3f06588b35b453b7c2a554",
"FLAMMFloatLib": "0xaa8c5f132fa07583c96fa27ac0eb7222af08f6e2",
"FLAMMQuoteLib": "0xb89089b3527398856abe2bdf458f6fec69466268",
"FLAMMTopUpLib": "0x8ee477572ef04b1ce6272e06c5fe512dbbd506e4",
"FLAMMPolicyLib": "0x788c2a9f6b155291f991197cf3a1d564ce1b963d",
"FLAMMSharedLib": "0x878459badc5e9ef9b9445a856402be18e04db256",
"FLAMMMaintainLib": "0xdde65f4ee0e958f77554e0296e3f56cdcce26d55"
}
},
"optimizer": {
"runs": 100,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts-compat/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable-compat/contracts/",
"solady/=lib/solady/src/",
"forge-std/=lib/forge-std/src/"
],
"experimental": false
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.