Verified contractPartialMIT
HardDepositVault
Address0x136c1112bbcb63ddfc0325d8e3587dde50589752
- Balance
0 ETH
- Transactions
20
- Compiler
solc 0.8.38
- Same code
Only this contract
Details
- Compiler
- solc 0.8.38+commit.1835d247
- Language
- solidity
- Optimization
- Yes, 50 runs
- EVM version
- prague
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,536,779
- Creation transaction
- 0x2b74ad9c99…0fdffba299
- Libraries
- src/HardSettlementLib.sol:HardSettlementLib0x73bc…0e515e
10 files
- src/HardDepositVault.solmain60.29 KB
- lib/solady/src/auth/Ownable.sol12.55 KB
- lib/solady/src/utils/FixedPointMathLib.sol55.67 KB
- lib/solady/src/utils/ReentrancyGuard.sol2.33 KB
- lib/solady/src/utils/SafeTransferLib.sol32.8 KB
- src/HardCore.sol6.67 KB
- src/HardErrors.sol1.58 KB
- src/HardSettlementLib.sol29.36 KB
- src/interfaces/IOnchainActionManager.sol574 B
- src/interfaces/IPnlReports.sol1.96 KB
src/HardDepositVault.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;
import {Ownable} from "solady/auth/Ownable.sol";
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {HardCore} from "./HardCore.sol";
import {HardSettlementLib} from "./HardSettlementLib.sol";
import {IPnlReports} from "./interfaces/IPnlReports.sol";
import {
AlreadyRedeemed,
BadSweepDestination,
BalanceUnreadable,
AlreadySwept,
AmountTooLarge,
BadMinimum,
BadPeriod,
BadReport,
BadTerms,
BelowMinimum,
InsufficientPending,
InsufficientSurplus,
LossTooLarge,
NoActiveSupply,
NoRedemptionPending,
NotPending,
NothingToClaim,
NothingToDistribute,
Paused,
RedemptionAlreadyPending,
RedemptionMismatch,
ReportExpired,
ReportMismatch,
ReportMissing,
SettlementTooLarge,
ProfitEpochOpen,
ProfitEpochSettled,
SweepRequired,
TimelockPending,
TokenNotRecoverable,
Unauthorized,
UnpaidWipe,
UnknownWindow,
WindowOpen,
ZeroAddress,
ZeroAmount
} from "./HardErrors.sol";
/// @notice Custody vault. A wallet holds one account: pending deposits in at most two windows, trading
/// capital in the book's pools, profit that is not trading capital until it is reinvested, and a redemption
/// claim. No call loops over wallets, so a window and the book have no wallet limit. See ADR-0171.
/// @dev Sweep transfers ERC-20 to the destination the owner sets once. Derive deposit calldata is not encoded
/// here while OQ-034 is open. An account is brought up to date lazily: every account call settles the caller
/// first, and `settle` settles any list of wallets. Profit and loss settle only against the Chainlink CRE
/// report of the next contiguous window, for every caller including the owner. The exit is the owner's pause
/// and `redeem` against a CRE redemption report. Without one, only the owner's `emergencyRedeem` after the
/// timelock splits all free stablecoin into principal first. See ADR-0242, ADR-0248, ADR-0249, and ADR-0252.
contract HardDepositVault is Ownable, ReentrancyGuard {
address public immutable stable;
uint8 public immutable stableDecimals;
address public immutable actionManager;
address public immutable companyFee;
/// @notice The Chainlink PnL adapter whose reports gate `distribute`, `applyLoss`, and `closeFlat`.
address public immutable pnlAdapter;
uint64 public immutable feeRiseAt;
uint64 public immutable feePeriod;
uint16 public immutable feeBase;
uint16 public immutable feeStep;
uint16 public immutable feeCap;
uint64 public immutable timelock;
uint64 public immutable minHuman;
uint64 public immutable maxHuman;
uint64 public immutable minPeriod;
uint64 public immutable maxPeriod;
/// @notice Length of window 1, measured from the deploy block. Later windows do not read it.
uint64 public immutable startPeriod;
/// @notice Shortfall a redemption absorbs as the Derive withdrawal fee, in stable units. It is also the most
/// a redemption report may show left on Derive. A larger gap in `emergencyRedeem` needs a ready
/// `proposeShortfall` for that redemption id.
uint256 public immutable withdrawFeeCap;
/// @notice Derive deposit target of `sweep`: the mailbox registered for this vault before its deploy.
/// A constructor argument; nothing can change it (ADR-0249).
address public immutable sweepDestination;
address public operator;
address public keeper;
/// @notice Fast emergency key. It may pause the vault, revoke a compromised operator or keeper, and revoke a
/// Derive session key, but it cannot unpause, veto the owner, change parameters, or move funds. Having no
/// veto, it needs no timelock: the owner sets and clears it at once (ADR-0248).
address public guardian;
bool public paused;
uint256 public minimumDeposit;
uint256 public nextTradingPeriod;
/// @notice Pending deposits plus reinvestment waiting for the next fold.
uint256 public pendingTotal;
/// @notice Settled available profit plus profit staged for reinvestment. Neither is trading capital.
uint256 public claimableTotal;
uint256 public redemptionReserve;
uint64 public currentWindowId;
uint64 public staleUnswept;
HardSettlementLib.Book internal ledger;
mapping(uint256 => bool) public redeemed;
bool public minimumPending;
uint256 public pendingMinimum;
uint64 public minimumReadyAt;
bool public operatorPending;
address public pendingOperator;
uint64 public operatorReadyAt;
bool public keeperPending;
address public pendingKeeper;
uint64 public keeperReadyAt;
bool public tradingPeriodPending;
uint256 public pendingTradingPeriod;
uint64 public tradingPeriodReadyAt;
/// @dev True after a sweep that moved principal, until that snapshot's profit is
/// credited or the owner finishes an empty-epoch acknowledgement.
bool public profitEpochOpen;
uint64 public profitEpoch;
uint64 public epochEndsAt;
/// @notice End, in unix milliseconds, of the last report window the vault settled. The next report must
/// start here, so settled windows are contiguous. Set at the first epoch open.
uint64 public attestedUntilMs;
/// @notice Block time, in unix milliseconds, of the `sweep` or `carryEpoch` that opened the current epoch.
/// Trades before it belong to the capital that traded then (`main`); a report window may not straddle it.
uint64 public epochOpenedMs;
/// @notice Deposits swept by the sweep that opened this epoch. This value is the size of the swept deposit
/// and is not marked down. There is no deposit fee and no `depositFeeCharged` flag (ADR-0169, audit finding 9).
uint256 public epochIntake;
/// @notice Book marked to zero by `applyLoss`. Unaccounted stablecoin is not surplus
/// until `redeem` pays these weights.
uint256 public wipedCapital;
bool public redemptionPending;
uint256 public pendingRedemptionId;
uint256 public redemptionBook;
bool internal redemptionStartedPaused;
/// @notice Block time of the pending `beginRedemption`. A redemption report must end after it, and
/// `emergencyRedeem` waits `timelock` from it. Zero while no redemption is pending.
uint64 public redemptionStartedAt;
bool public shortfallPending;
uint256 public shortfallRedemptionId;
uint256 public pendingShortfall;
uint64 public shortfallReadyAt;
/// @notice Company fee that was earned but could not be delivered to `companyFee` because the transfer
/// reverted (for example a stablecoin blocklist). It is held for `claimCompanyFee`, is excluded from
/// `surplus`, and never blocks epoch settlement. Zero on the normal path.
uint256 public claimableCompanyFee;
/// @notice Attested profit that `closeFlat` left on Derive and no call has credited yet. `distribute` credits it
/// above the report once the stablecoin arrives, and `redeem` charges the company fee on it. It belongs to the
/// current generation and ends with it (audit N-2, ADR-0254).
uint256 public deferredProfit;
event Deposited(address indexed investor, uint64 indexed windowId, uint256 amount, uint16 feeBps);
event FeeLocked(address indexed investor, uint16 feeBps);
event Cancelled(address indexed investor, uint64 indexed windowId, uint256 amount);
event Swept(uint64 indexed windowId, uint256 amount, address destination);
event Distributed(uint256 profit, uint256 investorTotal, uint256 feeTotal);
event ProfitWithdrawn(address indexed investor, uint256 amount);
event ReinvestStaged(address indexed investor, uint256 amount);
event ReinvestUnstaged(address indexed investor, uint256 amount);
event Reinvested(address indexed investor, uint256 amount, uint64 round);
event ReinvestCancelled(address indexed investor, uint256 amount);
event Redeemed(uint256 indexed redemptionId, uint256 principal, uint256 profit, uint256 fee);
event RedemptionStarted(uint256 indexed redemptionId, uint256 book);
event RedemptionCancelled(uint256 indexed redemptionId);
event RedemptionClaimed(address indexed investor, uint256 paid);
event PausedSet(bool paused);
event GuardianSet(address indexed guardian);
/// @notice A report window settled: `attestedUntilMs` moved to `windowEndMs`.
event ReportSettled(uint64 indexed epoch, uint64 windowEndMs, int256 realizedPnl);
event SessionKeySubmitted(address indexed sessionKey, uint256 expiry);
event MinimumProposed(uint256 value, uint64 readyAt);
event MinimumApplied(uint256 value);
event OperatorProposed(address indexed next, uint64 readyAt);
event OperatorApplied(address indexed next);
event KeeperProposed(address indexed next, uint64 readyAt);
event KeeperApplied(address indexed next);
event TradingPeriodProposed(uint256 value, uint64 readyAt);
event TradingPeriodApplied(uint256 value);
event LossApplied(uint64 indexed epoch, uint256 loss, uint256 remain);
event ShortfallProposed(uint256 indexed redemptionId, uint256 shortfall, uint64 readyAt);
event EpochClosedFlat(uint64 indexed epoch);
/// @notice `closeFlat` left `amount` of attested profit on Derive; it joins `deferredProfit` (ADR-0254).
event ProfitDeferred(uint64 indexed epoch, uint256 amount);
event EpochCarried(uint64 indexed epoch, uint256 capital, uint64 endsAt);
event CompanyFeeClaimed(uint256 amount);
/// @dev A non-stable token swept out by `recover`. `to` is operator-pair supplied; see invariant I-recover.
event Recovered(address indexed token, address indexed to, uint256 amount);
/// @dev Mirrors of `HardSettlementLib` events so the delegatecall logs decode against the vault ABI.
/// Declared, not emitted, here; the library emits the identical topics in the vault context.
event CompanyFeeDeferred(uint256 amount);
event Settled(address indexed investor, uint256 profit);
constructor(
address owner_,
address operator_,
address stable_,
uint8 stableDecimals_,
address actionManager_,
address companyFee_,
address pnlAdapter_,
address sweepDestination_,
HardCore.Terms memory terms
) {
if (
owner_ == address(0) || operator_ == address(0) || stable_ == address(0) || actionManager_ == address(0)
|| companyFee_ == address(0) || pnlAdapter_ == address(0)
) revert ZeroAddress();
// The Derive mailbox is the only stablecoin exit to the exchange. It is fixed here and never changes.
if (sweepDestination_ == address(0)) revert ZeroAddress();
if (
sweepDestination_ == address(this) || sweepDestination_ == companyFee_ || sweepDestination_ == stable_
|| sweepDestination_ == actionManager_ || sweepDestination_ == pnlAdapter_
) revert BadSweepDestination();
if (stableDecimals_ > 18) revert BadMinimum();
HardCore.validate(terms);
// A workflow replacement must wait at least as long as any owner change here (ADR-0249).
if (IPnlReports(pnlAdapter_).workflowTimelock() < terms.timelock) revert BadTerms();
_initializeOwner(owner_);
operator = operator_;
stable = stable_;
stableDecimals = stableDecimals_;
actionManager = actionManager_;
companyFee = companyFee_;
pnlAdapter = pnlAdapter_;
sweepDestination = sweepDestination_;
feeRiseAt = terms.feeRiseAt;
feePeriod = terms.feePeriod;
feeBase = terms.feeBase;
feeStep = terms.feeStep;
feeCap = terms.feeCap;
timelock = terms.timelock;
minHuman = terms.minHuman;
maxHuman = terms.maxHuman;
minPeriod = terms.minPeriod;
maxPeriod = terms.maxPeriod;
startPeriod = terms.startPeriod;
withdrawFeeCap = uint256(terms.withdrawFeeHuman) * 10 ** stableDecimals_;
minimumDeposit = uint256(terms.startHuman) * 10 ** stableDecimals_;
nextTradingPeriod = terms.startTradingPeriod;
currentWindowId = 1;
ledger.windows[1].closesAt = HardCore.readyAt(terms.startPeriod);
ledger.main.scale = HardSettlementLib.ONE;
// Drift guard: the reentrancy-slot literal must equal Solady's preimage. Folds away on a match.
assert(_GUARD_SLOT == _GUARD_SLOT_DERIVED);
}
function _guardInitializeOwner() internal pure override returns (bool) {
return true;
}
/// @dev Solady's guard slot. It must stay a hex literal because inline assembly accepts only direct
/// number constants (solc 7615), but the literal is not trusted blindly: `_GUARD_SLOT_DERIVED` recomputes
/// it from Solady 0.1.26's own preimage and the constructor asserts the two are equal, so a hand-typed
/// slip in the literal reverts every deployment — including the whole Foundry suite's `setUp` — instead
/// of reaching production. The assert folds to `assert(true)` and is removed on a match, so there is no
/// runtime cost. A Solady bump that *moves* the slot leaves the literal and this preimage agreeing, so
/// that case is covered by `HardDepositVault_GuardSlot.t.sol`, which checks the slot Solady actually
/// writes. See the reentrancy-slot audit note.
uint256 private constant _GUARD_SLOT = 0x929eee149b4bd21268;
uint256 private constant _GUARD_SLOT_DERIVED = uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")));
/// @dev The same guard as Solady's `nonReentrant`: same slot, same `Reentrancy()` revert, same
/// release. The checks live in two private functions so the runtime holds one copy of the assembly
/// instead of one per guarded function.
modifier nonReentrant() override {
_lockGuard();
_;
_unlockGuard();
}
function _lockGuard() private {
assembly ("memory-safe") {
if eq(sload(_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_GUARD_SLOT, address())
}
}
function _unlockGuard() private {
assembly ("memory-safe") {
sstore(_GUARD_SLOT, codesize())
}
}
function openWindowClosesAt() external view returns (uint64) {
return ledger.windows[currentWindowId].closesAt;
}
/// @notice The closed window the keeper may sweep. Zero while an epoch is open, the vault is paused, or nothing is pending.
function sweepableWindow() external view returns (uint64 windowId) {
return _sweepableWindow();
}
function windowClosesAt(uint64 windowId) external view returns (uint64) {
return ledger.windows[windowId].closesAt;
}
function windowSnapshotted(uint64 windowId) external view returns (bool) {
return ledger.windows[windowId].swept;
}
/// @notice Pending stablecoin of one window and the number of wallets holding a deposit in it.
function windowPending(uint64 windowId) external view returns (uint256 amount, uint256 wallets) {
HardSettlementLib.Window storage w = ledger.windows[windowId];
return (w.stablePending, w.count);
}
/// @notice Trading capital of the live book.
function activeCapital() public view returns (uint256) {
return ledger.main.cap + ledger.fresh[ledger.freshEpoch].cap;
}
/// @notice Capital that joined at the sweep or carry that opened the current epoch: swept deposits and
/// folded reinvestment. It did not trade in the period before. While the epoch has not ended, profit and
/// loss belong to the rest of the book, `activeCapital - newCapital`, the cohort of that earlier period.
function newCapital() public view returns (uint256) {
return ledger.fresh[ledger.freshEpoch].cap;
}
/// @notice Net profit credited to the book that accounts have not settled yet. It is accounted, not surplus.
function unsettledProfit() external view returns (uint256) {
return ledger.unsettledProfit;
}
/// @notice Reinvestment waiting for the next `sweep` or `carryEpoch`, and the round it belongs to.
function reinvestWaiting() external view returns (uint256 amount, uint64 round) {
return (ledger.reinvestTotal, ledger.round);
}
/// @notice The current book generation. A whole-book wipe or `redeem` ends one.
function generation() external view returns (uint64) {
return ledger.gen;
}
/// @notice The account of `investor` as a settlement would leave it, without writing.
function account(address investor) external view returns (HardSettlementLib.AccountView memory) {
return HardSettlementLib.accountOf(ledger, investor);
}
/// @notice Profit fee a first deposit would lock at `timestamp`.
function feeAt(uint256 timestamp) external view returns (uint16) {
return _feeAt(timestamp);
}
function _feeAt(uint256 timestamp) internal view returns (uint16) {
return HardCore.feeAt(timestamp, feeRiseAt, feePeriod, feeBase, feeStep, feeCap);
}
/// @notice Free stablecoin that is not pending, claimable, reserved for redemption, or credited and
/// unsettled. `distribute` credits at most the attested profit of it. A book marked to zero hides it
/// until `redeem`.
function surplus() public view returns (uint256) {
if (wipedCapital != 0) return 0;
return _rawSurplus();
}
/// @notice Free stablecoin `redeem` splits, principal first. A wiped book does not hide it.
function unaccounted() external view returns (uint256) {
return _rawSurplus();
}
/// @notice Set or clear the emergency guardian. Owner only.
function setGuardian(address next) external onlyOwner {
guardian = next;
emit GuardianSet(next);
}
function setPaused(bool next) external {
// The owner may pause or unpause; the guardian may only pause.
if (msg.sender != owner() && !(next && msg.sender == guardian)) revert Unauthorized();
if (redemptionPending) {
if (!next) revert RedemptionAlreadyPending();
// A pause during the redemption is kept when the redemption is cancelled (audit 2 rev 2, M-01).
redemptionStartedPaused = true;
}
_setPaused(next);
}
/// @dev A pause classifies nothing. Free stablecoin stays surplus: a report credits at most its attested
/// profit, and `redeem` splits the rest into principal first.
function _setPaused(bool next) internal {
paused = next;
emit PausedSet(next);
}
function proposeMinimum(uint256 humanUnits) external onlyOwner {
if (humanUnits < minHuman || humanUnits > maxHuman) revert BadMinimum();
pendingMinimum = humanUnits * 10 ** stableDecimals;
minimumReadyAt = _readyAt();
minimumPending = true;
emit MinimumProposed(pendingMinimum, minimumReadyAt);
}
function applyMinimum() external onlyOwner {
_ripe(minimumPending, minimumReadyAt);
minimumDeposit = pendingMinimum;
minimumPending = false;
emit MinimumApplied(minimumDeposit);
}
function proposeOperator(address next) external onlyOwner {
if (next == address(0)) revert ZeroAddress();
pendingOperator = next;
operatorReadyAt = _readyAt();
operatorPending = true;
emit OperatorProposed(next, operatorReadyAt);
}
function applyOperator() external onlyOwner {
_ripe(operatorPending, operatorReadyAt);
operator = pendingOperator;
operatorPending = false;
emit OperatorApplied(operator);
}
function proposeKeeper(address next) external onlyOwner {
if (next == address(0)) revert ZeroAddress();
pendingKeeper = next;
keeperReadyAt = _readyAt();
keeperPending = true;
emit KeeperProposed(next, keeperReadyAt);
}
function applyKeeper() external onlyOwner {
_ripe(keeperPending, keeperReadyAt);
keeper = pendingKeeper;
keeperPending = false;
emit KeeperApplied(keeper);
}
/// @notice Emergency revocation for a compromised operator. Owner or guardian. Setting a new operator still waits the deploy timelock.
function disableOperator() external {
_onlyOwnerOrGuardian();
operator = address(0);
operatorPending = false;
pendingOperator = address(0);
emit OperatorApplied(address(0));
}
/// @notice Emergency revocation for a compromised keeper. Owner or guardian. Setting a new keeper still waits the deploy timelock.
function disableKeeper() external {
_onlyOwnerOrGuardian();
keeper = address(0);
keeperPending = false;
pendingKeeper = address(0);
emit KeeperApplied(address(0));
}
function _onlyOwnerOrGuardian() internal view {
if (msg.sender != owner() && msg.sender != guardian) revert Unauthorized();
}
/// @notice Queue the trading-period length used by the next sweep. The open epoch end stays.
function proposeTradingPeriod(uint256 seconds_) external onlyOwner {
if (seconds_ < minPeriod || seconds_ > maxPeriod) revert BadPeriod();
pendingTradingPeriod = seconds_;
tradingPeriodReadyAt = _readyAt();
tradingPeriodPending = true;
emit TradingPeriodProposed(seconds_, tradingPeriodReadyAt);
}
function applyTradingPeriod() external onlyOwner {
_ripe(tradingPeriodPending, tradingPeriodReadyAt);
nextTradingPeriod = pendingTradingPeriod;
tradingPeriodPending = false;
emit TradingPeriodApplied(nextTradingPeriod);
}
/// @notice Queue acceptance of a redemption return short of the book by more than `withdrawFeeCap`.
/// After the deploy timelock `emergencyRedeem` of this id accepts a shortfall up to `shortfall`. A report
/// redemption needs none: the attested loss is the shortfall.
function proposeShortfall(uint256 redemptionId, uint256 shortfall) external onlyOwner {
if (!redemptionPending) revert NoRedemptionPending();
if (redemptionId != pendingRedemptionId) revert RedemptionMismatch();
if (shortfall == 0) revert ZeroAmount();
if (shortfall > redemptionBook) revert LossTooLarge();
shortfallPending = true;
shortfallRedemptionId = redemptionId;
pendingShortfall = shortfall;
shortfallReadyAt = _readyAt();
emit ShortfallProposed(redemptionId, shortfall, shortfallReadyAt);
}
/// @notice Bring the accounts of `wallets` up to date. Anyone may call it; the result does not depend on
/// who settles or when. The keeper may batch it so idle accounts show current figures on chain.
function settle(address[] calldata wallets) external nonReentrant {
for (uint256 i; i < wallets.length; ++i) {
_settle(wallets[i]);
}
}
/// @notice Pull `amount` onto this contract into the open window. The floor is `minimumDeposit`, the
/// smallest amount an investor may place here. That floor is not a minimum for `sweep`.
function deposit(uint256 amount) external nonReentrant returns (uint64 windowId) {
if (paused) revert Paused();
if (amount < minimumDeposit) revert BelowMinimum();
// Pool capital is checked against 128 bits at each open; refuse here so a closed window can always sweep.
if (pendingTotal + activeCapital() + amount > type(uint128).max) revert AmountTooLarge();
HardSettlementLib.Account storage a = _settled(msg.sender);
uint16 feeBps = _lockFee(a);
windowId = _windowForNewCapital();
uint256 beforeBal = _stableBalance();
SafeTransferLib.safeTransferFrom(stable, msg.sender, address(this), amount);
if (_stableBalance() - beforeBal != amount) revert InsufficientSurplus();
HardSettlementLib.Window storage w = ledger.windows[windowId];
if (a.winA == windowId && a.amtA != 0) {
a.amtA += amount;
} else if (a.winB == windowId && a.amtB != 0) {
a.amtB += amount;
} else {
// After settlement only unswept windows hold a deposit, and at most two are unswept.
if (a.amtA == 0) {
a.winA = windowId;
a.amtA = amount;
} else if (a.amtB == 0) {
a.winB = windowId;
a.amtB = amount;
} else {
revert SweepRequired();
}
w.count += 1;
}
w.stablePending += amount;
w.feeWeight += uint256(feeBps) * amount;
pendingTotal += amount;
emit Deposited(msg.sender, windowId, amount, feeBps);
}
/// @notice Return pending capital of one window before it is swept. Trading capital stays put.
function cancel(uint64 windowId, uint256 amount) external nonReentrant {
if (amount == 0) revert ZeroAmount();
HardSettlementLib.Account storage a = _settled(msg.sender);
HardSettlementLib.Window storage w = ledger.windows[windowId];
if (w.swept) revert NotPending();
bool inA = a.winA == windowId && a.amtA != 0;
if (!inA && !(a.winB == windowId && a.amtB != 0)) revert NotPending();
uint256 held = inA ? a.amtA : a.amtB;
if (amount > held) revert InsufficientPending();
uint256 left = held - amount;
if (left != 0 && left < minimumDeposit) revert BelowMinimum();
if (inA) {
a.amtA = left;
if (left == 0) a.winA = 0;
} else {
a.amtB = left;
if (left == 0) a.winB = 0;
}
if (left == 0) w.count -= 1;
w.stablePending -= amount;
w.feeWeight -= uint256(a.feeBps) * amount;
pendingTotal -= amount;
if (windowId == staleUnswept && w.stablePending == 0) {
w.swept = true;
staleUnswept = 0;
}
_releaseFeeIfUncommitted(a);
emit Cancelled(msg.sender, windowId, amount);
_pay(msg.sender, amount);
}
/// @notice Send one closed window's pending stablecoin to the constructor destination.
/// When a closed window still holds a deposit, only the window `sweepableWindow` returns can be swept.
/// The amount is that window's pending balance plus the reinvestment waiting in this round; it is not
/// compared with `minimumDeposit`. The transfer is a placeholder until OQ-034 names the Derive deposit
/// calldata. Both become the fresh capital of the epoch this sweep opens; accounts pick it up at settlement.
function sweep(uint64 windowId) external nonReentrant {
if (paused) revert Paused();
_onlySettlement();
HardSettlementLib.Window storage w = ledger.windows[windowId];
if (w.closesAt == 0) revert UnknownWindow();
if (block.timestamp < w.closesAt) revert WindowOpen();
if (w.swept) revert AlreadySwept();
if (profitEpochOpen) revert ProfitEpochOpen();
if (wipedCapital != 0) revert UnpaidWipe();
uint64 due = _sweepableWindow();
if (due != 0 && windowId != due) revert SweepRequired();
uint256 amount = w.stablePending;
uint256 weight = w.feeWeight;
uint256 count = w.count;
w.swept = true;
w.stablePending = 0;
if (staleUnswept == windowId) staleUnswept = 0;
// A later window that already closed with deposits joins the same epoch. Stretching it to the new
// epoch end would reopen a closed window (audit 2 L-1, ADR-0249).
uint64 laterId = currentWindowId;
HardSettlementLib.Window storage later = ledger.windows[laterId];
uint256 laterAmount;
if (laterId != windowId && _holdsClosedDeposit(later)) {
laterAmount = later.stablePending;
weight += later.feeWeight;
count += later.count;
later.swept = true;
later.stablePending = 0;
}
uint256 moved = amount + laterAmount + ledger.reinvestTotal;
if (moved != 0) {
pendingTotal -= moved;
uint64 epoch = profitEpoch + 1;
w.epoch = epoch;
if (laterAmount != 0) later.epoch = epoch;
HardSettlementLib.openEpoch(ledger, epoch, amount + laterAmount, weight, count);
_openEpoch(amount + laterAmount);
_pay(sweepDestination, moved);
}
emit Swept(windowId, moved - laterAmount, sweepDestination);
if (laterAmount != 0) emit Swept(laterId, laterAmount, sweepDestination);
}
/// @notice Credit attested profit of the next report window. The report must show a profit `A`, and the
/// free surplus `S` must cover it net of the Derive withdrawal fee: `S + withdrawFeeCap >= A`. The credit
/// is `min(S, A)`, so stablecoin above the attested figure stays surplus for `redeem`. A window that ends
/// by `epochOpenedMs` is the gap before this epoch's capital reached Derive: only the `main` pool earns it.
/// Every later window credits the whole book by capital; the one that ends at `epochEndsAt` closes the
/// epoch, an earlier one leaves it open (ADR-0249).
function distribute() external nonReentrant {
(int256 pnl, uint64 endMs, bool isFinal, bool gap) = _report();
if (pnl <= 0) revert ReportMismatch();
uint256 attested = uint256(pnl);
uint256 free = surplus();
if (free + withdrawFeeCap < attested) revert ReportMismatch();
// Profit an earlier report left on Derive is credited above this one once it arrived (audit N-2, ADR-0254).
uint256 target = attested + deferredProfit;
uint256 taken = _creditProfit(free < target ? free : target, gap && ledger.main.cap != 0);
if (taken == 0) revert NothingToDistribute();
if (taken > attested) {
uint256 paid = taken - attested;
deferredProfit -= paid < deferredProfit ? paid : deferredProfit;
}
_consumeReport(endMs, pnl, !isFinal);
}
/// @dev Credit `profit` to the book. Returns what left surplus. The remainder of the split stays surplus.
function _creditProfit(uint256 profit, bool mainOnly) internal returns (uint256 taken) {
if (profit == 0) return 0;
uint256 fee;
(taken, fee) = HardSettlementLib.credit(ledger, profit, mainOnly);
if (taken == 0) return 0;
emit Distributed(taken, taken - fee, fee);
_settleCompanyFee(fee);
}
/// @notice Mark the book down by the attested loss of the next report window: `loss` must equal `-A`.
/// No fee is charged and surplus is not touched. The same rule binds the owner: there is no markdown
/// without a report. A gap window (ending by `epochOpenedMs`) marks down only the `main` pool, or the whole
/// book when that pool cannot carry the loss. Every later window marks down the whole book; the one that
/// ends at `epochEndsAt` closes the epoch. A markdown of the whole book keeps the weights for `redeem`.
/// A partial markdown deeper than the pool scale floor reverts.
function applyLoss(uint256 loss) external nonReentrant {
(int256 pnl, uint64 endMs, bool isFinal, bool gap) = _report();
if (pnl >= 0 || loss != uint256(-pnl)) revert ReportMismatch();
uint256 remain = _markLoss(loss, gap);
_consumeReport(endMs, pnl, !isFinal && remain != 0);
}
/// @dev Mark the book down by an attested `loss`. For a gap window only `main`, the capital that traded then,
/// is marked down while it can carry the loss. A loss of the whole book wipes it.
function _markLoss(uint256 loss, bool gap) internal returns (uint256 remain) {
// The loss first burns attested profit left on Derive that no account was credited (audit 2 rev 2,
// NEW-M-02): that stablecoin was on the subaccount too.
uint256 burned = loss < deferredProfit ? loss : deferredProfit;
deferredProfit -= burned;
uint256 rest = loss - burned;
uint256 book = activeCapital();
if (book == 0) revert NoActiveSupply();
// A gap loss falls on the earlier cohort that traded then, and only its excess on the fresh pool (audit 2
// rev 2, NEW-H-01). A loss the book cannot carry wipes it instead of reverting: what comes back still
// reaches the wiped book.
if (gap) {
rest = HardSettlementLib.markGapLoss(ledger, rest);
book = activeCapital();
if (rest == 0) remain = book;
else _wipe(book);
} else if (rest >= book) {
_wipe(book);
} else {
remain = book - rest;
if (rest != 0) HardSettlementLib.markdown(ledger, remain, false);
}
emit LossApplied(profitEpoch, loss, remain);
}
/// @notice Close the epoch on a final report window whose result is between zero and `withdrawFeeCap`.
/// Such a profit is not worth a Derive withdrawal; it stays on the exchange and returns with `redeem`.
/// Surplus already on the vault stays surplus.
/// It also consumes a gap window (ending by `epochOpenedMs`), which must settle before any later window,
/// and leaves the epoch open. A profit above `withdrawFeeCap` that did not reach the vault credits the part
/// that arrived, `min(surplus, A)`, to the cohort the window belongs to; the rest stays on Derive like a
/// flat profit. For the final window that needs `epochEndsAt + timelock` (audit 2 M-3, ADR-0249). Without
/// an accepted report nothing is credited or written off.
function closeFlat() external nonReentrant {
(int256 pnl, uint64 endMs, bool isFinal, bool gap) = _report();
if (pnl < 0 || !(isFinal || gap)) revert ReportMismatch();
uint256 attested = uint256(pnl);
uint256 credited;
if (attested > withdrawFeeCap) {
// The final window waits from the epoch end, a gap window from the epoch open, so the keeper can bring
// the profit to the vault and credit it to its own cohort first (audit 2 rev 2, NEW-H-02).
uint256 from = isFinal ? uint256(epochEndsAt) : uint256(epochOpenedMs) / 1000;
if (block.timestamp < from + timelock) revert TimelockPending();
uint256 free = surplus();
credited = _creditProfit(free < attested ? free : attested, gap && ledger.main.cap != 0);
}
// The rest stays on Derive. It is remembered so it is credited, with the fee, when it arrives (ADR-0254).
if (attested > credited) {
deferredProfit += attested - credited;
emit ProfitDeferred(profitEpoch, attested - credited);
}
_consumeReport(endMs, pnl, !isFinal);
if (isFinal) emit EpochClosedFlat(profitEpoch);
}
/// @dev The accepted report that starts at `attestedUntilMs`, after the caller, pause, and epoch checks.
/// `isFinal` is true for the window that ends at `epochEndsAt`; `gap` for one that ends by `epochOpenedMs`.
function _report() internal view returns (int256 pnl, uint64 endMs, bool isFinal, bool gap) {
_onlySettlement();
if (!profitEpochOpen) revert ProfitEpochSettled();
(bool accepted, uint64 epoch, uint64 windowEndMs, int256 realizedPnl, uint64 expiresAt) =
IPnlReports(pnlAdapter).settlementReport(address(this), attestedUntilMs);
if (!accepted || epoch != profitEpoch) revert ReportMissing();
if (expiresAt < block.timestamp) revert ReportExpired();
uint256 epochEndMs = uint256(epochEndsAt) * 1000;
if (windowEndMs <= attestedUntilMs || windowEndMs > epochEndMs) revert BadReport();
// Trades before the epoch opened belong to the capital that traded then. A window may not mix the two
// (ADR-0249), and the gap settles as one window that ends at `epochOpenedMs`: a split gap could retire
// `main` on a loss and give a later gap profit to the newcomers (audit 4, A4-H-01, ADR-0260).
if (attestedUntilMs < epochOpenedMs && windowEndMs != epochOpenedMs) revert BadReport();
gap = windowEndMs <= epochOpenedMs;
// The pause of a pending redemption still lets the gap settle, which `redeem` needs first (audit N-4,
// ADR-0253). Any other pause blocks every window.
if (paused && !(gap && redemptionPending)) revert Paused();
return (realizedPnl, windowEndMs, windowEndMs == epochEndMs, gap);
}
/// @dev Move the settled line to the end of the report window. A final window closes the epoch.
function _consumeReport(uint64 endMs, int256 pnl, bool keepOpen) internal {
attestedUntilMs = endMs;
if (!keepOpen) profitEpochOpen = false;
// A gap settled during a redemption may mark the book down: `emergencyRedeem` splits the current book.
if (redemptionPending) redemptionBook = wipedCapital != 0 ? wipedCapital : activeCapital();
emit ReportSettled(profitEpoch, endMs, pnl);
}
/// @notice Open the next trading epoch on capital already sent to the destination. Reinvestment waiting
/// in this round becomes the epoch's fresh capital and is the only stablecoin sent, to `sweepDestination`.
/// Surplus stays for the same book. A closed window that still holds a deposit must be swept first.
function carryEpoch() external nonReentrant {
if (paused) revert Paused();
_onlySettlement();
if (profitEpochOpen) revert ProfitEpochOpen();
if (wipedCapital != 0) revert UnpaidWipe();
if (activeCapital() == 0) revert NoActiveSupply();
if (_sweepableWindow() != 0) revert SweepRequired();
uint256 folded = ledger.reinvestTotal;
pendingTotal -= folded;
HardSettlementLib.openEpoch(ledger, profitEpoch + 1, 0, 0, 0);
_openEpoch(0);
emit EpochCarried(profitEpoch, activeCapital(), epochEndsAt);
if (folded != 0) _pay(sweepDestination, folded);
}
/// @notice Pull available profit. Investment capital is unchanged.
function withdrawProfit(uint256 amount) external nonReentrant {
_takeAvailable(amount);
claimableTotal -= amount;
emit ProfitWithdrawn(msg.sender, amount);
_pay(msg.sender, amount);
}
/// @notice Move available profit aside. It stays withdrawable and out of trading until `reinvestStaged`.
function stageReinvest(uint256 amount) external nonReentrant {
_takeAvailable(amount).staged += amount;
emit ReinvestStaged(msg.sender, amount);
}
/// @notice Put staged profit back into the available balance.
function unstageReinvest(uint256 amount) external nonReentrant {
_takeStaged(amount).available += amount;
emit ReinvestUnstaged(msg.sender, amount);
}
/// @notice Withdraw profit that was staged and not yet reinvested.
function withdrawStaged(uint256 amount) external nonReentrant {
_takeStaged(amount);
claimableTotal -= amount;
emit ProfitWithdrawn(msg.sender, amount);
_pay(msg.sender, amount);
}
/// @notice Reinvest available profit. It waits in this round and joins trading capital at the next
/// `sweep` or `carryEpoch` as fresh capital of the epoch that call opens. There is no automatic share:
/// only the wallet decides.
function reinvest(uint256 amount) external nonReentrant {
if (paused) revert Paused();
_reinvestTaken(_takeAvailable(amount), amount);
}
/// @notice Confirm staged profit. Same rules as `reinvest`.
function reinvestStaged(uint256 amount) external nonReentrant {
if (paused) revert Paused();
_reinvestTaken(_takeStaged(amount), amount);
}
/// @notice Return reinvestment that has not joined capital yet to available profit. Pause does not block it.
function cancelReinvest(uint256 amount) external nonReentrant {
if (amount == 0) revert ZeroAmount();
HardSettlementLib.Account storage a = _settled(msg.sender);
if (amount > a.reinvest) revert InsufficientPending();
a.reinvest -= amount;
if (a.reinvest == 0) ledger.reinvestCount -= 1;
ledger.reinvestTotal -= amount;
ledger.reinvestWeight -= uint256(a.feeBps) * amount;
pendingTotal -= amount;
a.available += amount;
claimableTotal += amount;
emit ReinvestCancelled(msg.sender, amount);
}
/// @notice Enter the paused principal-return mode before withdrawing trading capital from Derive. Owner only:
/// it pauses every investor and ends the book generation (ADR-0248).
function beginRedemption(uint256 redemptionId) external onlyOwner {
if (redemptionPending) revert RedemptionAlreadyPending();
if (redeemed[redemptionId]) revert AlreadyRedeemed();
uint256 book = wipedCapital != 0 ? wipedCapital : activeCapital();
if (book == 0) revert NoActiveSupply();
redemptionStartedPaused = paused;
_setPaused(true);
redemptionPending = true;
pendingRedemptionId = redemptionId;
redemptionBook = book;
redemptionStartedAt = uint64(block.timestamp);
emit RedemptionStarted(redemptionId, book);
}
/// @notice Cancel a redemption intent before it is redeemed. Owner only. The free stablecoin stays surplus.
function cancelRedemption(uint256 redemptionId) external onlyOwner {
_pendingId(redemptionId);
bool restorePaused = redemptionStartedPaused;
_clearRedemptionIntent();
if (!restorePaused) _setPaused(false);
emit RedemptionCancelled(redemptionId);
}
/// @notice Return of trading capital against the Chainlink CRE redemption report. Any settlement role may call
/// it: the report decides the split, not the caller. The report starts at `attestedUntilMs`, ends after
/// `beginRedemption`, names this id, and shows a Derive subaccount with no open position and a value of at
/// most `withdrawFeeCap`. An attested loss marks the book down first, as `applyLoss` does. The vault must
/// then hold `book + profit`, short by at most `withdrawFeeCap`, or the return is still on its way and the
/// call reverts. Principal comes first, up to the book; the rest, at most the attested profit, carries the
/// company fee. Stablecoin above that is paid back with the principal, without a fee. See ADR-0248, ADR-0252.
function redeem(uint256 redemptionId) external nonReentrant {
_onlySettlement();
_pendingId(redemptionId);
(
bool accepted,
uint256 reportedId,
uint64 epoch,
uint64 windowEndMs,
int256 pnl,
uint256 openPositions,
uint256 remainingValue,
uint64 expiresAt
) = IPnlReports(pnlAdapter).redemptionReport(address(this), attestedUntilMs);
if (!accepted || reportedId != redemptionId || epoch != profitEpoch) revert ReportMissing();
// The gap before the epoch opened must be settled first, by its own report (ADR-0249). A closed epoch (a
// book wiped on a gap window) has no cohort to split it (audit 2 rev 2, NEW-H-04).
if (profitEpochOpen && attestedUntilMs < epochOpenedMs) revert ReportMissing();
if (expiresAt < block.timestamp) revert ReportExpired();
if (uint256(windowEndMs) <= uint256(redemptionStartedAt) * 1000) revert BadReport();
if (openPositions != 0 || remainingValue > withdrawFeeCap) revert ReportMismatch();
if (pnl < 0 && wipedCapital == 0) _markLoss(uint256(-pnl), false);
uint256 book = wipedCapital != 0 ? wipedCapital : activeCapital();
uint256 gain = pnl > 0 ? uint256(pnl) : 0;
// A wiped book has nothing left on Derive but what it earned after the wipe.
uint256 expected = (wipedCapital != 0 ? 0 : book) + gain;
uint256 free = _rawSurplus();
if (free + withdrawFeeCap < expected) revert InsufficientSurplus();
// All free stablecoin goes to the book that traded it, so a reported loss cannot leave returned
// capital as surplus for the next generation (audit N-1, ADR-0252). Principal first up to the book,
// then at most the attested profit with the company fee; the rest is paid back with the principal.
uint256 base = free < book ? free : book;
uint256 rest = free - base;
// Profit left on Derive by an earlier `closeFlat` is profit too, though this report does not show it.
uint256 feeable = gain + deferredProfit;
uint256 profit = rest < feeable ? rest : feeable;
_closeRedemption(redemptionId, free - profit, profit, book, pnl);
}
/// @notice Return of trading capital without a report, for when the CRE workflow cannot attest. Owner only,
/// and not before `timelock` after `beginRedemption`. The amount is all free stablecoin: principal comes
/// first, up to the book fixed at `beginRedemption`, and only stablecoin above the book is profit. A return
/// short of the book by more than `withdrawFeeCap` needs a ripe `proposeShortfall` for this id and
/// `SHORTFALL_WAIT` from `beginRedemption` (ADR-0252).
function emergencyRedeem(uint256 redemptionId) external onlyOwner nonReentrant {
_pendingId(redemptionId);
_ripe(true, redemptionStartedAt + timelock);
uint256 total = _rawSurplus();
uint256 book = redemptionBook;
if (total < book) _checkShortfall(redemptionId, book - total);
uint256 principal = total < book ? total : book;
_closeRedemption(redemptionId, principal, total - principal, book, 0);
}
/// @dev Pay `principal` to the book generation by capital, then credit `profit` with the company fee.
/// `principal` may exceed `book`: the excess is returned capital above the report. Investors bear a gap
/// pro rata. The generation ends, waiting reinvestment returns to available profit, and the report line
/// moves to now, so the next generation's first window holds none of these trades.
function _closeRedemption(uint256 redemptionId, uint256 principal, uint256 profit, uint256 book, int256 pnl)
internal
{
redeemed[redemptionId] = true;
deferredProfit = 0;
uint64 gen;
uint256 taken;
uint256 fee;
if (wipedCapital != 0) {
// The weights are the capital at the wipe, and the whole wiped book shares the profit.
gen = ledger.gen - 1;
(taken, fee) = HardSettlementLib.creditEnded(ledger, gen, profit);
wipedCapital = 0;
} else {
// The redemption window starts at or after `epochOpenedMs`, so the whole book shares it (ADR-0249).
(taken, fee) = HardSettlementLib.credit(ledger, profit, false);
gen = HardSettlementLib.endGen(ledger);
}
HardSettlementLib.closeGen(ledger, gen, principal, book);
redemptionReserve += principal;
uint256 released = HardSettlementLib.releaseReinvest(ledger);
if (released != 0) {
pendingTotal -= released;
claimableTotal += released;
}
_clearRedemptionIntent();
uint64 nowMs = uint64(block.timestamp * 1000);
if (nowMs > attestedUntilMs) attestedUntilMs = nowMs;
emit ReportSettled(profitEpoch, attestedUntilMs, pnl);
_settleCompanyFee(fee);
// The book is empty now. An epoch still open would block `sweep` and `carryEpoch`. See ADR-0159.
if (profitEpochOpen) profitEpochOpen = false;
emit Redeemed(redemptionId, principal, taken - fee, fee);
}
/// @dev The vault is paused by the pending redemption `redemptionId`, which is not redeemed yet.
function _pendingId(uint256 redemptionId) internal view {
if (!redemptionPending) revert NoRedemptionPending();
if (redemptionId != pendingRedemptionId) revert RedemptionMismatch();
}
function claimRedemption() external nonReentrant {
HardSettlementLib.Account storage a = _settled(msg.sender);
uint256 pay = a.redeemable;
if (pay == 0) revert NothingToClaim();
a.redeemable = 0;
redemptionReserve -= pay;
emit RedemptionClaimed(msg.sender, pay);
_pay(msg.sender, pay);
}
/// @notice Deliver a previously deferred company fee to `companyFee`. Permissionless: the recipient
/// is fixed, so anyone can trigger the payout once the earlier transfer blocker is cleared.
function claimCompanyFee() external nonReentrant {
uint256 amount = claimableCompanyFee;
if (amount == 0) revert NothingToClaim();
claimableCompanyFee = 0;
emit CompanyFeeClaimed(amount);
_pay(companyFee, amount);
}
/// @notice Register a session key. Scope code 0 is `admin` and is refused.
/// Only withdraw (1), trading (2 to 10), and vault (17) scope codes pass; an empty list is a read-only key.
/// The key lives at most 90 days. A key with scopes must name its subaccounts (audit 2 M-5, ADR-0249), and
/// each must be the subaccount the adapter attests for this vault (audit 2 rev 2, NEW-L-02).
function authorizeSessionKey(
address sessionKey,
uint256 expiry,
uint256[] calldata scopes,
uint256[] calldata subaccountIds
) external onlyOwner nonReentrant {
HardSettlementLib.authorizeSessionKey(actionManager, pnlAdapter, sessionKey, expiry, scopes, subaccountIds);
emit SessionKeySubmitted(sessionKey, expiry);
}
/// @notice Revoke a Derive session key. The owner or the guardian may call it; a revoke is expiry zero.
function revokeSessionKey(address sessionKey) external nonReentrant {
_onlyOwnerOrGuardian();
HardSettlementLib.submitSessionKey(actionManager, sessionKey, 0, new uint256[](0), new uint256[](0));
emit SessionKeySubmitted(sessionKey, 0);
}
/// @notice Sweep out a non-stable token sent here by mistake. The owner pair chooses `to`; the vault
/// cannot send the custody `stable` this way. The arbitrary-destination guard (invariant) is on `stable`
/// only, so `recover` of any other token rests on the honesty of the 2-of-2 owner pair. See invariant I-recover.
function recover(address token, address to) external onlyOwner nonReentrant {
if (token == address(0) || to == address(0)) revert ZeroAddress();
if (token == stable) revert TokenNotRecoverable();
uint256 amount = _balanceOf(token, address(this));
if (amount == 0) revert ZeroAmount();
SafeTransferLib.safeTransfer(token, to, amount);
emit Recovered(token, to, amount);
}
function _readyAt() internal view returns (uint64) {
return HardCore.readyAt(timelock);
}
function _ripe(bool pending, uint64 readyAt) internal view {
if (!pending || block.timestamp < readyAt) revert TimelockPending();
}
function _onlySettlement() internal view {
if (msg.sender != owner() && msg.sender != operator && msg.sender != keeper) revert Unauthorized();
}
function _checkShortfall(uint256 redemptionId, uint256 shortfall) internal {
if (shortfall <= withdrawFeeCap) return;
if (!shortfallPending || shortfallRedemptionId != redemptionId || shortfall > pendingShortfall) {
revert SettlementTooLarge();
}
_ripe(true, shortfallReadyAt);
// The capital may still be on its way from Derive. Closing short before it arrives would leave it as
// surplus with no owner (audit N-1, ADR-0252).
_ripe(true, redemptionStartedAt + HardCore.SHORTFALL_WAIT);
shortfallPending = false;
}
function _clearRedemptionIntent() internal {
redemptionPending = false;
pendingRedemptionId = 0;
redemptionBook = 0;
redemptionStartedPaused = false;
redemptionStartedAt = 0;
shortfallPending = false;
}
/// @dev The closed window that still holds a deposit. Zero while an epoch is open, the vault is paused, or nothing is pending.
function _sweepableWindow() internal view returns (uint64 windowId) {
if (paused || profitEpochOpen || wipedCapital != 0) return 0;
if (staleUnswept != 0 && _holdsClosedDeposit(ledger.windows[staleUnswept])) return staleUnswept;
if (_holdsClosedDeposit(ledger.windows[currentWindowId])) return currentWindowId;
return 0;
}
function _holdsClosedDeposit(HardSettlementLib.Window storage w) internal view returns (bool) {
return !w.swept && w.closesAt != 0 && block.timestamp >= w.closesAt && w.stablePending != 0;
}
/// @dev A window opened during a trading epoch closes with that epoch. A window
/// opened while no epoch is open waits the trading period that is current then.
/// After `epochEndsAt` has passed but before the epoch is settled, a rolled window
/// takes a future close time instead of the elapsed `epochEndsAt`, so a late deposit
/// does not open an already-expired window.
/// The constructor sets the first window to five days and does not call this.
function _windowCloseAt() internal view returns (uint64) {
if (profitEpochOpen && epochEndsAt > block.timestamp) return epochEndsAt;
return uint64(block.timestamp + nextTradingPeriod);
}
/// @dev Open the next profit epoch after the library opened its pools. `intake` is the swept deposits.
/// There is no deposit fee (ADR-0169).
/// Pool capital stays inside 128 bits so the index arithmetic cannot overflow.
function _openEpoch(uint256 intake) internal {
if (activeCapital() > type(uint128).max) revert AmountTooLarge();
epochIntake = intake;
// The first open of a generation starts the chain of report windows: with no earlier cohort there is no
// gap to settle (audit 2 rev 2, NEW-M-01). Later windows start where the last settled one ended.
uint64 nowMs = uint64(block.timestamp * 1000);
if (ledger.main.cap == 0) attestedUntilMs = nowMs;
epochOpenedMs = nowMs;
profitEpoch += 1;
profitEpochOpen = true;
epochEndsAt = uint64(block.timestamp + nextTradingPeriod);
_pinCollectingWindow(epochEndsAt);
}
/// @dev If the next window was opened before this sweep, stretch it to the epoch just stored.
function _pinCollectingWindow(uint64 epochEnd) internal {
HardSettlementLib.Window storage current = ledger.windows[currentWindowId];
if (current.swept || current.closesAt == 0) return;
current.closesAt = epochEnd;
}
/// @dev Save the book as redemption weights and end its generation. A second full markdown reverts until
/// `redeem` pays the weights already saved.
function _wipe(uint256 book) internal {
if (wipedCapital != 0) revert UnpaidWipe();
HardSettlementLib.endGen(ledger);
wipedCapital = book;
}
function _rawSurplus() internal view returns (uint256) {
uint256 balance = _stableBalance();
uint256 accounted =
pendingTotal + claimableTotal + redemptionReserve + claimableCompanyFee + ledger.unsettledProfit;
return balance > accounted ? balance - accounted : 0;
}
function _settle(address investor) internal {
uint256 net = HardSettlementLib.settle(ledger, investor);
if (net != 0) claimableTotal += net;
}
function _settled(address investor) internal returns (HardSettlementLib.Account storage) {
_settle(investor);
return ledger.accounts[investor];
}
/// @dev The first deposit that is still pending locks the wallet rate.
/// A later deposit keeps it. Sweep makes the lock permanent.
function _lockFee(HardSettlementLib.Account storage a) internal returns (uint16 feeBps) {
if (a.feeLocked) return a.feeBps;
feeBps = _feeAt(block.timestamp);
a.feeLocked = true;
a.feeBps = feeBps;
emit FeeLocked(msg.sender, feeBps);
}
/// @dev A wallet with no pending deposit and no swept deposit does not keep the rate.
function _releaseFeeIfUncommitted(HardSettlementLib.Account storage a) internal {
if (a.feeCommitted || a.amtA != 0 || a.amtB != 0 || a.reinvest != 0) return;
a.feeLocked = false;
a.feeBps = 0;
}
/// @dev An expired window with nothing pending is closed in place. A timelock
/// warp must not leave an empty window as `staleUnswept` and block the next deposit.
function _rollWindow() internal {
HardSettlementLib.Window storage current = ledger.windows[currentWindowId];
if (block.timestamp < current.closesAt) return;
if (current.stablePending == 0) current.swept = true;
if (staleUnswept != 0 && !ledger.windows[staleUnswept].swept) revert SweepRequired();
if (!current.swept) staleUnswept = currentWindowId;
currentWindowId += 1;
ledger.windows[currentWindowId].closesAt = _windowCloseAt();
}
function _windowForNewCapital() internal returns (uint64 windowId) {
_rollWindow();
if (ledger.windows[currentWindowId].swept) {
if (staleUnswept != 0 && !ledger.windows[staleUnswept].swept) revert SweepRequired();
currentWindowId += 1;
windowId = currentWindowId;
ledger.windows[windowId].closesAt = _windowCloseAt();
return windowId;
}
return currentWindowId;
}
/// @dev Debits the caller's available profit after settling it.
function _takeAvailable(uint256 amount) internal returns (HardSettlementLib.Account storage a) {
if (amount == 0) revert ZeroAmount();
a = _settled(msg.sender);
if (amount > a.available) revert NothingToClaim();
a.available -= amount;
}
/// @dev Debits the caller's staged profit after settling it.
function _takeStaged(uint256 amount) internal returns (HardSettlementLib.Account storage a) {
if (amount == 0) revert ZeroAmount();
a = _settled(msg.sender);
if (amount > a.staged) revert NothingToClaim();
a.staged -= amount;
}
/// @dev The profit of `amount` has already left the account's balance; it waits in the open round.
/// After settlement a non-zero waiting amount always belongs to the open round.
function _reinvestTaken(HardSettlementLib.Account storage a, uint256 amount) internal {
if (!a.feeLocked) revert NothingToClaim();
claimableTotal -= amount;
pendingTotal += amount;
uint64 round = ledger.round;
if (a.reinvest == 0) {
a.reinvestRound = round;
ledger.reinvestCount += 1;
}
a.reinvest += amount;
ledger.reinvestTotal += amount;
ledger.reinvestWeight += uint256(a.feeBps) * amount;
emit Reinvested(msg.sender, amount, round);
}
/// @dev Deliver the company fee to `companyFee`. A failing transfer (for example a stablecoin
/// blocklist of `companyFee`) must never revert epoch settlement, so the undelivered amount is held
/// for `claimCompanyFee` instead. The non-reverting transfer lives in the linked library.
function _settleCompanyFee(uint256 feeTotal) internal {
uint256 deferred = HardSettlementLib.settleCompanyFee(stable, companyFee, feeTotal);
if (deferred != 0) claimableCompanyFee += deferred;
}
function _pay(address to, uint256 amount) internal {
SafeTransferLib.safeTransfer(stable, to, amount);
}
function _stableBalance() internal view returns (uint256) {
return _balanceOf(stable, address(this));
}
function _balanceOf(address token, address account_) internal view returns (uint256 amount) {
bool ok;
(ok, amount) = SafeTransferLib.checkBalanceOf(token, account_);
if (!ok) revert BalanceUnreadable();
}
}
lib/solady/src/auth/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
lib/solady/src/utils/FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error ExpOverflow();
/// @dev The operation failed, as the output exceeds the maximum value of uint256.
error FactorialOverflow();
/// @dev The operation failed, due to an overflow.
error RPowOverflow();
/// @dev The mantissa is too big to fit.
error MantissaOverflow();
/// @dev The operation failed, due to an multiplication overflow.
error MulWadFailed();
/// @dev The operation failed, due to an multiplication overflow.
error SMulWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error DivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error SDivWadFailed();
/// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
error MulDivFailed();
/// @dev The division failed, as the denominator is zero.
error DivFailed();
/// @dev The full precision multiply-divide operation failed, either due
/// to the result being larger than 256 bits, or a division by a zero.
error FullMulDivFailed();
/// @dev The output is undefined, as the input is less-than-or-equal to zero.
error LnWadUndefined();
/// @dev The input outside the acceptable domain.
error OutOfDomain();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The scalar of ETH and most ERC20s.
uint256 internal constant WAD = 1e18;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* SIMPLIFIED FIXED POINT OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to `(x * y) / WAD` rounded down.
function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if gt(x, div(not(0), y)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded towards zero.
function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded towards zero, but without overflow checks.
function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, y), WAD)
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up.
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
if iszero(eq(div(z, y), x)) {
if y {
mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
revert(0x1c, 0x04)
}
}
z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
}
}
/// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down.
function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded towards zero.
function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, WAD)
// Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
if iszero(mul(y, eq(sdiv(z, WAD), x))) {
mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
revert(0x1c, 0x04)
}
z := sdiv(z, y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded towards zero, but without overflow and divide by zero checks.
function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(mul(x, WAD), y)
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up.
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
}
}
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
/// Note: This function is an approximation.
function powWad(int256 x, int256 y) internal pure returns (int256) {
// Using `ln(x)` means `x` must be greater than 0.
return expWad((lnWad(x) * y) / int256(WAD));
}
/// @dev Returns `exp(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function expWad(int256 x) internal pure returns (int256 r) {
unchecked {
// When the result is less than 0.5 we return zero.
// This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
if (x <= -41446531673892822313) return r;
/// @solidity memory-safe-assembly
assembly {
// When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
// an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
if iszero(slt(x, 135305999368893231589)) {
mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
revert(0x1c, 0x04)
}
}
// `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
// for more intermediate precision and a binary basis. This base conversion
// is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
x = (x << 78) / 5 ** 18;
// Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
// of two such that exp(x) = exp(x') * 2**k, where k is an integer.
// Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
x = x - k * 54916777467707473351141471128;
// `k` is in the range `[-61, 195]`.
// Evaluate using a (6, 7)-term rational approximation.
// `p` is made monic, we'll multiply by a scale factor later.
int256 y = x + 1346386616545796478920950773328;
y = ((y * x) >> 96) + 57155421227552351082224309758442;
int256 p = y + x - 94201549194550492254356042504812;
p = ((p * y) >> 96) + 28719021644029726153956944680412240;
p = p * x + (4385272521454847904659076985693276 << 96);
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
int256 q = x - 2855989394907223263936484059900;
q = ((q * x) >> 96) + 50020603652535783019961831881945;
q = ((q * x) >> 96) - 533845033583426703283633433725380;
q = ((q * x) >> 96) + 3604857256930695427073651918091429;
q = ((q * x) >> 96) - 14423608567350463180887372962807573;
q = ((q * x) >> 96) + 26449188498355588339934803723976023;
/// @solidity memory-safe-assembly
assembly {
// Div in assembly because solidity adds a zero check despite the unchecked.
// The q polynomial won't have zeros in the domain as all its roots are complex.
// No scaling is necessary because p is already `2**96` too large.
r := sdiv(p, q)
}
// r should be in the range `(0.09, 0.25) * 2**96`.
// We now need to multiply r by:
// - The scale factor `s ≈ 6.031367120`.
// - The `2**k` factor from the range reduction.
// - The `1e18 / 2**96` factor for base conversion.
// We do this all at once, with an intermediate result in `2**213`
// basis, so the final right shift is always by a positive amount.
r = int256(
(uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
);
}
}
/// @dev Returns `ln(x)`, denominated in `WAD`.
/// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
/// Note: This function is an approximation. Monotonically increasing.
function lnWad(int256 x) internal pure returns (int256 r) {
/// @solidity memory-safe-assembly
assembly {
// We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
// We do this by multiplying by `2**96 / 10**18`. But since
// `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
// and add `ln(2**96 / 10**18)` at the end.
// Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// We place the check here for more optimal stack operations.
if iszero(sgt(x, 0)) {
mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
revert(0x1c, 0x04)
}
// forgefmt: disable-next-item
r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))
// Reduce range of x to (1, 2) * 2**96
// ln(2^k * x) = k * ln(2) + ln(x)
x := shr(159, shl(r, x))
// Evaluate using a (8, 8)-term rational approximation.
// `p` is made monic, we will multiply by a scale factor later.
// forgefmt: disable-next-item
let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
sar(96, mul(add(43456485725739037958740375743393,
sar(96, mul(add(24828157081833163892658089445524,
sar(96, mul(add(3273285459638523848632254066296,
x), x))), x))), x)), 11111509109440967052023855526967)
p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
// We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
// `q` is monic by convention.
let q := add(5573035233440673466300451813936, x)
q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
q := add(909429971244387300277376558375, sar(96, mul(x, q)))
// `p / q` is in the range `(0, 0.125) * 2**96`.
// Finalization, we need to:
// - Multiply by the scale factor `s = 5.549…`.
// - Add `ln(2**96 / 10**18)`.
// - Add `k * ln(2)`.
// - Multiply by `10**18 / 2**96 = 5**18 >> 78`.
// The q polynomial is known not to have zeros in the domain.
// No scaling required because p is already `2**96` too large.
p := sdiv(p, q)
// Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
p := mul(1677202110996718588342820967067443963516166, p)
// Add `ln(2) * k * 5**18 * 2**192`.
// forgefmt: disable-next-item
p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
// Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
// Base conversion: mul `2**18 / 2**192`.
r := sar(174, p)
}
}
/// @dev Returns `W_0(x)`, denominated in `WAD`.
/// See: https://en.wikipedia.org/wiki/Lambert_W_function
/// a.k.a. Product log function. This is an approximation of the principal branch.
/// Note: This function is an approximation. Monotonically increasing.
function lambertW0Wad(int256 x)
internal
pure
returns (int256 w)
{
// forgefmt: disable-next-item
unchecked {
if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
(int256 wad, int256 p) = (int256(WAD), x);
uint256 c; // Whether we need to avoid catastrophic cancellation.
uint256 i = 4; // Number of iterations.
if (w <= 0x1ffffffffffff) {
if (-0x4000000000000 <= w) {
i = 1; // Inputs near zero only take one step to converge.
} else if (w <= -0x3ffffffffffffff) {
i = 32; // Inputs near `-1/e` take very long to converge.
}
} else if (uint256(w >> 63) == uint256(0)) {
/// @solidity memory-safe-assembly
assembly {
// Inline log2 for more performance, since the range is small.
let v := shr(49, w)
let l := shl(3, lt(0xff, v))
l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
c := gt(l, 60)
i := add(2, add(gt(l, 53), c))
}
} else {
int256 ll = lnWad(w = lnWad(w));
/// @solidity memory-safe-assembly
assembly {
// `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
i := add(3, iszero(shr(68, x)))
c := iszero(shr(143, x))
}
if (c == uint256(0)) {
do { // If `x` is big, use Newton's so that intermediate values won't overflow.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := mul(w, div(e, wad))
w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
}
if (p <= w) break;
p = w;
} while (--i != uint256(0));
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
return w;
}
}
do { // Otherwise, use Halley's for faster convergence.
int256 e = expWad(w);
/// @solidity memory-safe-assembly
assembly {
let t := add(w, wad)
let s := sub(mul(w, e), mul(x, wad))
w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
}
if (p <= w) break;
p = w;
} while (--i != c);
/// @solidity memory-safe-assembly
assembly {
w := sub(w, sgt(w, 2))
}
// For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
// R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
if (c == uint256(0)) return w;
int256 t = w | 1;
/// @solidity memory-safe-assembly
assembly {
x := sdiv(mul(x, wad), t)
}
x = (t * (wad + lnWad(x)));
/// @solidity memory-safe-assembly
assembly {
w := sdiv(x, add(wad, t))
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* GENERAL NUMBER UTILITIES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `a * b == x * y`, with full precision.
function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// 512-bit multiply `[p1 p0] = x * y`.
// Compute the product mod `2**256` and mod `2**256 - 1`
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that `product = p1 * 2**256 + p0`.
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`.
for {} 1 {} {
// If overflows.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
/*------------------- 512 by 256 division --------------------*/
// Make division exact by subtracting the remainder from `[p1 p0]`.
let r := mulmod(x, y, d) // Compute remainder using mulmod.
let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
// Make sure `z` is less than `2**256`. Also prevents `d == 0`.
// Placing the check here seems to give more optimal stack operations.
if iszero(gt(d, p1)) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
d := div(d, t) // Divide `d` by `t`, which is a power of two.
// Invert `d mod 2**256`
// Now that `d` is an odd number, it has an inverse
// modulo `2**256` such that `d * inv = 1 mod 2**256`.
// Compute the inverse by starting with a seed that is
// correct for four bits. That is, `d * inv = 1 mod 2**4`.
let inv := xor(2, mul(3, d))
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
z := mul(
// Divide [p1 p0] by the factors of two.
// Shift in bits from `p1` into `p0`. For this we need
// to flip `t` such that it is `2**256 / t`.
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
)
break
}
z := div(z, d)
break
}
}
}
/// @dev Calculates `floor(x * y / d)` with full precision.
/// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
/// Performs the full 512 bit calculation regardless.
function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z)))
let t := and(d, sub(0, d))
let r := mulmod(x, y, d)
d := div(d, t)
let inv := xor(2, mul(3, d))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
inv := mul(inv, sub(2, mul(d, inv)))
z := mul(
or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
mul(sub(2, mul(d, inv)), inv)
)
}
}
/// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
/// Throws if result overflows a uint256 or when `d` is zero.
/// Credit to Uniswap-v3-core under MIT license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
z = fullMulDiv(x, y, d);
/// @solidity memory-safe-assembly
assembly {
if mulmod(x, y, d) {
z := add(z, 1)
if iszero(z) {
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
/// Throws if result overflows a uint256.
/// Credit to Philogy under MIT license:
/// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Temporarily use `z` as `p0` to save gas.
z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
for {} 1 {} {
if iszero(or(iszero(x), eq(div(z, x), y))) {
let k := and(n, 0xff) // `n`, cleaned.
let mm := mulmod(x, y, not(0))
let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
// | p1 | z |
// Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 |
// Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 |
// Check that final `z` doesn't overflow by checking that p1_0 = 0.
if iszero(shr(k, p1)) {
z := add(shl(sub(256, k), p1), shr(k, z))
break
}
mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
revert(0x1c, 0x04)
}
z := shr(and(n, 0xff), z)
break
}
}
}
/// @dev Returns `floor(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := div(z, d)
}
}
/// @dev Returns `ceil(x * y / d)`.
/// Reverts if `x * y` overflows, or `d` is zero.
function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(x, y)
// Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
mstore(0x00, 0xad251c27) // `MulDivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(z, d))), div(z, d))
}
}
/// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
/// @solidity memory-safe-assembly
assembly {
let g := n
let r := mod(a, n)
for { let y := 1 } 1 {} {
let q := div(g, r)
let t := g
g := r
r := sub(t, mul(r, q))
let u := x
x := y
y := sub(u, mul(y, q))
if iszero(r) { break }
}
x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
}
}
/// @dev Returns `ceil(x / d)`.
/// Reverts if `d` is zero.
function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
if iszero(d) {
mstore(0x00, 0x65244e4e) // `DivFailed()`.
revert(0x1c, 0x04)
}
z := add(iszero(iszero(mod(x, d))), div(x, d))
}
}
/// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `max(0, x - y)`.
function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(gt(x, y), sub(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x + y)`.
function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(0, lt(add(x, y), x)), add(x, y))
}
}
/// @dev Returns `min(2 ** 256 - 1, x * y)`.
function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `condition ? x : y`, without branching.
function ternary(bool condition, address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), iszero(condition)))
}
}
/// @dev Returns `x != 0 ? x : y`, without branching.
function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != bytes32(0) ? x : y`, without branching.
function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(x)))
}
}
/// @dev Returns `x != address(0) ? x : y`, without branching.
function coalesce(address x, address y) internal pure returns (address z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, mul(y, iszero(shl(96, x))))
}
}
/// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
/// Reverts if the computation overflows.
function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
if x {
z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
let half := shr(1, b) // Divide `b` by 2.
// Divide `y` by 2 every iteration.
for { y := shr(1, y) } y { y := shr(1, y) } {
let xx := mul(x, x) // Store x squared.
let xxRound := add(xx, half) // Round to the nearest number.
// Revert if `xx + half` overflowed, or if `x ** 2` overflows.
if or(lt(xxRound, xx), shr(128, x)) {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
x := div(xxRound, b) // Set `x` to scaled `xxRound`.
// If `y` is odd:
if and(y, 1) {
let zx := mul(z, x) // Compute `z * x`.
let zxRound := add(zx, half) // Round to the nearest number.
// If `z * x` overflowed or `zx + half` overflowed:
if or(xor(div(zx, x), z), lt(zxRound, zx)) {
// Revert if `x` is non-zero.
if x {
mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
revert(0x1c, 0x04)
}
}
z := div(zxRound, b) // Return properly scaled `zxRound`.
}
}
}
}
}
/// @dev Returns the square root of `x`, rounded down.
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
// but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffffff, shr(r, x))))
z := shl(shr(1, r), z)
// Goal was to get `z*z*y` within a small factor of `x`. More iterations could
// get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
// We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
// That's not possible if `x < 256` but we can just verify those cases exhaustively.
// Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
// Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
// Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.
// For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
// is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
// with largest error when `s = 1` and when `s = 256` or `1/256`.
// Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
// Then we can estimate `sqrt(y)` using
// `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.
// There is no overflow risk here since `y < 2**136` after the first branch above.
z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If `x+1` is a perfect square, the Babylonian method cycles between
// `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
z := sub(z, lt(div(x, z), z))
}
}
/// @dev Returns the cube root of `x`, rounded down.
/// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
/// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// Makeshift lookup table to nudge the approximate log2 result.
z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
// Newton-Raphson's.
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
z := div(add(add(div(x, mul(z, z)), z), z), 3)
// Round down.
z := sub(z, lt(div(x, mul(z, z)), z))
}
}
/// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
function sqrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
z = (1 + sqrt(x)) * 10 ** 9;
z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
}
/// @solidity memory-safe-assembly
assembly {
z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
}
}
/// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
/// Formally verified by xuwinnie:
/// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
function cbrtWad(uint256 x) internal pure returns (uint256 z) {
unchecked {
if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
z = (1 + cbrt(x)) * 10 ** 12;
z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
}
/// @solidity memory-safe-assembly
assembly {
let p := x
for {} 1 {} {
if iszero(shr(229, p)) {
if iszero(shr(199, p)) {
p := mul(p, 100000000000000000) // 10 ** 17.
break
}
p := mul(p, 100000000) // 10 ** 8.
break
}
if iszero(shr(249, p)) { p := mul(p, 100) }
break
}
let t := mulmod(mul(z, z), z, p)
z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
}
}
/// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
if (x == y) return x;
uint256 p = rawMul(x, y);
if (y == rawDiv(p, x)) return sqrt(p);
for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
}
}
/// @dev Returns the factorial of `x`.
function factorial(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := 1
if iszero(lt(x, 58)) {
mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
revert(0x1c, 0x04)
}
for {} x { x := sub(x, 1) } { z := mul(z, x) }
}
}
/// @dev Returns the log2 of `x`.
/// Equivalent to computing the index of the most significant bit (MSB) of `x`.
/// Returns 0 if `x` is zero.
function log2(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(r, shl(3, lt(0xff, shr(r, x))))
// forgefmt: disable-next-item
r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
0x0706060506020504060203020504030106050205030304010505030400000000))
}
}
/// @dev Returns the log2 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log2Up(uint256 x) internal pure returns (uint256 r) {
r = log2(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(r, 1), x))
}
}
/// @dev Returns the log10 of `x`.
/// Returns 0 if `x` is zero.
function log10(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(x, 100000000000000000000000000000000000000)) {
x := div(x, 100000000000000000000000000000000000000)
r := 38
}
if iszero(lt(x, 100000000000000000000)) {
x := div(x, 100000000000000000000)
r := add(r, 20)
}
if iszero(lt(x, 10000000000)) {
x := div(x, 10000000000)
r := add(r, 10)
}
if iszero(lt(x, 100000)) {
x := div(x, 100000)
r := add(r, 5)
}
r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
}
}
/// @dev Returns the log10 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log10Up(uint256 x) internal pure returns (uint256 r) {
r = log10(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(exp(10, r), x))
}
}
/// @dev Returns the log256 of `x`.
/// Returns 0 if `x` is zero.
function log256(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
r := or(r, shl(4, lt(0xffff, shr(r, x))))
r := or(shr(3, r), lt(0xff, shr(r, x)))
}
}
/// @dev Returns the log256 of `x`, rounded up.
/// Returns 0 if `x` is zero.
function log256Up(uint256 x) internal pure returns (uint256 r) {
r = log256(x);
/// @solidity memory-safe-assembly
assembly {
r := add(r, lt(shl(shl(3, r), 1), x))
}
}
/// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
/// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
/// @solidity memory-safe-assembly
assembly {
mantissa := x
if mantissa {
if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
mantissa := div(mantissa, 1000000000000000000000000000000000)
exponent := 33
}
if iszero(mod(mantissa, 10000000000000000000)) {
mantissa := div(mantissa, 10000000000000000000)
exponent := add(exponent, 19)
}
if iszero(mod(mantissa, 1000000000000)) {
mantissa := div(mantissa, 1000000000000)
exponent := add(exponent, 12)
}
if iszero(mod(mantissa, 1000000)) {
mantissa := div(mantissa, 1000000)
exponent := add(exponent, 6)
}
if iszero(mod(mantissa, 10000)) {
mantissa := div(mantissa, 10000)
exponent := add(exponent, 4)
}
if iszero(mod(mantissa, 100)) {
mantissa := div(mantissa, 100)
exponent := add(exponent, 2)
}
if iszero(mod(mantissa, 10)) {
mantissa := div(mantissa, 10)
exponent := add(exponent, 1)
}
}
}
}
/// @dev Convenience function for packing `x` into a smaller number using `sci`.
/// The `mantissa` will be in bits [7..255] (the upper 249 bits).
/// The `exponent` will be in bits [0..6] (the lower 7 bits).
/// Use `SafeCastLib` to safely ensure that the `packed` number is small
/// enough to fit in the desired unsigned integer type:
/// ```
/// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
/// ```
function packSci(uint256 x) internal pure returns (uint256 packed) {
(x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
/// @solidity memory-safe-assembly
assembly {
if shr(249, x) {
mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
revert(0x1c, 0x04)
}
packed := or(shl(7, x), packed)
}
}
/// @dev Convenience function for unpacking a packed number from `packSci`.
function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
unchecked {
unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards zero.
function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = (x & y) + ((x ^ y) >> 1);
}
}
/// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
function avg(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
/// @dev Returns the absolute value of `x`.
function abs(int256 x) internal pure returns (uint256 z) {
unchecked {
z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
}
}
/// @dev Returns the absolute distance between `x` and `y`.
function dist(int256 x, int256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), lt(y, x)))
}
}
/// @dev Returns the minimum of `x` and `y`.
function min(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), slt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), gt(y, x)))
}
}
/// @dev Returns the maximum of `x` and `y`.
function max(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, y), sgt(y, x)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(uint256 x, uint256 minValue, uint256 maxValue)
internal
pure
returns (uint256 z)
{
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
}
}
/// @dev Returns `x`, bounded to `minValue` and `maxValue`.
function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
}
}
/// @dev Returns greatest common divisor of `x` and `y`.
function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
for { z := x } y {} {
let t := y
y := mod(z, y)
z := t
}
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begin == end`, returns `t <= begin ? a : b`.
function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
internal
pure
returns (uint256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
unchecked {
if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
return a - fullMulDiv(a - b, t - begin, end - begin);
}
}
/// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
/// with `t` clamped between `begin` and `end` (inclusive).
/// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
/// If `begin == end`, returns `t <= begin ? a : b`.
function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
internal
pure
returns (int256)
{
if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
if (t <= begin) return a;
if (t >= end) return b;
// forgefmt: disable-next-item
unchecked {
if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
uint256(t - begin), uint256(end - begin)));
return int256(uint256(a) - fullMulDiv(uint256(a - b),
uint256(t - begin), uint256(end - begin)));
}
}
/// @dev Returns if `x` is an even number. Some people may need this.
function isEven(uint256 x) internal pure returns (bool) {
return x & uint256(1) == uint256(0);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RAW NUMBER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x + y`, without checking for overflow.
function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x + y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x - y`, without checking for underflow.
function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x - y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x * y`, without checking for overflow.
function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
unchecked {
z = x * y;
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := div(x, y)
}
}
/// @dev Returns `x / y`, returning 0 if `y` is zero.
function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := sdiv(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mod(x, y)
}
}
/// @dev Returns `x % y`, returning 0 if `y` is zero.
function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
/// @solidity memory-safe-assembly
assembly {
z := smod(x, y)
}
}
/// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := addmod(x, y, d)
}
}
/// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := mulmod(x, y, d)
}
}
}
lib/solady/src/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
/// 9 bytes is large enough to avoid collisions with lower slots,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_REENTRANCY_GUARD_SLOT, address())
}
_;
/// @solidity memory-safe-assembly
assembly {
sstore(_REENTRANCY_GUARD_SLOT, codesize())
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
_;
}
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) {
revert(codesize(), codesize())
} // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) {
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
// If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount := mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` implements `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented := and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))
) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0x84, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
src/HardCore.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;
import {BadTerms} from "./HardErrors.sol";
/// @notice The weekly profit-fee steps and the bounds a deploy may set.
/// @dev `BPS` is the basis-point unit. `SET_SESSION_KEY` is the Derive action id, passed as `uint64`.
/// Neither is a deploy input. Before `FEE_RISE_AT` the rate is `FEE_BASE`.
/// That instant is 2026-12-08 14:00:00 UTC, one week after the sale opens on 2026-12-01 14:00 UTC
/// (ADR-0255). Each `FEE_PERIOD` from then adds `FEE_STEP`, and the rate stops at `FEE_CAP`.
library HardCore {
/// @dev 2026-12-08 14:00:00 UTC. The first week from the 2026-12-01 14:00 UTC sale start stays at `FEE_BASE`.
uint64 internal constant FEE_RISE_AT = 1_796_738_400;
uint64 internal constant FEE_PERIOD = 7 days;
uint16 internal constant FEE_BASE = 2_000;
uint16 internal constant FEE_STEP = 100;
uint16 internal constant FEE_CAP = 5_000;
uint256 internal constant BPS = 10_000;
uint64 internal constant TIMELOCK = 48 hours;
uint64 internal constant MIN_HUMAN = 1;
uint64 internal constant MAX_HUMAN = 1_000_000;
uint64 internal constant START_HUMAN = 1_000;
uint64 internal constant MIN_PERIOD = 86_400;
uint64 internal constant MAX_PERIOD = 7_776_000;
/// @dev Production length of the first deposit window, measured from the deploy block.
uint64 internal constant START_PERIOD = 432_000;
/// @dev Production trading epoch. The open epoch end does not move when the next one changes.
uint64 internal constant START_TRADING_PERIOD = 604_800;
/// @dev Largest Derive withdrawal fee `redeem` absorbs without an owner shortfall proposal, in
/// human units. `private/withdraw` caps the fee by the signed `max_fee_usd`; the docs sample signs 1.5.
uint64 internal constant WITHDRAW_FEE_HUMAN = 2;
/// @dev Longest owner-change timelock a deploy may fix. A larger value would make every proposal wait
/// too long to ever apply. Audit v2 LOW-3.
uint64 internal constant MAX_TIMELOCK = 30 days;
/// @dev Shortest owner-change and workflow timelock a deploy may fix. Zero let the pair rotate the CRE
/// workflow and act on it in one block (audit N-1, ADR-0252).
uint64 internal constant MIN_TIMELOCK = 1 hours;
/// @dev Wait from `beginRedemption` before `emergencyRedeem` may accept a shortfall above the Derive
/// withdrawal fee. Earlier, the pair could close the book before the capital arrived and leave it as
/// surplus for the next generation (audit N-1, ADR-0252). Not a deploy term, so no deploy can shorten it.
uint64 internal constant SHORTFALL_WAIT = 30 days;
/// @dev Derive `OnchainActionManager` action. Documented, not a scope code.
uint64 internal constant SET_SESSION_KEY = 51;
/// @dev SDK 3.0.25 `ProtocolScopeCode.Admin`. The vault refuses this code on a session key.
uint256 internal constant ADMIN_SCOPE = 0;
/// @notice Values fixed in the vault constructor. Later owner changes stay inside these bounds.
struct Terms {
uint64 feeRiseAt;
uint64 feePeriod;
uint16 feeBase;
uint16 feeStep;
uint16 feeCap;
uint64 timelock;
uint64 minHuman;
uint64 maxHuman;
uint64 startHuman;
uint64 minPeriod;
uint64 maxPeriod;
uint64 startPeriod;
uint64 startTradingPeriod;
uint64 withdrawFeeHuman;
}
function defaultTerms() internal pure returns (Terms memory terms) {
terms = Terms({
feeRiseAt: FEE_RISE_AT,
feePeriod: FEE_PERIOD,
feeBase: FEE_BASE,
feeStep: FEE_STEP,
feeCap: FEE_CAP,
timelock: TIMELOCK,
minHuman: MIN_HUMAN,
maxHuman: MAX_HUMAN,
startHuman: START_HUMAN,
minPeriod: MIN_PERIOD,
maxPeriod: MAX_PERIOD,
startPeriod: START_PERIOD,
startTradingPeriod: START_TRADING_PERIOD,
withdrawFeeHuman: WITHDRAW_FEE_HUMAN
});
}
/// @dev The timelock is between `MIN_TIMELOCK` and `MAX_TIMELOCK` (ADR-0252).
/// A zero period is invalid, because the window or the epoch would have no duration.
function validate(Terms memory terms) internal pure {
if (terms.feePeriod == 0 || terms.feeBase > terms.feeCap) revert BadTerms();
if (uint256(terms.feeBase) > BPS || uint256(terms.feeStep) > BPS || uint256(terms.feeCap) > BPS) {
revert BadTerms();
}
if (terms.minHuman == 0 || terms.minHuman > terms.maxHuman) revert BadTerms();
if (terms.startHuman < terms.minHuman || terms.startHuman > terms.maxHuman) revert BadTerms();
if (terms.minPeriod == 0 || terms.minPeriod > terms.maxPeriod) revert BadTerms();
if (terms.startTradingPeriod < terms.minPeriod || terms.startTradingPeriod > terms.maxPeriod) {
revert BadTerms();
}
if (terms.startPeriod == 0 || terms.timelock < MIN_TIMELOCK || terms.timelock > MAX_TIMELOCK) {
revert BadTerms();
}
if (terms.withdrawFeeHuman > terms.maxHuman) revert BadTerms();
}
/// @dev `block.timestamp + delay` must fit the `uint64` clocks the vault stores.
function readyAt(uint64 delay) internal view returns (uint64) {
uint256 ready = block.timestamp + uint256(delay);
if (ready > type(uint64).max) revert BadTerms();
// forge-lint: disable-next-line(unsafe-typecast)
return uint64(ready);
}
/// @dev Before `riseAt` the rate is `base`. At `riseAt`, and every `period` after it, the rate
/// gains one `step`. It never passes `cap`. A zero `step` stays at `base`.
function feeAt(uint256 timestamp, uint64 riseAt, uint64 period, uint16 base, uint16 step, uint16 cap)
internal
pure
returns (uint16)
{
if (step == 0 || timestamp < riseAt) return base;
uint256 steps = (timestamp - riseAt) / period;
uint256 raised = uint256(base) + uint256(step) * (steps + 1);
if (raised > cap) return cap;
// forge-lint: disable-next-line(unsafe-typecast)
return uint16(raised);
}
/// @dev The whole positive profit is taxable. Losses from earlier periods are not
/// recovered: `applyLoss` marks the capital down and the next positive profit pays the
/// wallet fee on that reduced capital. See ADR-0126 and invariant I27.
function splitProfit(uint256 gross, uint16 feeBps_) internal pure returns (uint256 net, uint256 fee) {
if (gross == 0) return (0, 0);
fee = gross * feeBps_ / BPS;
net = gross - fee;
}
}
src/HardErrors.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;
error ZeroAddress();
error AdminScope();
error ScopeNotAllowed();
error BadExpiry();
error ZeroAmount();
error BadTerms();
error BadMinimum();
error BadPeriod();
error Unauthorized();
error Paused();
error BelowMinimum();
error InsufficientPending();
error SweepRequired();
error WindowOpen();
error AlreadySwept();
error UnknownWindow();
error NothingToClaim();
error NoActiveSupply();
error NothingToDistribute();
error ProfitEpochOpen();
error ProfitEpochSettled();
error AlreadyRedeemed();
error RedemptionAlreadyPending();
error NoRedemptionPending();
error RedemptionMismatch();
error InsufficientSurplus();
error TimelockPending();
error NoProposal();
error ProposalMismatch();
error InvalidPayees();
error InvalidShares();
error ThirdPayeeTooLarge();
error TokenNotRecoverable();
error NotPending();
error LossTooLarge();
error UnpaidWipe();
error SettlementTooLarge();
error AmountTooLarge();
error MarkdownRoundsToZero();
error BadReport();
error ReportExpired();
error ReportReplay();
error ReportWrongChain();
error ReportMissing();
error WorkflowUnset();
error InvalidWorkflow();
error UnregisteredVault();
error UnexpectedSubaccount();
error ReportMismatch();
error AlreadySet();
/// @dev The Derive mailbox given to the vault constructor is one of the vault's own wired addresses (audit
/// finding 10). A zero mailbox still reverts `ZeroAddress`.
error BadSweepDestination();
/// @dev The custody token did not answer `balanceOf` (audit finding 10). Not an input amount of zero.
error BalanceUnreadable();
src/HardSettlementLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";
import {HardCore} from "./HardCore.sol";
import {
AdminScope,
BadExpiry,
MarkdownRoundsToZero,
ScopeNotAllowed,
UnexpectedSubaccount,
UnpaidWipe,
UnregisteredVault,
ZeroAddress
} from "./HardErrors.sol";
import {IOnchainActionManager} from "./interfaces/IOnchainActionManager.sol";
/// @dev The adapter reads that bind a vault session key to the attested subaccount.
interface ISubaccountRegistry {
function vaultRegistered(address vault) external view returns (bool);
function expectedSubaccount(address vault) external view returns (uint256);
}
/// @notice Book arithmetic for `HardDepositVault`, deployed once and linked. Every `public` function runs by
/// `DELEGATECALL` in the vault's storage context; the library holds no state and is not an upgrade path:
/// the linked address is fixed in the vault bytecode at deploy. See ADR-0163 and ADR-0171.
/// @dev Trading capital sits in pools, never in per-wallet rows, so no call loops over wallets. A pool has
/// an exact capital `cap`, a unit total `units`, a loss scale `scale`, and a profit index `acc`. A wallet
/// holds units; its capital is `units * scale / ONE` and its gross profit is `units * (acc - snapshot) / ONE`.
/// `settle` brings one account up to date lazily. Directional rounding keeps the book solvent: tracked
/// `units` round up, `feeWeight` rounds down, account units and account profit round down, and the
/// per-account fee rounds up, so the sum of what accounts can take never exceeds what a pool reserved.
library HardSettlementLib {
/// @dev Unit scale and profit-index precision.
uint256 internal constant ONE = 1e36;
/// @dev A markdown that would take a pool's scale below this reverts `MarkdownRoundsToZero`. A cumulative
/// loss deeper than a factor of 1e18 within one book generation goes through the whole-book wipe instead.
uint256 internal constant MIN_SCALE = 1e18;
/// @dev Longest session-key lifetime the vault registers. The Derive API caps a key at 90 days.
uint256 internal constant MAX_KEY_LIFETIME = 90 days;
/// @dev `feeWeight` is a lower bound of the sum of `feeBps * units` over the pool's accounts. `count` is
/// the number of lots that joined a fresh pool, used only for the rounding slack of its merge into main.
struct Pool {
uint256 cap;
uint256 units;
uint256 scale;
uint256 acc;
uint256 feeWeight;
uint256 count;
}
/// @dev Main pool state at the moment fresh pool `e` merged into it, at the open of epoch `e + 1`.
struct Merge {
uint256 scale;
uint256 acc;
/// @dev The `main` era the fresh pool merged into (REV3-C-01).
uint64 era;
}
/// @dev A book generation ends at a whole-book wipe or at `redeem`. `main` is the frozen main pool and
/// `lastEpoch` the fresh pool that had not merged. `principal` over `book` is every account's share of its
/// capital at the end; it is set by `redeem`.
struct Ended {
Pool main;
uint64 lastEpoch;
/// @dev The `main` era at the end of the generation.
uint64 mainEra;
bool redeemed;
uint256 principal;
uint256 book;
}
/// @dev `epoch` is the epoch the sweep of this window opened, zero when nothing moved. `feeWeight` is the
/// sum of `feeBps * amount` of the pending deposits and `count` the wallets holding one.
struct Window {
uint64 closesAt;
bool swept;
uint64 epoch;
uint256 stablePending;
uint256 feeWeight;
uint256 count;
}
/// @dev One account per wallet. Pending deposits sit in at most two windows: the stale one and the open
/// one. `reinvest` waits for the fold of round `reinvestRound`. Capital is `mainUnits` of the main pool of
/// generation `gen` plus `freshUnits` of the fresh pool of epoch `freshEpoch`, each with its index snapshot.
struct Account {
uint64 winA;
uint64 winB;
uint64 gen;
uint64 freshEpoch;
uint64 reinvestRound;
uint16 feeBps;
bool feeLocked;
bool feeCommitted;
/// @dev The `main` era of `mainUnits`. Units of a retired era are worth zero (REV3-C-01).
uint64 mainEra;
uint256 amtA;
uint256 amtB;
uint256 reinvest;
uint256 mainUnits;
uint256 mainAcc;
uint256 freshUnits;
uint256 freshAcc;
uint256 available;
uint256 staged;
uint256 redeemable;
}
/// @dev The settled figures of one account. `capital` is trading capital in the live book. `frozen` is
/// capital in a book marked to zero whose `redeem` has not run: it is the redemption weight.
struct AccountView {
uint256 capital;
uint256 frozen;
uint64 windowA;
uint256 amountA;
uint64 windowB;
uint256 amountB;
uint256 reinvest;
uint256 available;
uint256 staged;
uint256 redeemable;
uint16 feeBps;
bool feeLocked;
bool feeCommitted;
}
/// @dev `main` is the earlier cohort of the live generation `gen`. `fresh[freshEpoch]` is the capital that
/// joined at the open of the current epoch; zero means none in this generation. `unsettledProfit` is net
/// profit credited to pools that no account has settled yet. Reinvestment of the open round waits in
/// `reinvestTotal`; a closed round folded at `roundEpoch[r]`, or was released when that is zero.
struct Book {
Pool main;
uint64 gen;
uint64 freshEpoch;
uint64 round;
/// @dev Counts retirements of `main`: a gap loss of its whole capital ends its era (REV3-C-01).
uint64 mainEra;
uint256 unsettledProfit;
uint256 reinvestTotal;
uint256 reinvestWeight;
uint256 reinvestCount;
mapping(uint64 => Pool) fresh;
mapping(uint64 => Merge) merges;
mapping(uint64 => uint64) epochGen;
mapping(uint64 => Ended) ended;
mapping(uint64 => uint64) roundEpoch;
mapping(uint64 => Window) windows;
mapping(address => Account) accounts;
/// @dev The final profit index of each retired `main` era.
mapping(uint64 => uint256) eraAcc;
}
/// @dev Mirrors of the vault events so a delegatecall from the vault emits the identical logs.
event Settled(address indexed investor, uint256 profit);
event CompanyFeeDeferred(uint256 amount);
/// @dev Deliver the company fee to `companyFee` from the vault's balance (this runs by delegatecall in
/// the vault's context, so the stablecoin sees the vault as sender). A failure (a blocklisted
/// `companyFee`, a frozen stablecoin, an odd token) must never revert epoch settlement, so a non-reverting
/// low-level transfer is used and the undelivered amount is returned for the vault to hold until a later
/// `claimCompanyFee`. What was delivered is what left the vault, not what the token returned: return data
/// is never decoded, so a non-boolean word cannot revert, a "true" that moved nothing defers the fee, and a
/// "false" that moved the tokens is not paid twice (audit finding 6, ADR-0256). If the balance cannot be
/// read, the return data decides as in `SafeTransferLib`: no data or the word 1 is success. See ADR-0163.
function settleCompanyFee(address stable, address companyFee, uint256 feeTotal)
public
returns (uint256 deferred)
{
if (feeTotal == 0) return 0;
(bool readBefore, uint256 before) = _tryBalance(stable);
(bool ok, bytes memory ret) =
stable.call(abi.encodeWithSignature("transfer(address,uint256)", companyFee, feeTotal));
(bool readAfter, uint256 afterwards) = _tryBalance(stable);
uint256 delivered;
if (readBefore && readAfter) {
delivered = before > afterwards ? before - afterwards : 0;
} else if (ok && (ret.length == 0 || (ret.length >= 32 && uint256(bytes32(ret)) == 1))) {
delivered = feeTotal;
}
if (delivered >= feeTotal) return 0;
deferred = feeTotal - delivered;
emit CompanyFeeDeferred(deferred);
}
/// @dev The vault's `stable` balance by a low-level static call; `ok` is false when it cannot be read.
function _tryBalance(address stable) private view returns (bool ok, uint256 amount) {
bytes memory data;
(ok, data) = stable.staticcall(abi.encodeWithSignature("balanceOf(address)", address(this)));
if (!ok || data.length < 32) return (false, 0);
amount = uint256(bytes32(data));
}
/// @dev Forward a session-key registration to the Derive action manager. This runs by DELEGATECALL, so the
/// manager sees the vault as the caller, which is what the Derive owner check requires. Scope code 0 is
/// `admin` and is refused. An `expiry` of zero is the revoke call. The vault is `onlyOwner` and emits.
/// @dev Allowlist of protocol scope codes a vault session key may hold (SDK 3.0.25 `ProtocolScopeCode`,
/// OQ-035): 1 withdraw, 2 to 10 trading, 17 vault. Admin, transfers, child keys, and liquidation are refused.
/// The key expires within `MAX_KEY_LIFETIME`, and a key with scopes names its subaccounts explicitly.
function authorizeSessionKey(
address actionManager,
address pnlAdapter,
address sessionKey,
uint256 expiry,
uint256[] memory scopes,
uint256[] memory subaccounts
) public {
for (uint256 i = 0; i < scopes.length; ++i) {
uint256 code = scopes[i];
if (code == HardCore.ADMIN_SCOPE) revert AdminScope();
if (code > 10 && code != 17) revert ScopeNotAllowed();
}
if (expiry <= block.timestamp || expiry > block.timestamp + MAX_KEY_LIFETIME) revert BadExpiry();
if (scopes.length != 0) {
if (subaccounts.length == 0) revert ScopeNotAllowed();
// A key that can act may act only on the subaccount the CRE report attests, so no trade or withdrawal
// happens where the report cannot see it (audit 2 rev 2, NEW-L-02). This runs in the vault's context.
ISubaccountRegistry registry = ISubaccountRegistry(pnlAdapter);
if (!registry.vaultRegistered(address(this))) revert UnregisteredVault();
uint256 attested = registry.expectedSubaccount(address(this));
for (uint256 i = 0; i < subaccounts.length; ++i) {
if (subaccounts[i] != attested) revert UnexpectedSubaccount();
}
}
submitSessionKey(actionManager, sessionKey, expiry, scopes, subaccounts);
}
function submitSessionKey(
address actionManager,
address sessionKey,
uint256 expiry,
uint256[] memory scopes,
uint256[] memory subaccounts
) public {
if (sessionKey == address(0)) revert ZeroAddress();
bytes memory data = abi.encode(sessionKey, expiry, scopes, subaccounts);
IOnchainActionManager(actionManager).submit(HardCore.SET_SESSION_KEY, data);
}
/// @dev Bring one account up to date and store it. Returns the net profit moved to its available balance;
/// the vault adds it to `claimableTotal`. Swept deposits become fresh units, folded reinvestment too,
/// a fresh lot whose pool merged becomes main units, an ended generation pays its redemption share.
function settle(Book storage b, address investor) public returns (uint256 net) {
Account memory a;
(a, net) = _project(b, investor);
b.accounts[investor] = a;
if (net != 0) {
b.unsettledProfit -= net;
emit Settled(investor, net);
}
}
/// @dev The settled figures of one account, without writing.
function accountOf(Book storage b, address investor) public view returns (AccountView memory v) {
(Account memory a,) = _project(b, investor);
if (a.gen == b.gen) v.capital = _capitalOf(b, a, b.main);
else v.frozen = _capitalOf(b, a, b.ended[a.gen].main);
v.windowA = a.winA;
v.amountA = a.amtA;
v.windowB = a.winB;
v.amountB = a.amtB;
v.reinvest = a.reinvest;
v.available = a.available;
v.staged = a.staged;
v.redeemable = a.redeemable;
v.feeBps = a.feeBps;
v.feeLocked = a.feeLocked;
v.feeCommitted = a.feeCommitted;
}
/// @dev Open epoch `epoch`: the previous fresh pool merges into main and stores its merge snapshot, and a
/// new fresh pool holds the swept intake plus the reinvestment of the open round, which closes as folded.
/// The fresh pool starts at scale `ONE`, so a lot's units equal its amount.
function openEpoch(Book storage b, uint64 epoch, uint256 intake, uint256 intakeWeight, uint256 intakeCount)
public
{
uint64 prev = b.freshEpoch;
if (prev != 0) {
Pool storage f = b.fresh[prev];
Pool storage m = b.main;
b.merges[prev] = Merge(m.scale, m.acc, b.mainEra);
if (f.units != 0 && f.scale == m.scale) {
// Equal scales convert one to one, so the merge is exact.
m.cap += f.cap;
m.units += f.units;
m.feeWeight += f.feeWeight;
} else if (f.units != 0) {
m.cap += f.cap;
// An account converts `floor(u * f.scale / m.scale)`, so the tracked total rounds up.
m.units += FixedPointMathLib.fullMulDivUp(f.units, f.scale, m.scale);
// Each account loses less than one main unit to that floor, which is at most `BPS` of fee
// weight per lot. The tracked weight must stay a lower bound.
uint256 w = FixedPointMathLib.fullMulDiv(f.feeWeight, f.scale, m.scale);
uint256 slack = f.count * HardCore.BPS;
if (w > slack) m.feeWeight += w - slack;
}
}
uint256 folded = b.reinvestTotal;
uint256 cap = intake + folded;
Pool storage n = b.fresh[epoch];
n.cap = cap;
n.units = cap;
n.scale = ONE;
n.feeWeight = intakeWeight + b.reinvestWeight;
n.count = intakeCount + b.reinvestCount;
b.freshEpoch = epoch;
b.epochGen[epoch] = b.gen;
b.roundEpoch[b.round] = epoch;
b.round += 1;
b.reinvestTotal = 0;
b.reinvestWeight = 0;
b.reinvestCount = 0;
}
/// @dev Reinvestment of the open round goes back to available profit: the book it would join has ended.
/// Returns the amount for the vault to move from pending to claimable.
function releaseReinvest(Book storage b) public returns (uint256 released) {
released = b.reinvestTotal;
b.round += 1;
b.reinvestTotal = 0;
b.reinvestWeight = 0;
b.reinvestCount = 0;
}
/// @dev Credit `profit` to the live book. While lagging only main earns it; otherwise it is split by
/// capital. Returns what left surplus (`taken`) and the company fee inside it; the rest is reserved in
/// `unsettledProfit`. Truncation stays in surplus.
function credit(Book storage b, uint256 profit, bool lag) public returns (uint256 taken, uint256 fee) {
if (lag) (taken, fee) = _credit(b.main, profit);
else (taken, fee) = _creditSplit(b.main, b.fresh[b.freshEpoch], profit);
b.unsettledProfit += taken - fee;
}
/// @dev Credit `profit` to the frozen pools of ended generation `gen`, by their capital at the end. Used
/// by `redeem` of a book marked to zero: the weights are the capital at the wipe.
function creditEnded(Book storage b, uint64 gen, uint256 profit) public returns (uint256 taken, uint256 fee) {
Ended storage e = b.ended[gen];
(taken, fee) = _creditSplit(e.main, b.fresh[e.lastEpoch], profit);
b.unsettledProfit += taken - fee;
}
/// @dev Mark the live book down to `remain`, which is above zero. While lagging only main is marked down
/// and `remain` is main's new capital. Otherwise both pools shrink by `remain / book` and the division
/// remainder joins the larger pool's capital, so the book equals `remain` exactly.
function markdown(Book storage b, uint256 remain, bool lag) public {
Pool storage m = b.main;
if (lag) {
_scaleDown(m, remain, m.cap);
return;
}
Pool storage f = b.fresh[b.freshEpoch];
uint256 book = m.cap + f.cap;
_scaleDown(m, remain, book);
_scaleDownFresh(f, remain, book);
uint256 dust = remain - m.cap - f.cap;
if (dust != 0) {
if (m.cap >= f.cap) m.cap += dust;
else f.cap += dust;
}
}
/// @dev Mark down a gap loss. The earlier cohort (`main`) traded the gap, so it carries the loss first. A loss of
/// its whole capital retires `main`: its capital is zero, its era ends, and an empty pool takes its place, so no
/// scale is ever squeezed toward the floor (REV3-C-01). Only the excess reaches the fresh pool. Returns non-zero,
/// with nothing changed, when no newcomers would survive (no fresh pool, or a loss of the whole book): the vault
/// then wipes the whole book with its full capital as redemption weights (REV3-C-02).
function markGapLoss(Book storage b, uint256 loss) public returns (uint256 rest) {
Pool storage m = b.main;
uint256 cap = m.cap;
if (loss < cap) {
_scaleDown(m, cap - loss, cap);
return 0;
}
Pool storage f = b.fresh[b.freshEpoch];
rest = loss - cap;
if (f.cap == 0 || rest >= f.cap) return loss;
if (cap != 0 || m.units != 0) {
b.eraAcc[b.mainEra] = m.acc;
b.mainEra += 1;
delete b.main;
m.scale = ONE;
}
if (rest != 0) _scaleDownFresh(f, f.cap - rest, f.cap);
return 0;
}
/// @dev End the live generation: freeze main and the unmerged fresh pool, and start an empty book.
/// Returns the ended generation.
function endGen(Book storage b) public returns (uint64 gen) {
gen = b.gen;
Ended storage e = b.ended[gen];
e.main = b.main;
e.lastEpoch = b.freshEpoch;
e.mainEra = b.mainEra;
delete b.main;
b.main.scale = ONE;
b.freshEpoch = 0;
b.gen = gen + 1;
}
/// @dev Fix the redemption of ended generation `gen`: each account gets `capital * principal / book`.
function closeGen(Book storage b, uint64 gen, uint256 principal, uint256 book) public {
Ended storage e = b.ended[gen];
e.redeemed = true;
e.principal = principal;
e.book = book;
}
function _project(Book storage b, address investor) private view returns (Account memory a, uint256 net) {
a = b.accounts[investor];
// A reinvestment whose round closed by a release goes back to available profit.
if (a.reinvest != 0 && a.reinvestRound < b.round && b.roundEpoch[a.reinvestRound] == 0) {
a.available += a.reinvest;
a.reinvest = 0;
}
uint64 ea = _lotEpoch(b, a.winA, a.amtA);
uint64 eb = _lotEpoch(b, a.winB, a.amtB);
uint64 er = a.reinvest != 0 && a.reinvestRound < b.round ? b.roundEpoch[a.reinvestRound] : 0;
uint256 gross;
// Lots join in epoch order, so an older fresh lot merges before a newer one is added.
for (uint256 i; i < 3; ++i) {
uint64 e = _min(_min(ea, eb), er);
if (e == 0) break;
if (e == ea) {
gross += _join(b, a, e, a.amtA);
a.amtA = 0;
a.winA = 0;
a.feeCommitted = true;
ea = 0;
} else if (e == eb) {
gross += _join(b, a, e, a.amtB);
a.amtB = 0;
a.winB = 0;
a.feeCommitted = true;
eb = 0;
} else {
gross += _join(b, a, e, a.reinvest);
a.reinvest = 0;
er = 0;
}
}
gross += _sync(b, a, b.gen);
if (gross != 0) {
// The company fee was paid at the credit from a lower-bound weight; rounding the account's fee up
// keeps the sum of nets inside the pool's reserve.
uint256 fee = (gross * a.feeBps + HardCore.BPS - 1) / HardCore.BPS;
net = gross - fee;
a.available += net;
}
}
/// @dev Epoch a pending lot joined capital at, or zero while its window is unswept.
function _lotEpoch(Book storage b, uint64 windowId, uint256 amount) private view returns (uint64) {
if (amount == 0) return 0;
Window storage w = b.windows[windowId];
return w.swept ? w.epoch : 0;
}
/// @dev Add `amount` units to the account's fresh lot of epoch `e`. Every lot of an epoch joins at its
/// open, before any credit, so the lot starts at index zero. After the sync a remaining fresh lot is of
/// epoch `e` itself: an older one has merged, and a newer one cannot exist because lots join in epoch order.
function _join(Book storage b, Account memory a, uint64 e, uint256 amount) private view returns (uint256 gross) {
uint64 gen = b.epochGen[e];
gross = _sync(b, a, gen);
// A later generation opens epochs only after the wipe of the earlier one was redeemed.
if (a.gen != gen) revert UnpaidWipe();
if (a.freshUnits == 0) {
a.freshEpoch = e;
a.freshAcc = 0;
} else {
// The lot already held is synced to the pool index; the added units earn from zero.
gross += FixedPointMathLib.fullMulDiv(amount, b.fresh[e].acc, ONE);
}
a.freshUnits += amount;
}
/// @dev Move the account to generation `target`, paying the redemption share of every ended generation it
/// held capital in, and accrue its profit in the generation it reaches. An account with capital in a book
/// marked to zero stays there until that book is redeemed.
function _sync(Book storage b, Account memory a, uint64 target) private view returns (uint256 gross) {
while (a.gen < target) {
if (a.mainUnits == 0 && a.freshUnits == 0) {
a.gen = target;
a.mainAcc = 0;
break;
}
Ended storage e = b.ended[a.gen];
gross += _accrue(b, a, e.main, e.lastEpoch, e.mainEra);
if (!e.redeemed) return gross;
uint256 capital = _capitalOf(b, a, e.main);
a.redeemable += FixedPointMathLib.fullMulDiv(capital, e.principal, e.book);
a.mainUnits = 0;
a.mainAcc = 0;
a.freshUnits = 0;
a.freshAcc = 0;
a.freshEpoch = 0;
a.gen += 1;
}
if (a.gen == b.gen) {
gross += _accrue(b, a, b.main, b.freshEpoch, b.mainEra);
} else {
Ended storage e = b.ended[a.gen];
gross += _accrue(b, a, e.main, e.lastEpoch, e.mainEra);
}
}
/// @dev Accrue the account's profit in its generation, whose main pool is `m` and whose newest fresh
/// pool is `lastFresh`. A fresh lot of an older epoch merged into main at the next open: it accrues up to
/// the merge, converts at the merge scales, and continues on main from the merge snapshot. Main units of a
/// retired era earn up to that era's end and are then worth zero (REV3-C-01).
function _accrue(Book storage b, Account memory a, Pool storage m, uint64 lastFresh, uint64 era)
private
view
returns (uint256 gross)
{
if (a.freshUnits != 0) {
Pool storage f = b.fresh[a.freshEpoch];
gross = FixedPointMathLib.fullMulDiv(a.freshUnits, f.acc - a.freshAcc, ONE);
a.freshAcc = f.acc;
if (a.freshEpoch < lastFresh) {
Merge storage merge = b.merges[a.freshEpoch];
gross += _retireStale(b, a, merge.era);
uint256 converted = FixedPointMathLib.fullMulDiv(a.freshUnits, f.scale, merge.scale);
if (a.mainUnits == 0) {
a.mainAcc = merge.acc;
} else if (a.mainAcc < merge.acc) {
gross += FixedPointMathLib.fullMulDiv(a.mainUnits, merge.acc - a.mainAcc, ONE);
a.mainAcc = merge.acc;
}
// A lot that joined after the account's main units were synced past this merge catches up
// from the merge snapshot to theirs.
if (a.mainAcc > merge.acc) gross += FixedPointMathLib.fullMulDiv(converted, a.mainAcc - merge.acc, ONE);
a.mainUnits += converted;
a.mainEra = merge.era;
a.freshUnits = 0;
a.freshAcc = 0;
a.freshEpoch = 0;
}
}
gross += _retireStale(b, a, era);
if (a.mainUnits != 0) gross += FixedPointMathLib.fullMulDiv(a.mainUnits, m.acc - a.mainAcc, ONE);
a.mainAcc = m.acc;
a.mainEra = era;
}
/// @dev Main units of an era other than `era` belong to a retired `main`: pay their profit up to the era's final
/// index, then drop them. Their capital was lost in the gap loss that retired it.
function _retireStale(Book storage b, Account memory a, uint64 era) private view returns (uint256 gross) {
if (a.mainUnits == 0 || a.mainEra == era) return 0;
gross = FixedPointMathLib.fullMulDiv(a.mainUnits, b.eraAcc[a.mainEra] - a.mainAcc, ONE);
a.mainUnits = 0;
a.mainAcc = 0;
}
function _capitalOf(Book storage b, Account memory a, Pool storage m) private view returns (uint256 capital) {
capital = FixedPointMathLib.fullMulDiv(a.mainUnits, m.scale, ONE);
if (a.freshUnits != 0) {
capital += FixedPointMathLib.fullMulDiv(a.freshUnits, b.fresh[a.freshEpoch].scale, ONE);
}
}
function _creditSplit(Pool storage m, Pool storage f, uint256 profit) private returns (uint256 taken, uint256 fee) {
uint256 book = m.cap + f.cap;
if (profit == 0 || book == 0) return (0, 0);
uint256 qm = FixedPointMathLib.fullMulDiv(profit, m.cap, book);
(uint256 tm, uint256 fm) = _credit(m, qm);
(uint256 tf, uint256 ff) = _credit(f, profit - qm);
return (tm + tf, fm + ff);
}
/// @dev Raise the pool's index by `floor(q * ONE / units)`. `taken = ceil(d * units / ONE) <= q` covers
/// every account's gross because tracked units are an upper bound. The company fee uses the lower-bound
/// fee weight, so it never exceeds the fee the accounts are charged.
function _credit(Pool storage p, uint256 q) private returns (uint256 taken, uint256 fee) {
uint256 units = p.units;
if (q == 0 || units == 0 || p.cap == 0) return (0, 0);
uint256 d = FixedPointMathLib.fullMulDiv(q, ONE, units);
if (d == 0) return (0, 0);
p.acc += d;
taken = FixedPointMathLib.fullMulDivUp(d, units, ONE);
fee = FixedPointMathLib.fullMulDiv(d, p.feeWeight, ONE * HardCore.BPS);
}
/// @dev Scale a pool by `num / den`. Account capital `units * scale / ONE` rounds down, so the pool's
/// rounded-down capital still covers it.
function _scaleDown(Pool storage p, uint256 num, uint256 den) private {
if (p.cap == 0) return;
uint256 scale = FixedPointMathLib.fullMulDiv(p.scale, num, den);
if (scale < MIN_SCALE) revert MarkdownRoundsToZero();
// A pool that entered with capital must keep at least one unit of it. Rounding that capital to zero
// would freeze `units` and `scale` while every later markdown skips the pool.
uint256 nextCap = FixedPointMathLib.fullMulDiv(p.cap, num, den);
if (nextCap == 0) revert MarkdownRoundsToZero();
p.scale = scale;
p.cap = nextCap;
}
/// @dev Like `_scaleDown`, for the fresh pool of a whole-book markdown. A fresh pool whose marked-down
/// capital rounds to zero is worth less than one stable unit: it is zeroed (`cap = 0`, `scale = 0`) instead
/// of reverting, so a dust reinvest cannot block the markdown of the whole book. Its accounts then hold zero
/// capital, a merge into main converts their units to zero, and the lost sub-unit joins the larger pool
/// through the markdown `dust`. The main pool keeps the revert: a zero main scale would divide by zero at
/// the next merge.
function _scaleDownFresh(Pool storage p, uint256 num, uint256 den) private {
if (p.cap == 0) return;
if (FixedPointMathLib.fullMulDiv(p.cap, num, den) == 0) {
p.cap = 0;
p.scale = 0;
return;
}
_scaleDown(p, num, den);
}
function _min(uint64 x, uint64 y) private pure returns (uint64) {
if (x == 0) return y;
if (y == 0) return x;
return x < y ? x : y;
}
}
src/interfaces/IOnchainActionManager.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;
/// @notice Subset of Derive `OnchainActionManager` used by a contract owner.
/// The manager address is a constructor argument. This file does not name one.
/// @dev `actionType` is `uint64` on the deployed manager and in SDK 3.0.25.
/// The docs sample declares `uint256`. That selector is absent: the call
/// reverts with empty data. Do not widen this argument.
interface IOnchainActionManager {
function submit(uint64 actionType, bytes calldata data) external payable returns (uint256 actionId);
}
src/interfaces/IPnlReports.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;
/// @notice The settlement view of `HardPnlOracleAdapter` that the vault reads.
interface IPnlReports {
/// @notice Wait before a replacement workflow identity takes effect. The vault requires at least its own
/// timelock (ADR-0249).
function workflowTimelock() external view returns (uint64);
/// @notice The accepted epoch report of `vault` whose window starts at `windowStartMs`, or `accepted == false`.
/// A redemption report at that start reads as not accepted here.
function settlementReport(address vault, uint64 windowStartMs)
external
view
returns (bool accepted, uint64 profitEpoch, uint64 windowEndMs, int256 realizedPnl, uint64 expiresAt);
/// @notice The accepted redemption report of `vault` whose window starts at `windowStartMs`, or
/// `accepted == false`. `openPositions` and `remainingValue` describe the Derive subaccount when the DON read it.
function redemptionReport(address vault, uint64 windowStartMs)
external
view
returns (
bool accepted,
uint256 redemptionId,
uint64 profitEpoch,
uint64 windowEndMs,
int256 realizedPnl,
uint256 openPositions,
uint256 remainingValue,
uint64 expiresAt
);
}
/// @notice The vault state the adapter binds a report to.
interface IReportedVault {
function profitEpoch() external view returns (uint64);
function profitEpochOpen() external view returns (bool);
function attestedUntilMs() external view returns (uint64);
function epochEndsAt() external view returns (uint64);
function epochOpenedMs() external view returns (uint64);
function redemptionPending() external view returns (bool);
function pendingRedemptionId() external view returns (uint256);
function redemptionStartedAt() external view returns (uint64);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {
"src/HardSettlementLib.sol": {
"HardSettlementLib": "0x73Bc83C5b326e964FCFb2B75BD76EFa2410E515E"
}
},
"optimizer": {
"runs": 50,
"enabled": true
},
"evmVersion": "prague",
"remappings": [
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.