Verified contractExactBUSL-1.1
StableRateEscrow
Address0xce77a452cb174233c0ec18e3092f0935839b9519
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,393,542
- Creation transaction
- 0x3dfa7f87f2…d6724088ff
10 files
- v2/src/stablerate/StableRateEscrow.solmain34.93 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol12.18 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol683 B
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.26 KB
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol3.24 KB
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.69 KB
- v2/src/stablerate/IStableRateTerms.sol2.42 KB
v2/src/stablerate/StableRateEscrow.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.24;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { IStableRateTerms } from "./IStableRateTerms.sol";
interface IEscrowRegistry {
function isApproved(address vault) external view returns (bool);
}
/// @title StableRateEscrow (V2)
/// @author ACCRUE (accrue.cc)
/// @notice Holder of record for the vault shares backing Stable Rate positions, and for
/// ACCRUE's prefunded liability against them. This is the only Stable Rate
/// contract that holds anything, and it is IMMUTABLE — no proxy, no delegatecall,
/// no upgrade path.
///
/// ================================================================
/// WHAT THIS CONTRACT CANNOT DO — not gated, NOT WRITTEN
/// ================================================================
/// There is no adminWithdraw, no rescue of user assets, no transfer of a
/// position, and no setter for a position's rate, term, maturity, liability,
/// adapter or owner. Nothing pauses, gates or allowlists an exit. Assets leave a
/// position only to its own owner. Treat any of these appearing here as a
/// finding, exactly as the nine custody invariants are treated on the vaults.
///
/// The only governance surface is: a deposit-side allowlist for guarded testing,
/// rotation of the roles, pointing at a new Terms for FUTURE quotes, and
/// withdrawing reserve that is NOT allocated to any position.
///
/// ================================================================
/// SETTLEMENT READS NEITHER TERMS NOR THE ORACLE
/// ================================================================
/// A position carries its own terms, stamped at lock. Settling it needs exactly
/// two numbers: the share price recorded at lock, and the share price now, read
/// from the immutable adapter. Terms is an ENTRY dependency. The Oracle is a
/// QUOTING instrument. Neither is on this path, so a position settles when
/// quoting has stopped, the keeper is gone, the Oracle has stalled and Terms has
/// been destroyed.
///
/// ================================================================
/// SETTLEMENT HAS NO BRANCHES, WHICH IS WHY IT CANNOT OVERPAY
/// ================================================================
/// At maturity ACCRUE always takes the position's actual yield IN SHARES, and
/// always pays the Stable Rate amount IN USDC out of the liability escrowed for
/// that position at lock. Both directions of the memo's table fall out of one
/// unconditional pair of movements:
///
/// vault grew more than the Stable Rate -> ACCRUE keeps the excess
/// vault grew less, or lost -> ACCRUE covers the difference
///
/// The most a position can cost ACCRUE is therefore the amount escrowed for it,
/// structurally — not because a check says so, but because that is all the money
/// there is. No combination of rounding, decimals, partial exit, stale reading or
/// timing can produce a payment above it. A hard check asserts it anyway.
///
/// What the holder can owe is capped by what their OWN position earned, and can
/// never reach the amount they locked. ACCRUE takes yield, never principal.
///
/// ================================================================
/// NO ADAPTER CALL AT SETTLEMENT, DELIBERATELY
/// ================================================================
/// ACCRUE's share of a settled position moves by internal bookkeeping rather than
/// by redeeming. Redeeming would put the adapter's liquidity, its fee accounting
/// and its revert paths between a holder and their own settlement. ACCRUE redeems
/// its own shares later, through the ordinary path, where a failure costs only
/// ACCRUE. Nor is the payout ever re-deposited: a deposit can be paused by the
/// Guardian, and nothing on this path may read state ACCRUE can set.
///
/// ================================================================
/// PER-VAULT SEGREGATION IS ASSERTED, NOT ASSUMED
/// ================================================================
/// One escrow serves every vault on a chain, so that adding a vault needs no new
/// contract and no new approval. Shares are accounted per vault and every
/// state-changing path ends by asserting that the escrow's real balance in that
/// vault covers everything it has promised there. A shortfall in one vault cannot
/// be paid out of another's shares. V1 shipped a cross-vault drain in the rewards
/// path; this is that lesson applied before the fact rather than after.
contract StableRateEscrow is ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeCast for uint256;
// --------------------------------------------------------------------
// Types
// --------------------------------------------------------------------
struct Position {
address owner;
address vault;
uint128 shares; // locked shares, in the vault's own share units
uint128 lockSharePrice; // assets per 1e18 shares at lock
uint128 maxLiability; // USDC escrowed for this position; the hard cap
uint32 stableRate; // RATE_SCALE-based annual rate, stamped
uint32 termDays;
uint64 lockedAt;
uint64 maturesAt;
bool closed;
}
// --------------------------------------------------------------------
// Constants
// --------------------------------------------------------------------
uint256 internal constant SHARE_UNIT = 1e18;
uint32 internal constant RATE_SCALE = 1_000_000;
uint256 internal constant SECONDS_PER_DAY = 1 days;
IERC20 public immutable ASSET; // USDC
/// @notice The ACCRUE vault directory.
/// @dev Read on the ENTRY side only — enabling a vault, depositing, locking. Never
/// on withdraw, exit or settlement, which must not depend on any contract
/// ACCRUE can change. A vault retired from the Registry therefore stops
/// taking new Stable Rate positions while every open one settles and exits
/// exactly as before, which is how the generation-1 adapters were retired.
IEscrowRegistry public immutable REGISTRY;
// --------------------------------------------------------------------
// Roles — none of them reach a position or an exit
// --------------------------------------------------------------------
address public timelock;
address public launchGuardian;
address public treasury;
/// @notice Entry pricing only. Never consulted once a position exists.
IStableRateTerms public terms;
// --------------------------------------------------------------------
// State
// --------------------------------------------------------------------
mapping(address vault => bool) public vaultEnabled;
/// @dev Unlocked shares a holder keeps in the escrow, per vault.
mapping(address vault => mapping(address owner => uint256)) public floatingShares;
/// @dev Everything the escrow owes in a vault: holders' floating, holders' locked,
/// and ACCRUE's own settled share. Asserted against the real balance.
mapping(address vault => uint256) public totalShares;
/// @dev ACCRUE's settled yield, still denominated in that vault's shares.
mapping(address vault => uint256) public accrueShares;
/// @notice Value locked in open positions per vault, measured in USDC at each
/// position's own lock price and released when it closes.
/// @dev The input to the underlying-market cap. Held here because this is the
/// contract that knows what is locked; interpreted by Terms and its lens,
/// because how much of a market ACCRUE may reach is a risk parameter rather
/// than a custody fact. Measured at lock price and released at lock price, so
/// it cannot drift with the share price and can never under-release.
mapping(address vault => uint256) public lockedValue;
/// @dev USDC escrowed against open positions. Untouchable by governance.
uint256 public allocatedReserve;
Position[] private _positions;
mapping(address owner => uint256[]) private _positionsOf;
// Guarded testing. Deposit side ONLY.
mapping(address => bool) public allowlisted;
bool public publicLaunchOpen;
// --------------------------------------------------------------------
// Events
// --------------------------------------------------------------------
event Deposited(address indexed vault, address indexed owner, uint256 assets, uint256 shares);
event Withdrawn(address indexed vault, address indexed owner, uint256 shares, uint256 assets);
event Locked(
uint256 indexed id,
address indexed vault,
address indexed owner,
uint256 shares,
uint32 stableRate,
uint32 termDays,
uint256 maxLiability
);
event Settled(
uint256 indexed id,
address indexed owner,
uint256 sharesToAccrue,
uint256 paidToOwner,
bool early
);
event ReserveFunded(address indexed from, uint256 amount);
event ReserveWithdrawn(address indexed to, uint256 amount);
event VaultEnabled(address indexed vault, bool enabled);
event TermsUpdated(address terms);
event AccrueSharesRedeemed(address indexed vault, uint256 shares, uint256 assets);
event RewardsSkimmed(address indexed token, address indexed to, uint256 amount);
// --------------------------------------------------------------------
// Errors
// --------------------------------------------------------------------
error NotTimelock();
error NotLaunchGuardian();
error NotOwner();
error ZeroAddress();
error ZeroAmount();
error VaultNotEnabled();
error VaultNotApproved(address vault);
error NotAllowlisted();
error AssetMismatch();
error InsufficientFloating(uint256 requested, uint256 available);
error QuoteNotOpen();
error MarketCapReached(address vault, bytes32 bindingMarket);
error QuoteTermMismatch(uint32 returned, uint32 requested);
error ReserveTooThin(uint256 needed, uint256 available);
error PositionClosed();
error NotMatured();
error LiabilityExceeded(uint256 paid, uint256 cap);
error VaultUndercollateralised(address vault, uint256 held, uint256 owed);
error ReserveIsAllocated(uint256 requested, uint256 unallocated);
error LiabilityBelowSettlement(uint256 offered, uint256 required);
error ProtectedToken(address token);
modifier onlyTimelock() {
if (msg.sender != timelock) revert NotTimelock();
_;
}
modifier onlyLaunchGuardian() {
if (msg.sender != launchGuardian) revert NotLaunchGuardian();
_;
}
/// @dev Deposit side only. Never applied to withdraw, exit or settle.
modifier entryAllowed() {
if (!publicLaunchOpen && !allowlisted[msg.sender]) revert NotAllowlisted();
_;
}
constructor(
IERC20 asset_,
IEscrowRegistry registry_,
address timelock_,
address launchGuardian_,
address treasury_,
IStableRateTerms terms_
) {
if (
address(asset_) == address(0) || address(registry_) == address(0)
|| timelock_ == address(0) || launchGuardian_ == address(0)
|| treasury_ == address(0) || address(terms_) == address(0)
) revert ZeroAddress();
ASSET = asset_;
REGISTRY = registry_;
timelock = timelock_;
launchGuardian = launchGuardian_;
treasury = treasury_;
terms = terms_;
}
// --------------------------------------------------------------------
// Holding
// --------------------------------------------------------------------
/// @notice Put USDC into `vault` through the escrow. The new balance is FLOATING.
function deposit(address vault, uint256 assets)
external
nonReentrant
entryAllowed
returns (uint256 shares)
{
shares = _deposit(vault, assets, msg.sender);
_assertSolvent(vault);
}
/// @notice Put USDC in and open a Stable Rate position on it, in ONE transaction.
/// @dev A holder never has to enter the floating product first and switch. Floating
/// is the resting state of shares between two calls, not a product anyone is
/// made to pass through — and this path removes even that gap, so a new
/// holder signs once for what the interface presents as one action.
///
/// Composed from the same internals `deposit` and `lock` use, so there is one
/// implementation of each and no second copy to drift.
function depositAndLock(address vault, uint256 assets, uint32 termDays)
external
nonReentrant
entryAllowed
returns (uint256 id, uint256 shares)
{
shares = _deposit(vault, assets, msg.sender);
id = _lock(vault, shares, termDays, msg.sender);
_assertSolvent(vault);
}
function _deposit(address vault, uint256 assets, address owner)
internal
returns (uint256 shares)
{
if (!vaultEnabled[vault]) revert VaultNotEnabled();
// Re-read rather than trusting the flag: a vault retired from the Registry after
// it was enabled must stop taking new money on the next block, not whenever
// somebody remembers to flip it off.
if (!REGISTRY.isApproved(vault)) revert VaultNotApproved(vault);
if (assets == 0) revert ZeroAmount();
// The assets arrive and leave for the vault inside this call, so they are never
// counted as free reserve by a `lock` running immediately afterwards.
ASSET.safeTransferFrom(owner, address(this), assets);
ASSET.forceApprove(vault, assets);
shares = IERC4626(vault).deposit(assets, address(this));
floatingShares[vault][owner] += shares;
totalShares[vault] += shares;
emit Deposited(vault, owner, assets, shares);
}
/// @notice Take floating shares out of the escrow and out of the vault.
/// @dev Floating only, by design. Reaching locked shares means ending a position
/// early, which costs the holder something, and a cost that large should be
/// an explicit choice rather than a side effect of asking to withdraw. The
/// interface quotes the difference and calls `exitPosition` itself.
///
/// Reads no governance state and cannot be paused.
function withdraw(address vault, uint256 shares)
external
nonReentrant
returns (uint256 assets)
{
uint256 available = floatingShares[vault][msg.sender];
if (shares == 0) revert ZeroAmount();
if (shares > available) revert InsufficientFloating(shares, available);
floatingShares[vault][msg.sender] = available - shares;
totalShares[vault] -= shares;
assets = IERC4626(vault).redeem(shares, msg.sender, address(this));
emit Withdrawn(vault, msg.sender, shares, assets);
_assertSolvent(vault);
}
// --------------------------------------------------------------------
// Locking
// --------------------------------------------------------------------
/// @notice Move floating shares into a Stable Rate position.
/// @dev Nothing is redeemed and nothing is redeposited: the shares stay invested in
/// the same vault throughout and simply stop being floating.
function lock(address vault, uint256 shares, uint32 termDays)
external
nonReentrant
entryAllowed
returns (uint256 id)
{
id = _lock(vault, shares, termDays, msg.sender);
_assertSolvent(vault);
}
/// @dev Both entry limits, kept out of `_lock` so it stays inside the stack under the
/// v2 profile, which builds without via-ir.
///
/// RESERVE: ACCRUE never opens a position it cannot fully cover. The whole
/// liability moves out of free reserve into the position at lock, so settlement
/// never has to ask whether the reserve can pay.
///
/// MARKET: Layer 3. Bounds what moving an underlying market's rate could ever
/// pay for, counted across every ACCRUE vault that reaches that market rather
/// than this one alone. Both are ENTRY controls and neither is consulted again
/// once the position exists.
function _assertWithinLimits(
address vault,
uint256 value,
uint32 stableRate,
uint32 termDays
) internal view {
uint256 free = unallocatedReserve();
uint256 required = terms.capacityRequired(value, stableRate, termDays);
if (required > free) revert ReserveTooThin(required, free);
(bool capOk, bytes32 binding,) = terms.checkMarketCapacity(vault, value);
if (!capOk) revert MarketCapReached(vault, binding);
}
function _lock(address vault, uint256 shares, uint32 termDays, address owner)
internal
returns (uint256 id)
{
if (!vaultEnabled[vault]) revert VaultNotEnabled();
if (!REGISTRY.isApproved(vault)) revert VaultNotApproved(vault);
if (shares == 0) revert ZeroAmount();
uint256 available = floatingShares[vault][owner];
if (shares > available) revert InsufficientFloating(shares, available);
IStableRateTerms.Quote memory q = terms.quote(vault, termDays);
// ACCEPT ONLY WHAT IS EXPLICITLY ON OFFER, rather than rejecting what is
// explicitly refused. Terms is replaceable, and this contract is not: a future
// implementation that returns a status this one has never heard of, or a default
// zero-valued struct, must fail closed here. Rejecting only `Unavailable` would
// have treated `Collecting` — a vault without enough history to price — as
// tradeable, and any newly added status as tradeable by default.
if (q.status != IStableRateTerms.Status.Quoting && q.status != IStableRateTerms.Status.Open) {
revert QuoteNotOpen();
}
// The quote must answer the question that was asked. A Terms that returned a
// 30-day rate for a 90-day request would stamp three times the liability's worth
// of term against a rate priced for a third of it.
if (q.termDays != termDays) revert QuoteTermMismatch(q.termDays, termDays);
if (q.stableRate == 0) revert QuoteNotOpen();
uint256 price = IERC4626(vault).convertToAssets(SHARE_UNIT);
uint256 value = (shares * price) / SHARE_UNIT;
uint256 liability = terms.maxLiability(value, q.stableRate, termDays);
if (liability == 0) revert ZeroAmount();
/* TERMS MAY NOT UNDER-STATE WHAT SETTLEMENT WILL DEMAND. Refused HERE, at entry.
`_close` pays the full Stable Rate at maturity and reverts if that exceeds the
liability stamped on the position. The payout formula is fixed in this
contract; the liability came from Terms, which the Timelock can replace. If a
future Terms returned even one wei less than the formula — a rounding change,
a different divisor, a unit slip — every position opened under it would reach
maturity and find that `settle` AND `exitPosition` revert, forever. The
holder's shares would be locked by a contract the architecture says may only
ever affect entry. Proven by test, not argued: see
StableRateEscrowBadTerms.t.sol.
So the escrow computes its own floor — the exact amount `_settlementOf` will
pay at maturity, same arithmetic — and a Terms that offers less is refused
before anything is stamped. A defective Terms then costs a failed lock, never
a locked holder. Early exit pays no more than this, so the floor covers every
path out. */
uint256 floor = (value * q.stableRate * termDays) / (uint256(RATE_SCALE) * 365);
if (liability < floor) revert LiabilityBelowSettlement(liability, floor);
_assertWithinLimits(vault, value, q.stableRate, termDays);
allocatedReserve += liability;
lockedValue[vault] += value;
floatingShares[vault][owner] = available - shares;
id = _positions.length;
_positions.push(
Position({
owner: owner,
vault: vault,
shares: shares.toUint128(),
lockSharePrice: price.toUint128(),
maxLiability: liability.toUint128(),
stableRate: q.stableRate,
termDays: termDays,
lockedAt: block.timestamp.toUint64(),
maturesAt: (block.timestamp + termDays * SECONDS_PER_DAY).toUint64(),
closed: false
})
);
_positionsOf[owner].push(id);
emit Locked(id, vault, owner, shares, q.stableRate, termDays, liability);
}
// --------------------------------------------------------------------
// Settlement — the closed loop
// --------------------------------------------------------------------
/// @notice Settle a matured position. Callable by anyone: it is automatic, and
/// neither side executes it as a discretionary act.
function settle(uint256 id) external nonReentrant {
Position storage p = _positions[id];
if (p.closed) revert PositionClosed();
// Maturity IS a time condition. A validator's few seconds of leeway against a
// term measured in months changes nothing about who is paid what, and the term
// counts in full at maturity regardless of when settlement lands.
// forge-lint: disable-next-line(block-timestamp)
if (block.timestamp < p.maturesAt) revert NotMatured();
_close(p, id, false);
}
/// @notice End a position before maturity. The holder's own choice, so only theirs.
/// @dev Pays the LOWER of the Stable Rate accrued so far or the position's actual
/// yield so far — always less than holding to maturity, on every path, so
/// there is no exit timing that extracts value.
function exitPosition(uint256 id) external nonReentrant {
Position storage p = _positions[id];
if (p.owner != msg.sender) revert NotOwner();
if (p.closed) revert PositionClosed();
// forge-lint: disable-next-line(block-timestamp)
_close(p, id, block.timestamp < p.maturesAt);
}
/// @dev THE settlement formula. There is exactly one, and both `previewSettle` and
/// `_close` go through it.
///
/// An earlier version computed it twice, once in each. Everything passed —
/// including a test that asserted the early-exit minimum — because the test read
/// the preview while the mutation changed the settlement. A quote that can drift
/// from what settles is the one defect this product cannot carry, so the
/// duplication is gone rather than documented.
///
/// Reads the stamped record and a share price. Nothing else: no Terms, no
/// Oracle, no governance state.
function _settlementOf(Position memory p, uint256 price, bool early)
internal
view
returns (uint256 payout, uint256 sharesToAccrue)
{
uint256 shares = p.shares;
uint256 valueAtLock = (shares * p.lockSharePrice) / SHARE_UNIT;
uint256 valueNow = (shares * price) / SHARE_UNIT;
// Principal losses stay with the holder: yield is growth above the locked value,
// never a negative number carried into the arithmetic.
uint256 actualYield = valueNow > valueAtLock ? valueNow - valueAtLock : 0;
// At maturity the term counts in full even if settlement lands a day late —
// otherwise a delay would quietly increase what ACCRUE owes.
// forge-lint: disable-next-line(block-timestamp)
uint256 elapsedDays = early ? (block.timestamp - p.lockedAt) / SECONDS_PER_DAY : p.termDays;
uint256 stableYield =
(valueAtLock * p.stableRate * elapsedDays) / (uint256(RATE_SCALE) * 365);
// Early exit pays the LOWER of the two. Holding to maturity pays the Stable Rate.
payout = early && actualYield < stableYield ? actualYield : stableYield;
sharesToAccrue = price == 0 ? 0 : (actualYield * SHARE_UNIT) / price;
if (sharesToAccrue > shares) sharesToAccrue = shares;
}
/// @dev ACCRUE always takes the position's actual yield in shares and always pays the
/// Stable Rate amount in USDC from what was escrowed at lock. Both rows of the
/// memo's table fall out of that one unconditional pair of movements.
function _close(Position storage p, uint256 id, bool early) internal {
address vault = p.vault;
uint256 shares = p.shares;
uint256 price = IERC4626(vault).convertToAssets(SHARE_UNIT);
(uint256 payout, uint256 sharesToAccrue) = _settlementOf(_positions[id], price, early);
// The hard cap, asserted rather than trusted. It cannot bind in practice: the
// escrowed amount is all there is to pay from.
if (payout > p.maxLiability) revert LiabilityExceeded(payout, p.maxLiability);
p.closed = true;
// Released at the same price it was booked at, so the running total is exactly
// the sum of what is still open.
lockedValue[vault] -= (shares * p.lockSharePrice) / SHARE_UNIT;
accrueShares[vault] += sharesToAccrue;
floatingShares[vault][p.owner] += shares - sharesToAccrue;
// Whatever was escrowed and not paid goes back to free reserve.
allocatedReserve -= p.maxLiability;
if (payout > 0) ASSET.safeTransfer(p.owner, payout);
emit Settled(id, p.owner, sharesToAccrue, payout, early);
_assertSolvent(vault);
}
// --------------------------------------------------------------------
// Reserve
// --------------------------------------------------------------------
/// @notice Add USDC to the reserve. Permissionless — funding is never gated.
function fundReserve(uint256 amount) external nonReentrant {
if (amount == 0) revert ZeroAmount();
ASSET.safeTransferFrom(msg.sender, address(this), amount);
emit ReserveFunded(msg.sender, amount);
}
/// @notice Reserve not escrowed against any open position.
function unallocatedReserve() public view returns (uint256) {
uint256 balance = ASSET.balanceOf(address(this));
return balance > allocatedReserve ? balance - allocatedReserve : 0;
}
/// @notice Withdraw reserve that is NOT allocated to a position.
/// @dev `allocatedReserve` is arithmetically out of reach here. Money escrowed
/// against an open position belongs to that position's settlement and cannot
/// be recalled by anyone, including the Timelock.
function withdrawReserve(uint256 amount) external nonReentrant onlyTimelock {
uint256 free = unallocatedReserve();
if (amount > free) revert ReserveIsAllocated(amount, free);
ASSET.safeTransfer(treasury, amount);
emit ReserveWithdrawn(treasury, amount);
}
/// @notice Turn ACCRUE's settled share of a vault into USDC for the treasury.
/// @dev Deliberately separate from settlement, and deliberately failure-tolerant:
/// if the vault cannot pay out right now, only ACCRUE waits.
function redeemAccrueShares(address vault, uint256 shares) external nonReentrant onlyTimelock {
uint256 held = accrueShares[vault];
if (shares == 0 || shares > held) revert ZeroAmount();
accrueShares[vault] = held - shares;
totalShares[vault] -= shares;
uint256 assets = IERC4626(vault).redeem(shares, treasury, address(this));
emit AccrueSharesRedeemed(vault, shares, assets);
_assertSolvent(vault);
}
// --------------------------------------------------------------------
// Protocol rewards
// --------------------------------------------------------------------
/// @notice Forward a protocol reward token (COMP, MORPHO, ...) that accrued to shares
/// this escrow holds. Permissionless; the destination is the treasury and is
/// not a parameter.
///
/// @dev WHY THIS EXISTS. The escrow is the vault's shareholder of record, so the
/// vault pays the escrow's reward accrual to the ESCROW on every withdrawal
/// (`AccrueVaultAdapter._withdraw` -> `REWARDS.claimAllFor(owner)`). Without
/// this function those tokens have no way out: the escrow's only other
/// transfers are USDC and vault shares. Proven by test —
/// StableRateEscrowStrandedRewards.t.sol.
///
/// WHY THE TREASURY. Under Stable Rate ACCRUE takes the position's actual
/// yield and pays the holder a fixed rate; protocol rewards are part of that
/// yield. A product that shares them with holders would need accounting this
/// contract does not carry.
///
/// WHAT IT CANNOT REACH. The asset — that is the reserve, and allocated
/// reserve belongs to open positions. Vault shares are soulbound and revert on
/// transfer, so they are unreachable by construction; the check on `vaultEnabled`
/// is belt and braces for a vault later disabled while shares remain.
function skimRewards(address token) external nonReentrant {
if (token == address(ASSET) || vaultEnabled[token]) revert ProtectedToken(token);
uint256 bal = IERC20(token).balanceOf(address(this));
if (bal == 0) return;
IERC20(token).safeTransfer(treasury, bal);
emit RewardsSkimmed(token, treasury, bal);
}
// --------------------------------------------------------------------
// Segregation
// --------------------------------------------------------------------
/// @dev Everything the escrow has promised in one vault must be covered by what it
/// actually holds there. Runs at the end of every state-changing path, so no
/// sequence can leave one vault's holders relying on another vault's shares.
function _assertSolvent(address vault) internal view {
uint256 held = IERC4626(vault).balanceOf(address(this));
uint256 owed = totalShares[vault];
if (held < owed) revert VaultUndercollateralised(vault, held, owed);
}
// --------------------------------------------------------------------
// Views
// --------------------------------------------------------------------
function positionCount() external view returns (uint256) {
return _positions.length;
}
function positionOf(uint256 id) external view returns (Position memory) {
return _positions[id];
}
function positionsOf(address owner) external view returns (uint256[] memory) {
return _positionsOf[owner];
}
/// @notice What settling right now would pay, without changing anything.
/// @dev Goes through the same `_settlementOf` the real settlement does, so a quote
/// and what actually settles cannot drift apart.
function previewSettle(uint256 id)
external
view
returns (uint256 payout, uint256 sharesToAccrue, bool early)
{
Position memory p = _positions[id];
if (p.closed) return (0, 0, false);
// forge-lint: disable-next-line(block-timestamp)
early = block.timestamp < p.maturesAt;
uint256 price = IERC4626(p.vault).convertToAssets(SHARE_UNIT);
(payout, sharesToAccrue) = _settlementOf(p, price, early);
}
// --------------------------------------------------------------------
// Governance — entry side, roles, and future pricing. Nothing else.
// --------------------------------------------------------------------
/// @dev Being a USDC ERC-4626 vault is not enough to be an ACCRUE vault. Without the
/// Registry check, any address answering `asset()` correctly could be enabled —
/// not a custody backdoor, since nothing here can move a holder's funds, but a
/// trust surface with no reason to exist. The same directory the market lens
/// reads decides what may enter.
function setVaultEnabled(address vault, bool enabled) external onlyTimelock {
if (vault == address(0)) revert ZeroAddress();
if (enabled) {
if (IERC4626(vault).asset() != address(ASSET)) revert AssetMismatch();
if (!REGISTRY.isApproved(vault)) revert VaultNotApproved(vault);
}
vaultEnabled[vault] = enabled;
emit VaultEnabled(vault, enabled);
}
/// @dev Reaches FUTURE quotes only. Open positions carry their own stamped terms and
/// are not read from here again.
function setTerms(IStableRateTerms newTerms) external onlyTimelock {
if (address(newTerms) == address(0)) revert ZeroAddress();
terms = newTerms;
emit TermsUpdated(address(newTerms));
}
function setAllowlisted(address who, bool allowed) external onlyLaunchGuardian {
allowlisted[who] = allowed;
}
function openToPublic() external onlyLaunchGuardian {
publicLaunchOpen = true;
}
function rotateTimelock(address newTimelock) external onlyTimelock {
if (newTimelock == address(0)) revert ZeroAddress();
timelock = newTimelock;
}
function rotateLaunchGuardian(address newGuardian) external onlyTimelock {
if (newGuardian == address(0)) revert ZeroAddress();
launchGuardian = newGuardian;
}
function setTreasury(address newTreasury) external onlyTimelock {
if (newTreasury == address(0)) revert ZeroAddress();
treasury = newTreasury;
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
}
v2/src/stablerate/IStableRateTerms.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.24;
/// @title IStableRateTerms
/// @author ACCRUE (accrue.cc)
/// @notice What the escrow asks of a Terms contract, and the whole of it.
///
/// The escrow depends on this interface rather than on any particular
/// implementation, which is what makes "replaceable" a real property instead of a
/// promise: a future Terms need only answer these three questions. It is asked
/// them when a position OPENS and never again — nothing here is on the settlement
/// path, and no implementation of it can reach a position that already exists.
interface IStableRateTerms {
/// @notice The four card states from the product design.
enum Status {
Collecting,
Quoting,
Open,
Unavailable
}
enum Reason {
None,
NotRegistered,
Collecting,
HistoryGap,
DerivationChanged,
ReferenceTooLow,
TermNotOffered
}
struct Quote {
Status status;
Reason reason;
uint32 referenceRate;
uint32 stableRate;
uint32 requiredReference;
uint32 daysUntilQuotable;
uint32 termDays;
}
function quote(address vault, uint32 termDays) external view returns (Quote memory);
/// @notice The most a position can ever cost ACCRUE, and exactly what is escrowed
/// for it at lock.
function maxLiability(uint256 amount, uint32 stableRate, uint32 termDays)
external
view
returns (uint256);
/// @notice Reserve capacity the position consumes while it is open.
function capacityRequired(uint256 amount, uint32 stableRate, uint32 termDays)
external
view
returns (uint256);
/// @notice Layer 3: would locking `addedValue` more into `vault` push any underlying
/// market past ACCRUE's share of it, counting every vault that reaches that
/// market rather than this one alone?
/// @dev MUST fail closed. An implementation with no market lens configured is
/// required to revert rather than answer true, because a cap that silently
/// does not apply is worse than one that is absent.
function checkMarketCapacity(address vault, uint256 addedValue)
external
view
returns (bool ok, bytes32 bindingMarket, uint256 headroom);
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.