Проверенный контрактТочноеMIT
POLAccumulator
Адрес0x2a5f65f4c74b1e49e77ae9a57e20fbdb0ced11d2
- Баланс
0 ETH
- Транзакций
3
- Компилятор
solc 0.8.26
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.26+commit.8a97fa7a
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 25 263 417
- Транзакция создания
- 0x2ef38bce7d…7c4c5041cb
22 файла
- src/POLAccumulator.solглавный62,5 КБ
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3,1 КБ
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2,48 КБ
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4,45 КБ
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol193 Б
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol182 Б
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2,78 КБ
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 Б
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol13,31 КБ
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 Б
- lib/openzeppelin-contracts/contracts/utils/Panic.sol1,97 КБ
- lib/openzeppelin-contracts/contracts/utils/Pausable.sol2,71 КБ
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol4,77 КБ
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4,18 КБ
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 Б
- lib/openzeppelin-contracts/contracts/utils/math/Math.sol32,66 КБ
- lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34,94 КБ
- src/base/OwnableNoRenounce.sol16,15 КБ
- src/base/PauseGuardian.sol5,82 КБ
- src/base/TimelockAdmin.sol16,83 КБ
- src/lib/SequencerCheck.sol25,32 КБ
- src/lib/WETHFallbackLib.sol14,09 КБ
src/POLAccumulator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {OwnableNoRenounce} from "./base/OwnableNoRenounce.sol";
import {TimelockAdmin} from "./base/TimelockAdmin.sol";
import {PauseGuardian} from "./base/PauseGuardian.sol";
import {SequencerCheck} from "./lib/SequencerCheck.sol";
import {WETHFallbackLib} from "./lib/WETHFallbackLib.sol";
interface IUniswapV2Router {
function swapExactETHForTokens(
uint256 amountOutMin, address[] calldata path, address to, uint256 deadline
) external payable returns (uint256[] memory amounts);
function addLiquidityETH(
address token, uint256 amountTokenDesired, uint256 amountTokenMin,
uint256 amountETHMin, address to, uint256 deadline
) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);
// AUDIT M12: removeLiquidityETH for the harvest path.
function removeLiquidityETH(
address token, uint256 liquidity, uint256 amountTokenMin,
uint256 amountETHMin, address to, uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function WETH() external pure returns (address);
// R015: factory introspection for constructor pair validation
function factory() external view returns (address);
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address);
}
/// @dev R015: Minimal TegridyTWAP read interface — mirrors the surface used in TegridyLending (R003).
/// `consult` returns the time-weighted output for `amountIn` of `tokenIn` over `period`.
/// `getLatestObservation` lets us check staleness explicitly before relying on a TWAP read.
interface ITegridyTWAP {
/// @dev AUDIT R014 (oracle layer, Wave-014): cumulative slots widened uint224 → uint256
/// to mirror the TegridyTWAP storage layout. Adds `bypassed` flag downstream
/// consumers can read to detect a rebootstrap-window observation.
struct Observation {
uint32 timestamp;
bool bypassed;
uint256 price0Cumulative;
uint256 price1Cumulative;
}
function consult(address pair, address tokenIn, uint256 amountIn, uint256 period)
external view returns (uint256 amountOut);
function getLatestObservation(address pair) external view returns (Observation memory);
/// @notice PASS7-POL-02 FIX: timestamp of the most recent dormancy bypass for `pair`.
/// Mirror of the same accessor on TegridyLending's local interface
/// (TegridyLending.sol:69-72). Used to enforce the bypass-cooldown
/// gate in `_twapMinOut` / `_twapHarvestMinOut`.
function lastBypassUsed(address pair) external view returns (uint256);
}
/// @title POLAccumulator (Protocol-Owned Liquidity)
/// @notice Uses protocol revenue (ETH) to buy TOWELI and create permanent LP.
///
/// Flow:
/// 1. ETH fees are sent to this contract
/// 2. Owner calls accumulate() → swaps half the ETH for TOWELI
/// 3. Adds TOWELI + remaining ETH as Uniswap V2 liquidity
/// 4. LP tokens are held permanently — never withdrawn
///
/// Result: The protocol owns its own liquidity. Deeper pools,
/// less slippage, more volume, more fees. Self-reinforcing flywheel.
/// AUDIT FIX M-14: Added Pausable so accumulations can be halted during emergencies.
contract POLAccumulator is OwnableNoRenounce, ReentrancyGuard, Pausable, TimelockAdmin, PauseGuardian {
using SafeERC20 for IERC20;
// ─── Timelock Operation Keys ─────────────────────────────────────
bytes32 public constant ACCUMULATE_CAP_CHANGE = keccak256("ACCUMULATE_CAP_CHANGE");
bytes32 public constant SWEEP_ETH_CHANGE = keccak256("SWEEP_ETH_CHANGE");
/// @dev AUDIT M-P02: 48h-timelocked token sweep, symmetric with SWEEP_ETH_CHANGE.
bytes32 public constant SWEEP_TOKENS = keccak256("SWEEP_TOKENS");
bytes32 public constant TREASURY_CHANGE = keccak256("POL_TREASURY_CHANGE");
bytes32 public constant POL_HARVEST = keccak256("POL_HARVEST"); // AUDIT M12
/// @dev [M7] Timelock key for daily ETH cap adjustments.
bytes32 public constant DAILY_ETH_CAP_CHANGE = keccak256("DAILY_ETH_CAP_CHANGE");
// ─── State ────────────────────────────────────────────────────────
IERC20 public immutable toweli;
/// @notice AUDIT FIX D-POL-M1: snapshot the TOWELI quote unit at construction
/// (= 10**decimals()) instead of hardcoding 1e18 in the TWAP consult. Pre-fix
/// every twap.consult(_, toweli, 1e18, _) site implicitly assumed 18-decimal
/// TOWELI; if a future redeploy / migration ever points POL at a non-18 token,
/// twapEthPer1eToweli would be off by orders of magnitude and `fairToweli =
/// sqrt(K * 1e18 / P)` would mis-quote the per-leg minimum, either rejecting
/// every legitimate harvest or worse, accepting off-market harvests. Reading
/// once at construction keeps the immutable guarantee while removing the magic
/// number from the math.
uint256 public immutable toweliUnit;
IUniswapV2Router public immutable router;
address public immutable weth;
address public immutable lpToken; // LP pair address — cannot be swept
/// @notice R015: TWAP oracle used to derive minOut floors INSIDE accumulate()/executeHarvestLP().
/// Battle-tested Olympus / Tokemak treasury-ops pattern: caller-supplied minOut is no
/// longer trusted (was effectively 1 in tests, ~5 ETH/call MEV bleed). The TWAP is the
/// single source of truth for slippage protection — caller-supplied params now act as
/// additive belt-and-braces, never relaxing below the TWAP-derived floor.
ITegridyTWAP public immutable twap;
/// @notice R015: TWAP averaging window — 30 minutes matches Aave V3 / R003 lending oracle.
/// Long enough to dilute single-block reserve manipulation, short enough that a
/// legitimate same-day price move still drives accumulate() execution.
uint256 public constant TWAP_PERIOD = 30 minutes;
/// @notice R015: Defence-in-depth staleness gate — refuse to operate if the TWAP's latest
/// observation is older than this. The TWAP itself enforces the same bound inside
/// consult, but the typed error here is what monitoring keys off.
uint256 public constant TWAP_MAX_STALENESS = 2 hours;
/// @notice R015: TWAP-derived safety margin (50 bps = 0.5%). The internal minOut for both
/// the swap leg and the addLiquidity leg is `twapOut * (BPS - TWAP_SAFETY_BPS) / BPS`.
/// Caller cannot relax this floor; they can only tighten it via the existing minOut
/// params. This TWAP-anchored margin (plus the spot-vs-TWAP deviation gate in
/// `_assertSpotNearTWAP`) is the sole source of slippage protection — it is keyed
/// off TWAP not spot, so TWAP-vs-actual divergence is bounded by TWAP_PERIOD volatility.
uint256 public constant TWAP_SAFETY_BPS = 50;
/// @notice FRESH-EYES H-4: maximum allowed deviation between spot price and TWAP price
/// at the moment of `executeHarvestLP`. Was 200 bps (2%), narrowed to match
/// `TWAP_SAFETY_BPS` (50 bps) per AUDIT FIX MEDIUM-5: pre-fix, an attacker
/// pushing spot 1.99% off TWAP passed the deviation gate but extracted ~1.5%
/// per harvest because the per-leg safety margin was only 0.5%. Aligning the
/// two thresholds means deviation gate now requires reserves within the same
/// tolerance as the per-leg slippage floor, eliminating the bypass window.
/// The TWAP_PERIOD-window consult is ~30 minutes, so genuine volatility rarely
/// exceeds 0.5% within a 30-minute window in liquid pools; if the keeper trips
/// this gate during a stress event, it retries after the next observation.
/// Pattern of record: Compound v2 / Aave v2 oracle sanity checks.
uint256 public constant HARVEST_TWAP_DEVIATION_BPS = 50;
uint256 private constant BPS = 10_000;
uint256 public constant MAX_DEADLINE = 1 minutes; // R015: Tightened from 2m → 1m — narrows MEV sandwich window further; Flashbots inclusion target is the next block (~12s) so 1m is comfortably forgiving for private-mempool relays.
uint256 public maxAccumulateAmount = 10 ether;
uint256 public constant MAX_ACCUMULATE_CAP = 100 ether; // AUDIT FIX M-06: Hard upper bound to prevent draining pool reserves
uint256 public constant ACCUMULATE_CAP_CHANGE_DELAY = 24 hours;
uint256 public pendingMaxAccumulateAmount;
uint256 public constant TREASURY_CHANGE_DELAY = 48 hours;
address public pendingTreasury;
uint256 public totalETHUsed;
uint256 public lastAccumulateTime;
uint256 public constant ACCUMULATE_COOLDOWN = 1 hours;
/// @notice [M7] Fixed-window 24h ETH accumulation cap — rate-limiter pattern
/// (analog of Chainlink CCIP `RateLimiter.sol`; NOT Compound/Aave supplyCap,
/// which is an absolute supply ceiling rather than a per-window throughput limit).
/// Prevents a single compromise from draining the entire ETH balance in one day.
/// Default 50 ETH = 5 × maxAccumulateAmount (10 ETH/call × max 5 calls visible
/// in a 24h window given the 1h cooldown, with headroom for legitimate spikes).
/// Hard ceiling MAX_DAILY_ETH_CAP prevents accidental misconfiguration.
uint256 public dailyETHCap = 50 ether;
uint256 public dailyETHAccumulated; // ETH used in the current DAILY_WINDOW
uint256 public currentDayStart; // timestamp of the window that opened last
uint256 public pendingDailyETHCap;
uint256 public constant DAILY_WINDOW = 1 days;
uint256 public constant MAX_DAILY_ETH_CAP = 500 ether;
uint256 public constant DAILY_ETH_CAP_CHANGE_DELAY = 24 hours;
uint256 public totalLPCreated;
uint256 public totalAccumulations;
/// @notice AUDIT FIX (pass-8 batch-18): cumulative ETH ingress through
/// `receive()`. Combined with the ETHReceived event, gives
/// off-chain monitoring a clean signal to reconcile
/// `address(this).balance` against legitimate fee inflow vs.
/// "donated" / accidental ETH. Pre-fix, donated ETH could silently
/// inflate balance and slip into sweep / accumulate paths without
/// a trace.
uint256 public totalETHReceived;
// ─── Events ───────────────────────────────────────────────────────
event Accumulated(uint256 ethUsed, uint256 toweliAdded, uint256 lpCreated);
event ETHReceived(address indexed sender, uint256 amount);
event TreasuryChangeProposed(address indexed newTreasury, uint256 executeAfter);
event TreasuryChanged(address indexed oldTreasury, address indexed newTreasury);
event TreasuryChangeCancelled(address indexed cancelled);
// ─── Errors ───────────────────────────────────────────────────────
error InsufficientETH();
error DeadlineTooFar(); // SECURITY FIX: Deadline exceeds MAX_DEADLINE
error OracleStale(); // R015: TWAP latest observation older than TWAP_MAX_STALENESS
error LPMismatch(); // R015: lpToken != factory.getPair(toweli, weth)
/// @notice FRESH-EYES H-4: spot reserves deviate from TWAP price by more than
/// `HARVEST_TWAP_DEVIATION_BPS`. Indicates an in-flight sandwich (or genuine
/// volatility) — either way, refusing to harvest at distorted reserves
/// protects the LP's exit value. Keeper retries after the next observation.
error ReservesDeviateFromTWAP();
/// @notice AUDIT R014 H-6: TWAP observation pre-dates the most recent
/// sequencer resume (plus grace). Even when `checkSequencerUp`
/// passes, a TWAP read whose latest observation was recorded
/// BEFORE the sequencer's last `startedAt` reflects pre-outage
/// reserves and is unsafe to act on. Closes the post-resume
/// staleness gap where an attacker watching the outage queue
/// could extract value the moment the gate opened.
error OracleObservationPredatesResume();
error AccumulateCapTooLow();
/// @notice [M7] All dailyETHCap has been consumed in the current 24h window.
error DailyCapExceeded();
event MaxAccumulateAmountUpdated(uint256 oldAmount, uint256 newAmount);
event MaxAccumulateAmountChangeProposed(uint256 newAmount, uint256 executeAfter);
event MaxAccumulateAmountChangeCancelled(uint256 cancelledAmount);
event DailyETHCapUpdated(uint256 oldCap, uint256 newCap);
event DailyETHCapChangeProposed(uint256 newCap, uint256 executeAfter);
event DailyETHCapChangeCancelled(uint256 cancelledCap);
event DailyWindowReset(uint256 newWindowStart);
// ─── Constructor ──────────────────────────────────────────────────
address public treasury;
// ─── AUDIT R062: L2 Sequencer Uptime gating ──────────────────────
/// @notice Optional Chainlink L2 Sequencer Uptime feed. address(0) on
/// mainnet / non-L2 (no-op). Stored immutable so it cannot be
/// hot-swapped post-deploy.
address public immutable sequencerFeed;
/// @notice Post-resume grace window during which `accumulate()` and
/// `executeHarvestLP()` refuse to act. Pool reserves drift while
/// the sequencer is offline; running either operation immediately
/// after resume risks ETH at off-market prices. 1h matches Aave V3.
uint256 public constant SEQUENCER_GRACE_PERIOD = 1 hours;
/// @param _twap R015: TegridyTWAP oracle that gates accumulate()/executeHarvestLP() slippage.
/// REQUIRED — passing address(0) reverts. Must be bootstrapped
/// (>=2 observations, see TegridyTWAP.MIN_PERIOD) BEFORE the
/// first accumulate() call or that call reverts with
/// InsufficientObservations from inside consult().
/// @param _sequencerFeed R062: Chainlink L2 Sequencer Uptime feed; pass address(0)
/// for mainnet / non-L2 deployments (gating disabled).
constructor(
address _toweli,
address _router,
address _lpToken,
address _treasury,
address _twap,
address _sequencerFeed
)
OwnableNoRenounce(msg.sender)
{
require(_toweli != address(0), "ZERO_TOWELI");
require(_router != address(0), "ZERO_ROUTER");
require(_lpToken != address(0), "ZERO_LP_TOKEN");
require(_treasury != address(0), "ZERO_TREASURY");
require(_twap != address(0), "ZERO_TWAP"); // R015
toweli = IERC20(_toweli);
// AUDIT FIX D-POL-M1: snapshot the quote unit (10**decimals) once at
// construction. Reverts if the TOWELI implementation doesn't expose
// decimals() — preferable to a silent assumption of 18 decimals.
toweliUnit = 10 ** IERC20Metadata(_toweli).decimals();
router = IUniswapV2Router(_router);
weth = router.WETH();
// R015: Constructor-time validation — confirm `_lpToken` is the canonical V2 pair
// for (toweli, weth) reported by the router's factory. Defends against misdeploy
// (or a future attacker spoofing a fake "LP" address that the accumulator would
// happily lock funds into). Mirrors the Tokemak treasury-ops pattern of
// cross-checking pair addresses against the canonical factory at construction.
address fac = IUniswapV2Router(_router).factory();
address canonicalPair = IUniswapV2Factory(fac).getPair(_toweli, router.WETH());
if (canonicalPair == address(0) || canonicalPair != _lpToken) revert LPMismatch();
lpToken = _lpToken;
treasury = _treasury;
twap = ITegridyTWAP(_twap);
// R062: zero permitted (mainnet / non-L2 = gating disabled).
sequencerFeed = _sequencerFeed;
}
receive() external payable {
// AUDIT FIX (pass-8 batch-18): track cumulative ETH ingress so
// off-chain monitoring can reconcile `address(this).balance` against
// legitimate fee inflow vs. "donated" / accidental ETH. Pre-fix,
// unaccounted ETH could silently inflate balance and leak through
// sweep paths without trace; the counter gives an explicit lower-
// bound on legitimate fee inflow that the timelocked `sweepETH`
// path can be reconciled against off-chain.
totalETHReceived += msg.value;
emit ETHReceived(msg.sender, msg.value);
}
/// @notice Propose a new max accumulate amount (timelocked 24h)
function proposeMaxAccumulateAmount(uint256 _amount) external onlyOwner {
if (_amount < 0.01 ether) revert AccumulateCapTooLow();
require(_amount <= MAX_ACCUMULATE_CAP, "EXCEEDS_HARD_CAP"); // AUDIT FIX M-06: Enforce upper bound
pendingMaxAccumulateAmount = _amount;
_propose(ACCUMULATE_CAP_CHANGE, ACCUMULATE_CAP_CHANGE_DELAY);
emit MaxAccumulateAmountChangeProposed(_amount, _executeAfter[ACCUMULATE_CAP_CHANGE]);
}
/// @notice Execute the pending max accumulate amount change after timelock
function executeMaxAccumulateAmount() external onlyOwner {
_execute(ACCUMULATE_CAP_CHANGE);
uint256 old = maxAccumulateAmount;
maxAccumulateAmount = pendingMaxAccumulateAmount;
pendingMaxAccumulateAmount = 0;
emit MaxAccumulateAmountUpdated(old, maxAccumulateAmount);
}
/// @notice Cancel a pending max accumulate amount change
function cancelMaxAccumulateAmountChange() external onlyOwner {
uint256 cancelled = pendingMaxAccumulateAmount;
_cancel(ACCUMULATE_CAP_CHANGE);
pendingMaxAccumulateAmount = 0;
emit MaxAccumulateAmountChangeCancelled(cancelled);
}
/// @notice Legacy view helper for test compatibility
function maxAccumulateAmountProposedAt() external view returns (uint256) {
return _executeAfter[ACCUMULATE_CAP_CHANGE];
}
// ─── M7: Daily ETH cap governance ────────────────────────────────
/// @notice [M7] Propose a new rolling 24h ETH cap (timelocked 24h).
/// @param _cap New cap in wei; must be in [0.01 ether, MAX_DAILY_ETH_CAP].
function proposeDailyETHCap(uint256 _cap) external onlyOwner {
require(_cap >= 0.01 ether, "DAILY_CAP_TOO_LOW");
require(_cap <= MAX_DAILY_ETH_CAP, "EXCEEDS_DAILY_HARD_CAP");
pendingDailyETHCap = _cap;
_propose(DAILY_ETH_CAP_CHANGE, DAILY_ETH_CAP_CHANGE_DELAY);
emit DailyETHCapChangeProposed(_cap, _executeAfter[DAILY_ETH_CAP_CHANGE]);
}
/// @notice [M7] Execute a pending daily ETH cap change after the 24h timelock.
function executeDailyETHCap() external onlyOwner {
_execute(DAILY_ETH_CAP_CHANGE);
uint256 old = dailyETHCap;
dailyETHCap = pendingDailyETHCap;
pendingDailyETHCap = 0;
emit DailyETHCapUpdated(old, dailyETHCap);
}
/// @notice [M7] Cancel a pending daily ETH cap change.
function cancelDailyETHCap() external onlyOwner {
uint256 cancelled = pendingDailyETHCap;
_cancel(DAILY_ETH_CAP_CHANGE);
pendingDailyETHCap = 0;
emit DailyETHCapChangeCancelled(cancelled);
}
// ─── Core ─────────────────────────────────────────────────────────
/// @notice Use ETH balance to buy TOWELI and add permanent LP.
/// Splits ETH 50/50: half buys TOWELI, half pairs as ETH liquidity.
/// @dev R015 BATTLE-TESTED PATTERN (Olympus / Tokemak treasury ops):
/// Caller-supplied minOut params are NO LONGER trusted as the slippage source.
/// Instead, the swap minOut is derived INTERNALLY from `twap.consult()` with a
/// fixed `TWAP_SAFETY_BPS` margin (0.5%). The caller can still tighten this floor
/// via `_minTokens`, but NEVER relax below the TWAP floor. The TWAP itself is
/// gated by a hard staleness window (TWAP_MAX_STALENESS) so a paused/abandoned
/// oracle cannot be used to grant a sandwich attacker an arbitrarily low minOut.
/// This closes H-1 (caller-supplied minOut accepted as 1, ~5 ETH/call MEV) and
/// H-2 (LP-add floors anchored to the post-swap attacked spot).
/// @param _minTokens Optional CALLER tightening of the swap minOut. The internal TWAP
/// floor always wins — `_minTokens` only matters if it exceeds the floor.
/// @param _minLPTokens Optional CALLER tightening of the LP-add token min. Same semantics.
/// @param _minLPETH Optional CALLER tightening of the LP-add ETH min. Same semantics.
/// @param _deadline Transaction deadline (reverts if block.timestamp > _deadline).
function accumulate(uint256 _minTokens, uint256 _minLPTokens, uint256 _minLPETH, uint256 _deadline) external onlyOwner nonReentrant whenNotPaused {
// R062 (HIGH): refuse to accumulate when the L2 sequencer is currently
// down or has just resumed within SEQUENCER_GRACE_PERIOD. Pool reserves
// drift while the chain is offline, so swapping ETH→TOWELI the moment
// the chain wakes up risks executing at stale spot price.
// AUDIT FIX (BATCH-L3 M4): 4h staleness on price-sensitive path.
SequencerCheck.checkSequencerUp(sequencerFeed, SEQUENCER_GRACE_PERIOD, 4 hours);
// AUDIT FIX 2026-05-26 [M-14]: validate deadline BEFORE stamping cooldown.
// Pre-fix ordering (stamp then validate) was safe via Solidity tx-rollback,
// but a future refactor extracting the cooldown stamp could break the
// rollback assumption. Single-line move — same gas, clearer invariant.
require(_deadline >= block.timestamp, "EXPIRED");
if (_deadline > block.timestamp + MAX_DEADLINE) revert DeadlineTooFar();
require(block.timestamp >= lastAccumulateTime + ACCUMULATE_COOLDOWN, "ACCUMULATE_COOLDOWN");
// AUDIT FIX (2026-05-25 2nd pass): stamp the cooldown BEFORE the external swap/add
// (CEI), matching SwapFeeRouter's conversion-cooldown ordering. Defense-in-depth on
// top of nonReentrant; if the swap path reverts, the whole tx (incl. this) rolls back.
lastAccumulateTime = block.timestamp;
uint256 ethBalance = address(this).balance;
if (ethBalance < 0.01 ether) revert InsufficientETH();
if (ethBalance > maxAccumulateAmount) ethBalance = maxAccumulateAmount;
// [M7 FIX] Fixed-window 24h ETH cap — rate-limiter (CCIP RateLimiter analog).
// Resets the window counter on the first call after each 24h interval.
// Caps `ethBalance` to remaining daily allowance; reverts DailyCapExceeded
// if the window is already exhausted. Flash-loan proof: no loan survives 24h.
if (block.timestamp >= currentDayStart + DAILY_WINDOW) {
currentDayStart = block.timestamp;
dailyETHAccumulated = 0;
emit DailyWindowReset(block.timestamp);
}
// AUDIT FIX 2026-05-31 [LOW-2]: saturating subtraction. If the owner lowers
// `dailyETHCap` below the amount already consumed in the current window, the
// bare subtraction would underflow → Panic(0x11), bricking accumulate() until
// the 24h window rolls. Saturate to 0 so the typed DailyCapExceeded fires
// gracefully instead (rounds in the protocol's favour — caps harder, never less).
uint256 _dailyRemaining = dailyETHCap > dailyETHAccumulated ? dailyETHCap - dailyETHAccumulated : 0;
if (_dailyRemaining == 0) revert DailyCapExceeded();
if (ethBalance > _dailyRemaining) ethBalance = _dailyRemaining;
uint256 halfETH = ethBalance / 2;
// AUDIT FIX FRESH-2026: POL-ACCUMULATE-SPOT-TWAP-DEVIATION [HIGH] —
// fail-closed when spot has been pushed > HARVEST_TWAP_DEVIATION_BPS
// off TWAP at the moment of accumulate. Pre-fix only `_twapMinOut`'s
// TWAP-anchored MIN gated the swap leg, and a captured owner could
// bank the full TWAP_SAFETY_BPS budget on every sandwich. Mirrors
// the inline deviation gate already in `_twapHarvestMinOut`.
_assertSpotNearTWAP();
// R015: Derive TWAP-based swap floor BEFORE the swap. `twap.consult` returns the
// time-weighted TOWELI output for `halfETH` of WETH over TWAP_PERIOD. This is the
// single source of truth for swap-leg slippage protection — caller-supplied
// `_minTokens` can only TIGHTEN this floor, never relax it. Staleness is asserted
// via `getLatestObservation` first so a frozen oracle cannot grant a 0-min swap.
uint256 internalSwapMinOut = _twapMinOut(weth, halfETH);
uint256 swapMinOut = _minTokens > internalSwapMinOut ? _minTokens : internalSwapMinOut;
// Step 1: Buy TOWELI with half the ETH (with the TWAP-enforced floor).
address[] memory path = new address[](2);
path[0] = weth;
path[1] = address(toweli);
// SLITHER 2026-05-18: nonReentrant on entrypoint; CEI verified in audit
// slither-disable-next-line reentrancy-eth
uint256[] memory amounts = router.swapExactETHForTokens{value: halfETH}(
swapMinOut,
path,
address(this),
_deadline
);
uint256 toweliAmount = amounts[amounts.length - 1];
// Step 2: Approve exact amount for LP add (no infinite approval)
toweli.forceApprove(address(router), toweliAmount);
// R015: LP-add minimums are now anchored to the TWAP-implied 50/50 ratio, not to
// the post-swap attacked spot. We compute `twapImpliedToken = consult(weth → toweli, remainingETH)`
// and enforce a TWAP_SAFETY_BPS floor on it. This TWAP-derived floor (together with
// the spot-vs-TWAP deviation gate asserted above) is the sole slippage protection on
// the LP-add token leg; the caller-supplied `_minLPTokens` can only tighten it.
uint256 remainingETH = ethBalance - halfETH;
uint256 twapMinLPToken = _twapMinOut(weth, remainingETH);
// AUDIT FIX: DEEP-DR-M-08 — REMOVED `slippageMin*` and `backstopMin*` floors.
// They were derived from `toweliAmount` (the post-swap output, attacker-controlled
// under sandwich) so they offered no real protection — under sandwich, both
// toweliAmount AND the derived floors degrade together. The TWAP-anchored
// `twapMinLPToken` is the only attacker-independent floor and is now the sole
// source of truth for the LP-add token min. The caller-supplied `_minLPTokens`
// can still TIGHTEN the TWAP floor; it can never relax below it.
//
// ETH-min: caller-supplied only. `remainingETH` is ground truth (the ETH we are
// depositing) — we cannot be sandwiched out of ETH we own. No TWAP floor needed.
uint256 minToken = _minLPTokens;
if (twapMinLPToken > minToken) minToken = twapMinLPToken;
uint256 minETH = _minLPETH;
(uint256 tokenUsed, uint256 ethUsed, uint256 lpReceived) = router.addLiquidityETH{value: remainingETH}(
address(toweli),
toweliAmount,
minToken,
minETH,
address(this), // LP tokens stay in this contract forever
_deadline
);
require(lpReceived > 0, "ZERO_LP_MINTED"); // AUDIT FIX M-26: Validate LP return value
// A4-M-17: Revoke residual approval after addLiquidity to prevent leftover approval exploit
toweli.forceApprove(address(router), 0);
uint256 ethConsumed = halfETH + ethUsed;
totalETHUsed += ethConsumed;
dailyETHAccumulated += ethConsumed; // [M7] track against rolling 24h cap
totalLPCreated += lpReceived;
totalAccumulations++;
emit Accumulated(ethConsumed, tokenUsed, lpReceived);
}
// ─── Treasury Change (L-11) ────────────────────────────────────────
/// @notice L-11: Propose a treasury address change (48h timelock)
function proposeTreasuryChange(address _newTreasury) external onlyOwner {
require(_newTreasury != address(0), "ZERO_ADDRESS");
pendingTreasury = _newTreasury;
_propose(TREASURY_CHANGE, TREASURY_CHANGE_DELAY);
emit TreasuryChangeProposed(_newTreasury, _executeAfter[TREASURY_CHANGE]);
}
/// @notice Execute a previously proposed treasury change after the timelock
function executeTreasuryChange() external onlyOwner {
_execute(TREASURY_CHANGE);
address old = treasury;
treasury = pendingTreasury;
pendingTreasury = address(0);
emit TreasuryChanged(old, treasury);
}
/// @notice Cancel a pending treasury change
function cancelTreasuryChange() external onlyOwner {
_cancel(TREASURY_CHANGE);
emit TreasuryChangeCancelled(pendingTreasury);
pendingTreasury = address(0);
}
// ─── Pause ─────────────────────────────────────────────────────────
/// @notice AUDIT FIX M-14: Pause accumulations during emergencies
function pause() external onlyOwner { _pause(); }
function unpause() external onlyOwner { _unpause(); }
/// @notice mvp-launch Phase 0.4 — pause-only emergency guardian role.
/// See base/PauseGuardian.sol.
function setPauseGuardian(address _newGuardian) external onlyOwner {
_setPauseGuardian(_newGuardian);
}
function guardianPause() external onlyPauseGuardian { _pause(); }
// ─── Admin ─────────────────────────────────────────────────────────
// AUDIT FIX H-14: Timelock for sweepETH to prevent instant owner drain
uint256 public constant SWEEP_ETH_DELAY = 48 hours;
uint256 public sweepETHProposedAmount;
event SweepETHProposed(uint256 amount, uint256 readyAt);
event SweepETHExecuted(address indexed recipient, uint256 amount);
event SweepETHCancelled();
/// @notice Propose sweeping trapped ETH to treasury (timelocked 48h, amount locked at proposal)
function proposeSweepETH(uint256 _amount) external onlyOwner {
require(_amount > 0, "ZERO_AMOUNT");
sweepETHProposedAmount = _amount;
_propose(SWEEP_ETH_CHANGE, SWEEP_ETH_DELAY);
emit SweepETHProposed(_amount, _executeAfter[SWEEP_ETH_CHANGE]);
}
/// @notice Execute the pending ETH sweep after timelock (sends to treasury)
/// @dev AUDIT FIX: DEEP-DR-M-02 — `whenNotPaused` so the universal kill-switch
/// freezes owner-side mutators alongside accumulate (M-7 sibling-search).
function executeSweepETH() external onlyOwner nonReentrant whenNotPaused {
_execute(SWEEP_ETH_CHANGE);
uint256 amount = sweepETHProposedAmount;
uint256 balance = address(this).balance;
if (amount > balance) amount = balance;
require(amount > 0, "NO_ETH");
address recipient = treasury;
sweepETHProposedAmount = 0;
// AUDIT FIX (L6): route through WETHFallbackLib for parity with
// executeHarvestLP. If treasury is later rotated to a contract whose
// receive() reverts, the WETH-wrap fallback keeps this sweep from bricking
// (the raw .call + require(success) would have needed another 48h treasury
// rotation to recover).
WETHFallbackLib.safeTransferETHOrWrap(weth, recipient, amount);
emit SweepETHExecuted(recipient, amount);
}
/// @notice Cancel a pending ETH sweep
function cancelSweepETH() external onlyOwner {
_cancel(SWEEP_ETH_CHANGE);
sweepETHProposedAmount = 0;
emit SweepETHCancelled();
}
/// @notice Legacy view helper for test compatibility
function sweepETHReadyAt() external view returns (uint256) {
return _executeAfter[SWEEP_ETH_CHANGE];
}
/// @dev DEPRECATED: Use proposeSweepETH() + executeSweepETH()
function sweepETH() external pure {
revert("Use proposeSweepETH()");
}
// ─── AUDIT M12: POL Harvest ──────────────────────────────────────────
/// @notice Pull a fraction of accumulated POL liquidity back as TOWELI + ETH and forward
/// to treasury. Closes the "LP locked forever" silent killer where the protocol
/// deposited liquidity but had no way to realize fees from the position.
/// Strict 30-day timelock and a 10% per-call cap (relative to totalLPCreated)
/// prevent governance abuse / sudden liquidity removal that would crash the pair.
uint256 public constant POL_HARVEST_DELAY = 30 days;
uint256 public constant MAX_HARVEST_BPS = 1000; // 10% of totalLPCreated per harvest
uint256 public pendingHarvestLpAmount;
event POLHarvestProposed(uint256 lpAmount, uint256 readyAt);
event POLHarvestExecuted(uint256 lpAmount, uint256 tokenOut, uint256 ethOut);
event POLHarvestCancelled();
/// @notice Propose a harvest of `lpAmount` LP tokens from the protocol-owned position.
/// @param lpAmount LP tokens to remove (capped at MAX_HARVEST_BPS of totalLPCreated)
function proposeHarvestLP(uint256 lpAmount) external onlyOwner {
require(lpAmount > 0, "ZERO_LP");
require(totalLPCreated > 0, "NO_POL");
uint256 cap = (totalLPCreated * MAX_HARVEST_BPS) / 10000;
require(lpAmount <= cap, "EXCEEDS_HARVEST_CAP");
pendingHarvestLpAmount = lpAmount;
_propose(POL_HARVEST, POL_HARVEST_DELAY);
emit POLHarvestProposed(lpAmount, _executeAfter[POL_HARVEST]);
}
/// @notice Execute the pending POL harvest. Caller-supplied minimums are TIGHTENED
/// (never relaxed) by TWAP-derived floors, mirroring `accumulate()` (R015).
/// @dev R015 BATTLE-TESTED PATTERN (asymmetric → symmetric): Previously this path
/// accepted caller-supplied `minToken`/`minETH` with no floor — fully asymmetric
/// vs `accumulate()`. Now the same TWAP-derived floor (`_twapHarvestMinOut`,
/// plus the spot-vs-TWAP deviation gate inside it) is the sole slippage
/// protection and gates both legs; caller params can only tighten it.
/// Recovered TOWELI and ETH both go to treasury.
/// @dev AUDIT FIX: DEEP-DR-M-02 — `whenNotPaused` so the universal kill-switch
/// freezes owner-side mutators alongside accumulate (M-7 sibling-search).
function executeHarvestLP(uint256 minToken, uint256 minETH, uint256 deadline)
external onlyOwner nonReentrant whenNotPaused
{
// R062 (HIGH): refuse to harvest when the L2 sequencer is currently
// down or has just resumed within SEQUENCER_GRACE_PERIOD. Pool reserves
// drift while the chain is offline; running the harvest the moment the
// chain resumes risks burning LP at stale spot reserves.
// AUDIT FIX (BATCH-L3 M4): 4h staleness on price-sensitive path.
SequencerCheck.checkSequencerUp(sequencerFeed, SEQUENCER_GRACE_PERIOD, 4 hours);
_execute(POL_HARVEST);
uint256 lpAmount = pendingHarvestLpAmount;
pendingHarvestLpAmount = 0;
require(deadline >= block.timestamp, "EXPIRED");
if (deadline > block.timestamp + MAX_DEADLINE) revert DeadlineTooFar();
// R015: TWAP-derived per-leg floors. Compute the LP's share of pool reserves
// (lpAmount / lpTotalSupply * reserve_X), then enforce a TWAP-safety margin on
// each side. This makes the harvest sandwich-resistant in the same way the
// accumulate path is — an attacker pushing the pool ratio cannot trick us into
// accepting near-zero TOWELI or ETH on the burn. These TWAP-anchored floors
// (plus the spot-vs-TWAP deviation gate inside `_twapHarvestMinOut`) are the
// sole slippage protection on the burn; caller params can only tighten them.
(uint256 floorToken, uint256 floorETH) = _twapHarvestMinOut(lpAmount);
uint256 effMinToken = minToken > floorToken ? minToken : floorToken;
uint256 effMinETH = minETH > floorETH ? minETH : floorETH;
IERC20(lpToken).forceApprove(address(router), lpAmount);
uint256 ethBefore = address(this).balance;
(uint256 tokenOut, uint256 ethOut) = router.removeLiquidityETH(
address(toweli), lpAmount, effMinToken, effMinETH, address(this), deadline
);
IERC20(lpToken).forceApprove(address(router), 0);
// Sanity: confirm we actually received the ETH the router claims.
require(address(this).balance - ethBefore >= ethOut, "ETH_NOT_RECEIVED");
// Bookkeeping.
if (lpAmount <= totalLPCreated) {
totalLPCreated -= lpAmount;
} else {
totalLPCreated = 0;
}
// Forward ETH to treasury via WETH-fallback (matches sister contracts).
// AUDIT M-P01 (2026-04-29): replaced raw `treasury.call{value: ethOut}("")`
// with WETHFallbackLib.safeTransferETHOrWrap. The raw call had no gas cap
// and no fallback, so a treasury upgraded to a contract with a heavy
// `receive()` (or one that reverts on receive) would brick the entire
// harvest. The lib wraps to WETH and safeTransfers if the ETH path fails,
// matching the pattern already used in RevenueDistributor + ReferralSplitter
// + CommunityGrants + MemeBountyBoard.
if (ethOut > 0) {
WETHFallbackLib.safeTransferETHOrWrap(weth, treasury, ethOut);
}
if (tokenOut > 0) {
toweli.safeTransfer(treasury, tokenOut);
}
emit POLHarvestExecuted(lpAmount, tokenOut, ethOut);
}
function cancelHarvestLP() external onlyOwner {
_cancel(POL_HARVEST);
pendingHarvestLpAmount = 0;
emit POLHarvestCancelled();
}
function harvestLPReadyAt() external view returns (uint256) {
return _executeAfter[POL_HARVEST];
}
// ─── AUDIT M-P02: sweepTokens 48h timelock ─────────────────────────
/// @notice 48-hour delay matches SWEEP_ETH_DELAY for symmetry — both
/// protocol-owned-asset sweeps now share the same review window.
uint256 public constant SWEEP_TOKENS_DELAY = 48 hours;
/// @notice Token whose sweep is queued. address(0) when no proposal pending.
address public pendingSweepToken;
event SweepTokensProposed(address indexed token, uint256 readyAt);
event SweepTokensExecuted(address indexed token, address indexed recipient, uint256 amount);
event SweepTokensCancelled(address indexed token);
/// @notice AUDIT M-P02 (2026-04-29): Propose sweeping token dust to the
/// treasury after a 48h timelock. The token address is locked at
/// proposal time; the actual balance swept is read at execution.
/// Mirrors `proposeSweepETH` so both sister sweep paths share the
/// same review/cancel surface — closes the asymmetry where the ETH
/// sweep was timelocked but the token sweep was instant.
/// @param token Token contract whose balance will be swept on execute.
function proposeSweepTokens(address token) external onlyOwner {
// SECURITY FIX: Cannot sweep LP tokens — defeats permanent liquidity invariant.
// Reject at proposal time so the queue cannot stall on a doomed proposal.
require(token != lpToken, "CANNOT_SWEEP_LP");
require(token != address(0), "ZERO_TOKEN");
pendingSweepToken = token;
_propose(SWEEP_TOKENS, SWEEP_TOKENS_DELAY);
emit SweepTokensProposed(token, _executeAfter[SWEEP_TOKENS]);
}
/// @notice Execute a previously-proposed token sweep after the 48h
/// timelock has elapsed. Sweeps the FULL balance of the queued
/// token to `treasury`. Re-enforces the LP-token guard at the
/// executor in case `lpToken` were ever to change (it is
/// immutable today, but the defense-in-depth is cheap and matches
/// the OZ-style invariant chokepoint pattern used elsewhere).
/// @dev AUDIT FIX: DEEP-DR-M-02 — `whenNotPaused` so the universal kill-switch
/// freezes owner-side mutators alongside accumulate (M-7 sibling-search).
function executeSweepTokens() external onlyOwner nonReentrant whenNotPaused {
_execute(SWEEP_TOKENS);
address token = pendingSweepToken;
pendingSweepToken = address(0);
require(token != lpToken, "CANNOT_SWEEP_LP");
uint256 balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
IERC20(token).safeTransfer(treasury, balance); // AUDIT FIX L-08: Send to treasury, not owner()
}
emit SweepTokensExecuted(token, treasury, balance);
}
/// @notice Cancel a pending token sweep (e.g. wrong token queued, or the
/// dust amount has since been put to productive use).
function cancelSweepTokens() external onlyOwner {
_cancel(SWEEP_TOKENS);
address cancelled = pendingSweepToken;
pendingSweepToken = address(0);
emit SweepTokensCancelled(cancelled);
}
/// @notice View helper — timestamp at which the queued sweepTokens
/// becomes executable. 0 if no pending sweep.
function sweepTokensReadyAt() external view returns (uint256) {
return _executeAfter[SWEEP_TOKENS];
}
/// @dev DEPRECATED: instant token sweep replaced by the 48h-timelocked
/// `proposeSweepTokens` → `executeSweepTokens` flow above. Retained
/// as an explicit reverter so any pre-fix integrators surface a
/// typed error instead of silently invoking a no-op.
function sweepTokens(address) external pure {
revert("Use proposeSweepTokens()");
}
// ─── R015 helpers ────────────────────────────────────────────────
/// @notice TWAP-derived minOut for a swap leg. `twap.consult` returns the
/// time-weighted output amount over `TWAP_PERIOD`. We then apply a
/// `TWAP_SAFETY_BPS` (0.5%) margin so the floor is not so tight
/// that legitimate volatility within the window causes false
/// reverts. Staleness is asserted via `getLatestObservation`
/// BEFORE consulting so a paused/abandoned oracle cannot grant a
/// 0-min swap silently. Reverts `OracleStale` if the most recent
/// observation is older than `TWAP_MAX_STALENESS`.
/// @dev AUDIT R014 H-6: in addition to the wall-clock staleness gate,
/// we read the sequencer's resume timestamp and reject the TWAP
/// read if the latest observation pre-dates `resumeAt + grace`.
/// The standard `SequencerCheck.checkSequencerUp` at the entry of
/// accumulate() / executeHarvestLP() proves the sequencer is up
/// AND the grace window has elapsed, but it does NOT prove the
/// observation we are about to consume is itself post-resume —
/// a freshly-passed gate can still feed pre-outage reserves into
/// consult(). This second check closes that staleness gap.
/// `getResumeTimestamp` returns 0 on the no-feed mainnet path,
/// which makes the comparison a no-op (`resumeAt == 0` short-
/// circuits) and preserves mainnet semantics.
/// @dev AUDIT FIX FRESH-2026: POL-ACCUMULATE-SPOT-TWAP-DEVIATION [HIGH] —
/// assert spot reserves are within `HARVEST_TWAP_DEVIATION_BPS` of the
/// TWAP price. Mirrors the inline check in `_twapHarvestMinOut`
/// (lines 906-920) so accumulate is no longer the soft underbelly that
/// lets a captured-key owner sandwich-extract ~0.5% per call. Pre-fix,
/// the only on-chain gate was `_twapMinOut`'s TWAP-anchored MIN; a
/// manipulated spot that still cleared the MIN (output >= TWAP_min)
/// let the attacker bank the full TWAP_SAFETY_BPS budget every call.
/// With ACCUMULATE_COOLDOWN = 1h and maxAccumulateAmount = 10 ETH,
/// that compounded to ~876 ETH/yr in the worst case. The deviation
/// gate forces spot to track TWAP within 50 bps before each
/// accumulate, eliminating the sandwich-setup window. Same staleness
/// + post-resume + bypass-cooldown rails as `_twapMinOut`.
/// Pattern of record: Compound v2 / Aave v2 / RAI oracle sanity check.
function _assertSpotNearTWAP() internal view {
// Same staleness gate as `_twapMinOut` so the deviation check is meaningful.
ITegridyTWAP.Observation memory latest = twap.getLatestObservation(lpToken);
if (block.timestamp - latest.timestamp > TWAP_MAX_STALENESS) revert OracleStale();
uint256 resumeAt = SequencerCheck.getResumeTimestamp(sequencerFeed);
// AUDIT FIX (sentinel short-circuit): getResumeTimestamp returns
// type(uint256).max on a stale L2 feed; surface a typed OracleStale revert
// instead of letting `resumeAt + SEQUENCER_GRACE_PERIOD` overflow into a
// checked-math Panic(0x11). Matches TegridyTWAP's own short-circuit. No-op on
// mainnet (feed == address(0) → resumeAt == 0).
if (resumeAt == type(uint256).max) revert OracleStale();
if (resumeAt != 0 && uint256(latest.timestamp) < resumeAt + SEQUENCER_GRACE_PERIOD) {
revert OracleObservationPredatesResume();
}
uint256 lastBypass = twap.lastBypassUsed(lpToken);
if (lastBypass > block.timestamp) revert OracleStale();
if (lastBypass != 0 && block.timestamp - lastBypass < TWAP_PERIOD * 2) {
revert OracleStale();
}
// Snapshot reserves + token0 via staticcall (same pattern as
// `_twapHarvestMinOut` so we don't add new pair-interface imports).
(bool okR, bytes memory dataR) =
lpToken.staticcall(abi.encodeWithSignature("getReserves()"));
require(okR && dataR.length >= 96, "POOL_READ");
(uint112 r0, uint112 r1, ) = abi.decode(dataR, (uint112, uint112, uint32));
(bool okT0, bytes memory dataT0) =
lpToken.staticcall(abi.encodeWithSignature("token0()"));
require(okT0 && dataT0.length == 32, "POOL_READ");
address t0 = abi.decode(dataT0, (address));
uint256 toweliReserve;
uint256 ethReserve;
if (t0 == address(toweli)) {
(toweliReserve, ethReserve) = (uint256(r0), uint256(r1));
} else {
(toweliReserve, ethReserve) = (uint256(r1), uint256(r0));
}
if (toweliReserve == 0 || ethReserve == 0) revert OracleStale();
uint256 twapEthPer1eToweli = twap.consult(lpToken, address(toweli), toweliUnit, TWAP_PERIOD);
if (twapEthPer1eToweli == 0) revert OracleStale();
_assertSpotDeviationFromTWAP(toweliReserve, ethReserve, twapEthPer1eToweli);
}
/// @notice AUDIT FIX 2026-05-26 [M-15]: extracted the duplicated spot-vs-TWAP
/// deviation check (was inline in both `_assertSpotNearTWAP` and
/// `_twapHarvestMinOut`). Drift between the two copies was the M-15
/// finding's concern; one source of truth now.
function _assertSpotDeviationFromTWAP(
uint256 toweliReserve,
uint256 ethReserve,
uint256 twapEthPer1eToweli
) internal view {
uint256 spotEthPer1eToweli = (ethReserve * toweliUnit) / toweliReserve;
uint256 priceDelta = spotEthPer1eToweli > twapEthPer1eToweli
? spotEthPer1eToweli - twapEthPer1eToweli
: twapEthPer1eToweli - spotEthPer1eToweli;
if ((priceDelta * BPS) / twapEthPer1eToweli > HARVEST_TWAP_DEVIATION_BPS) {
revert ReservesDeviateFromTWAP();
}
}
function _twapMinOut(address tokenIn, uint256 amountIn) internal view returns (uint256) {
ITegridyTWAP.Observation memory latest = twap.getLatestObservation(lpToken);
if (block.timestamp - latest.timestamp > TWAP_MAX_STALENESS) revert OracleStale();
// R014 H-6: post-resume observation freshness. See dev-note above for the
// attack model. resumeAt == 0 → mainnet no-op (skip the comparison).
uint256 resumeAt = SequencerCheck.getResumeTimestamp(sequencerFeed);
// AUDIT FIX (sentinel short-circuit): getResumeTimestamp returns
// type(uint256).max on a stale L2 feed; surface a typed OracleStale revert
// instead of letting `resumeAt + SEQUENCER_GRACE_PERIOD` overflow into a
// checked-math Panic(0x11). Matches TegridyTWAP's own short-circuit. No-op on
// mainnet (feed == address(0) → resumeAt == 0).
if (resumeAt == type(uint256).max) revert OracleStale();
if (resumeAt != 0 && uint256(latest.timestamp) < resumeAt + SEQUENCER_GRACE_PERIOD) {
revert OracleObservationPredatesResume();
}
// PASS7-POL-02 FIX: mirror TegridyLending's bypass-cooldown defense
// (TegridyLending.sol:1255-1259). When the TWAP recently absorbed a
// bypassed observation (bootstrap or post-dormancy), refuse to consume
// any consult for `TWAP_PERIOD * 2` so a single un-gated reading cannot
// sole-source the harvest/accumulate floor. Pre-fix, POL had no
// equivalent gate and would consume any TWAP the moment count >= 2,
// composing with PASS7-TWAP-01 to enable up to 99.5% MEV bleed per
// call on the swap leg. Same typed revert as the staleness gate.
uint256 lastBypass = twap.lastBypassUsed(lpToken);
if (lastBypass > block.timestamp) revert OracleStale();
if (lastBypass != 0 && block.timestamp - lastBypass < TWAP_PERIOD * 2) {
revert OracleStale();
}
uint256 out = twap.consult(lpToken, tokenIn, amountIn, TWAP_PERIOD);
// Apply TWAP_SAFETY_BPS margin (out * (BPS - TWAP_SAFETY_BPS) / BPS).
return (out * (BPS - TWAP_SAFETY_BPS)) / BPS;
}
/// @notice TWAP-derived per-leg floors for `executeHarvestLP`. Computes
/// the LP's pro-rata share of TOWELI/ETH reserves, then applies
/// the same `TWAP_SAFETY_BPS` margin used on the swap leg. The
/// result is the minimum acceptable output on each side of
/// `removeLiquidityETH`. Caller-supplied `minToken` / `minETH`
/// can only TIGHTEN this floor.
/// @dev AUDIT R014 H-6: same post-resume staleness gate as `_twapMinOut`.
/// The harvest path reads pair reserves directly (not through the
/// TWAP), but the staleness gate on the latest observation is the
/// only on-chain proxy we have for "the chain has caught up since
/// resume" — without it, we would burn LP at reserves that were
/// set during the outage and have not yet been corrected by
/// post-resume arbitrage.
function _twapHarvestMinOut(uint256 lpAmount) internal view returns (uint256 floorToken, uint256 floorETH) {
// Staleness gate (mirrors `_twapMinOut`).
ITegridyTWAP.Observation memory latest = twap.getLatestObservation(lpToken);
if (block.timestamp - latest.timestamp > TWAP_MAX_STALENESS) revert OracleStale();
// R014 H-6: same post-resume freshness gate as `_twapMinOut`.
uint256 resumeAt = SequencerCheck.getResumeTimestamp(sequencerFeed);
// AUDIT FIX (sentinel short-circuit): getResumeTimestamp returns
// type(uint256).max on a stale L2 feed; surface a typed OracleStale revert
// instead of letting `resumeAt + SEQUENCER_GRACE_PERIOD` overflow into a
// checked-math Panic(0x11). Matches TegridyTWAP's own short-circuit. No-op on
// mainnet (feed == address(0) → resumeAt == 0).
if (resumeAt == type(uint256).max) revert OracleStale();
if (resumeAt != 0 && uint256(latest.timestamp) < resumeAt + SEQUENCER_GRACE_PERIOD) {
revert OracleObservationPredatesResume();
}
// PASS7-POL-02 FIX: same bypass-cooldown gate as `_twapMinOut`. Even
// though this path reads pair reserves directly (not through the TWAP
// consult), it relies on the latest observation as a proxy for "the
// chain has a non-bypassed price reference." Without this gate, an
// attacker who pre-stages a bypass observation can have the next
// executeHarvestLP burn LP at reserves that share the manipulated
// baseline.
uint256 lastBypass = twap.lastBypassUsed(lpToken);
if (lastBypass > block.timestamp) revert OracleStale();
if (lastBypass != 0 && block.timestamp - lastBypass < TWAP_PERIOD * 2) {
revert OracleStale();
}
// Pro-rata share = lpAmount / totalSupply * reserve_X. We read
// reserves through the standard V2 pair surface — `lpToken` is the
// pair contract.
uint256 totalSupply = IERC20(lpToken).totalSupply();
if (totalSupply == 0) return (0, 0);
// Snapshot reserves via the V2 pair's reserves slot. We don't import
// a full pair interface here — the staticcall pattern below avoids
// adding more imports for two reads.
(bool okR, bytes memory dataR) =
lpToken.staticcall(abi.encodeWithSignature("getReserves()"));
require(okR && dataR.length >= 96, "POOL_READ");
(uint112 r0, uint112 r1, ) = abi.decode(dataR, (uint112, uint112, uint32));
(bool okT0, bytes memory dataT0) =
lpToken.staticcall(abi.encodeWithSignature("token0()"));
require(okT0 && dataT0.length == 32, "POOL_READ");
address t0 = abi.decode(dataT0, (address));
uint256 toweliReserve;
uint256 ethReserve;
if (t0 == address(toweli)) {
(toweliReserve, ethReserve) = (uint256(r0), uint256(r1));
} else {
(toweliReserve, ethReserve) = (uint256(r1), uint256(r0));
}
if (toweliReserve == 0 || ethReserve == 0) revert OracleStale();
// FRESH-EYES H-4: derive per-side floors from TWAP-IMPLIED reserves rather than spot.
// The pre-fix code multiplied `lpAmount` by raw spot reserves; an attacker could push
// those reserves to a skewed ratio in the same block as harvest (sandwich) so the
// computed "fair" share collapsed on one leg.
//
// Battle-tested pattern: Alpha Homora V2 / RAI fair-LP-price oracle. The K = r0*r1
// invariant is preserved across swaps (it can only grow ~0.3%/swap from fees), so K
// is sandwich-resistant. The TWAP price gives us the un-manipulated ratio. From these
// two we reconstruct the fair per-side reserves at the TWAP price:
//
// K = r_toweli * r_eth (sandwich-invariant)
// P = TWAP price (eth-wei per 1e18 toweli) (sandwich-resistant via window)
// fair_r_toweli = sqrt(K * 1e18 / P)
// fair_r_eth = K / fair_r_toweli (= sqrt(K * P / 1e18) by symmetry)
//
// Defense-in-depth: also bound spot-vs-TWAP deviation. If spot has been pushed >2%
// off TWAP in the harvest tx, revert. Keeper retries after the next observation.
// AUDIT FIX D-POL-M1: use snapshot toweliUnit (10**decimals) instead of
// hardcoded 1e18. Both consult quote-in and spot quote-in must use the
// same unit so the deviation comparison and fairToweli math line up.
uint256 twapEthPer1eToweli = twap.consult(lpToken, address(toweli), toweliUnit, TWAP_PERIOD);
if (twapEthPer1eToweli == 0) revert OracleStale();
// AUDIT FIX 2026-05-26 [M-15]: shared helper — see `_assertSpotDeviationFromTWAP`.
_assertSpotDeviationFromTWAP(toweliReserve, ethReserve, twapEthPer1eToweli);
uint256 K = toweliReserve * ethReserve;
// AUDIT FIX D-POL-M1: use toweliUnit consistent with the consult quote.
// AUDIT FIX FRESH-2026 [M-POL-MULDIV-OVERFLOW]: route through
// Math.mulDiv (512-bit intermediate) so `K * toweliUnit` cannot trip
// the Solidity-0.8 checked-math overflow on high-decimal token
// redeploys. With uint112 reserves at theoretical max (~5.19e33)
// and toweliUnit at 18-decimal default (1e18), `K * toweliUnit`
// reaches ~2.7e85 — over uint256.max (~1.16e77). At realistic
// mainnet reserves this never trips, but a forward-compat redeploy
// to >18-decimal token + deep pool would silently DoS executeHarvestLP
// with Panic(0x11). Pattern matches Uniswap V3 FullMath usage in
// OracleLibrary consumers.
uint256 fairToweli = Math.sqrt(Math.mulDiv(K, toweliUnit, twapEthPer1eToweli));
if (fairToweli == 0) revert OracleStale();
// SLITHER 2026-05-18: precision/overflow tradeoff acceptable; combined-fraction form risks uint256 overflow on large inputs
// slither-disable-next-line divide-before-multiply
uint256 fairEth = K / fairToweli;
// SLITHER 2026-05-18: precision/overflow tradeoff acceptable; combined-fraction form risks uint256 overflow on large inputs
// slither-disable-next-line divide-before-multiply
uint256 shareToken = (lpAmount * fairToweli) / totalSupply;
// SLITHER 2026-05-18: precision/overflow tradeoff acceptable; combined-fraction form risks uint256 overflow on large inputs
// slither-disable-next-line divide-before-multiply
uint256 shareETH = (lpAmount * fairEth) / totalSupply;
// Apply safety margin.
floorToken = (shareToken * (BPS - TWAP_SAFETY_BPS)) / BPS;
floorETH = (shareETH * (BPS - TWAP_SAFETY_BPS)) / BPS;
}
// ─── View ─────────────────────────────────────────────────────────
/// @notice ETH available for next accumulation
/// @return The contract's current ETH balance
function pendingETH() external view returns (uint256) {
return address(this).balance;
}
// AUDIT FIX FRESH-2026 (post-fix scan7 DC-5): three legacy *_PROPOSAL_VALIDITY
// constants deleted — comment claimed "test compatibility" but no test
// referenced them; they were dead surface inflation.
/// @notice AUDIT FIX 2026-05-21 M19-PORT: override `acceptOwnership` so that any
/// pending proposals queued by the outgoing owner are CANCELLED on handoff.
/// Mirrors `TegridyLaunchpadV2.acceptOwnership` (TegridyLaunchpadV2.sol:426-438).
/// Without this override, an outgoing/compromised owner could queue hostile
/// proposals (e.g. `proposeTreasuryChange(attacker)`, `proposeSweepETH(attackerAmount)`)
/// immediately before `transferOwnership`; the timelock would silently keep
/// running and the new owner inherits an executable booby-trap.
/// @dev Calls `super.acceptOwnership()` first so the Ownable2Step pendingOwner→owner
/// promotion happens before the cancellations — typed events emit under the
/// NEW owner's authority for a clean audit trail.
function acceptOwnership() public override {
super.acceptOwnership();
if (_executeAfter[ACCUMULATE_CAP_CHANGE] != 0) {
uint256 cancelled = pendingMaxAccumulateAmount;
_cancel(ACCUMULATE_CAP_CHANGE);
pendingMaxAccumulateAmount = 0;
emit MaxAccumulateAmountChangeCancelled(cancelled);
}
if (_executeAfter[SWEEP_ETH_CHANGE] != 0) {
_cancel(SWEEP_ETH_CHANGE);
sweepETHProposedAmount = 0;
emit SweepETHCancelled();
}
if (_executeAfter[SWEEP_TOKENS] != 0) {
address cancelled = pendingSweepToken;
_cancel(SWEEP_TOKENS);
pendingSweepToken = address(0);
emit SweepTokensCancelled(cancelled);
}
if (_executeAfter[TREASURY_CHANGE] != 0) {
address cancelled = pendingTreasury;
_cancel(TREASURY_CHANGE);
pendingTreasury = address(0);
emit TreasuryChangeCancelled(cancelled);
}
if (_executeAfter[POL_HARVEST] != 0) {
_cancel(POL_HARVEST);
pendingHarvestLpAmount = 0;
emit POLHarvestCancelled();
}
}
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
* return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
* value: the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
* the return value is optional (but if data is returned, it must not be false).
*
* @param token The token targeted by the call.
* @param spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
* by the {ReentrancyGuardTransient} variant in v6.0.
*
* @custom:stateless
*/
abstract contract ReentrancyGuard {
using StorageSlot for bytes32;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
/**
* @dev A `view` only version of {nonReentrant}. Use to block view functions
* from being called, preventing reading from inconsistent contract state.
*
* CAUTION: This is a "view" modifier and does not change the reentrancy
* status. Use it only on view functions. For payable or non-payable functions,
* use the standard {nonReentrant} modifier instead.
*/
modifier nonReentrantView() {
_nonReentrantBeforeView();
_;
}
function _nonReentrantBeforeView() private view {
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
_nonReentrantBeforeView();
// Any calls to nonReentrant after this point will fail
_reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
}
function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
return REENTRANCY_GUARD_STORAGE;
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the 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.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory buffer) private pure returns (bool) {
uint256 chunk;
for (uint256 i = 0; i < buffer.length; i += 0x20) {
// See _unsafeReadBytesOffset from utils/Bytes.sol
assembly ("memory-safe") {
chunk := mload(add(add(buffer, 0x20), i))
}
if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev A uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
src/base/OwnableNoRenounce.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";
/// @title OwnableNoRenounce — Ownable2Step with renounceOwnership permanently disabled
/// @notice Universal best practice across all battle-tested DeFi protocols:
/// Convex, Aave, Curve gauges, and every Tegriddy contract disable renounceOwnership()
/// to prevent accidental admin bricking.
/// @dev Inherits OZ Ownable2Step (2-step transfer: propose → accept).
/// All 10 Tegriddy admin contracts previously overrode renounceOwnership individually.
/// This base contract eliminates that repetition.
abstract contract OwnableNoRenounce is Ownable2Step {
/// @dev AUDIT FIX: DEEP-LIB-M1 — typed error for the opt-in
/// contract-only owner enforcement. Children that opt in by
/// overriding `_ownerMustBeContract()` to return `true` will revert
/// with this error if a constructor or `_transferOwnership` call
/// passes an EOA. Defaults to NOT enforced so existing tests and
/// deploy scripts that pass `msg.sender` (an EOA) continue to work.
error OwnerNotContract(address proposed);
/// @dev FRESH-EYES L: typed error replacing the legacy `revert("RENOUNCE_DISABLED")`
/// string. Brings this revert in line with every other rejection in the file
/// (typed selectors), so off-chain alerts and Tenderly filters can subscribe by
/// 4-byte selector instead of fragile string parsing.
error RenounceDisabled();
/// @dev AUDIT FIX FRESH-2026: F-40-ONR-1 — typed error for the
/// pending-transfer expiry path. After `OWNERSHIP_TRANSFER_EXPIRY`
/// (14 days) elapses without `acceptOwnership`, the pending slot
/// auto-clears and any acceptance attempt reverts with this error.
error OwnershipTransferExpired();
/// @dev AUDIT FIX FRESH-2026: F-40-ONR-1 — caller of
/// `cancelOwnershipTransfer` must be the current owner.
error NoPendingOwnershipTransfer();
/// @dev AUDIT FIX FRESH-2026 [M-OWN-TRANSFER-ZERO-DESYNC]: reject zero in
/// `transferOwnership` so the OZ-zero "cancel" shortcut can't leave
/// `_pendingOwner == 0` + `expiry > 0` desynced. Use
/// `cancelOwnershipTransfer(reason)` as the canonical cancel path.
/// Distinct from child contracts' own `ZeroAddress` errors to avoid
/// inheritance-chain identifier collisions.
error PendingOwnerZeroAddress();
/// @notice AUDIT FIX FRESH-2026: F-40-ONR-1 — emitted when the owner
/// cancels a pending ownership transfer before acceptance.
event OwnershipTransferCancelled(address indexed previousPendingOwner, string reason);
/// @notice AUDIT FIX FRESH-2026: F-40-ONR-1 — pending-transfer expiry
/// window. After this period elapses without acceptance, the
/// pendingOwner slot is treated as auto-cleared. 14 days
/// matches the Compound Timelock GRACE_PERIOD pattern.
uint256 public constant OWNERSHIP_TRANSFER_EXPIRY = 14 days;
/// @notice AUDIT FIX FRESH-2026: F-40-ONR-1 — wall-clock at which the
/// current pending ownership transfer expires. Zero when no
/// pending transfer exists. Set on every successful
/// `transferOwnership(newOwner)` call AND cleared on
/// `acceptOwnership` / `cancelOwnershipTransfer`.
uint256 public ownershipTransferExpiresAt;
/// @dev AUDIT FIX: DEEP-LIB-M1 — opt-in flag (returned by the virtual
/// hook below). Children that need contract-only ownership
/// enforcement override this to return `true`. Default is `false`
/// to preserve compatibility with existing test suites and the
/// reference deploy scripts that bootstrap with an EOA owner that
/// is later 2-step-rotated to a multisig. Production-only contracts
/// that ALWAYS deploy behind a multisig can opt in.
function _ownerMustBeContract() internal view virtual returns (bool) {
return false;
}
constructor(address initialOwner) Ownable(initialOwner) {
// AUDIT FIX: V2-LIB-L5 — body checks dropped as unreachable.
// OZ's `Ownable(initialOwner)` constructor invokes
// `_transferOwnership(initialOwner)` BEFORE this body runs.
// Solidity's virtual dispatch routes that call through the
// `_transferOwnership` override below even during construction,
// so the contract-only enforcement (and the OZ-typed
// `OwnableInvalidOwner(0)` revert for `initialOwner == 0`) both
// fire BEFORE control reaches this body. A duplicate check here
// was structurally unreachable defense-in-depth — pure dead code.
// Single source of truth: the `_transferOwnership` override.
}
/// @notice Disabled. Cannot renounce ownership.
/// @dev AUDIT FIX: DEEP-LIB-L2 — declared `view` (was `pure`) so future
/// subclasses can override with state reads (e.g. emitting an
/// `OwnershipRenounceAttempted` telemetry event for compromised-key
/// detection). Behaviour is unchanged: every call still reverts.
/// @dev AUDIT FIX: V2-LIB-I1 — `onlyOwner` re-added to preserve OZ's
/// contract surface (the L2 `pure → view` migration accidentally
/// dropped the modifier). The function still reverts unconditionally,
/// so the access-control change has no exploitable consequence today
/// — but a future subclass that emits a telemetry event before the
/// revert would otherwise log for ANY caller (event-stream spam by
/// arbitrary actors). `onlyOwner` is `view`-compatible since
/// `_checkOwner` is itself `view`.
function renounceOwnership() public view override onlyOwner {
revert RenounceDisabled();
}
/// @dev AUDIT FIX: DEEP-LIB-M1 — re-applies the contract-only enforcement
/// on every ownership rotation when the subclass has opted in. A
/// compromised owner cannot then `transferOwnership(new_eoa)` then
/// `new_eoa.acceptOwnership()` to escape multisig containment.
/// OZ Ownable2Step calls `_transferOwnership` from `acceptOwnership`,
/// so this guard catches both initial transfer and rotation.
/// @dev AUDIT FIX: V2-LIB-L1 — removed the `newOwner != address(0)`
/// carve-out. The only path that ever reaches `_transferOwnership(0)`
/// is `Ownable.renounceOwnership()`, which our override above
/// reverts unconditionally — so the carve-out was unreachable dead
/// code AND its rationale comment ("OZ's `delete _pendingOwner`
/// isn't broken by our guard") was factually wrong: OZ's
/// `Ownable2Step._transferOwnership` runs `delete _pendingOwner`
/// UNCONDITIONALLY at the start, with no dependence on `newOwner`.
/// Removing the carve-out tightens the invariant: any future child
/// that adds a "soft-renounce" path which calls `_transferOwnership(0)`
/// directly will now correctly trip `OwnerNotContract` when the
/// subclass opts in to contract-only ownership.
function _transferOwnership(address newOwner) internal virtual override {
if (_ownerMustBeContract()) {
// AUDIT FIX (BATCH-H M29): EIP-7702 detection. Post-Pectra (live
// 2025-05-07), an EOA can delegate to code via `0xef0100 ‖ addr`,
// making `code.length == 23` (3-byte prefix + 20-byte address).
// Pre-fix, a 7702-EOA passed the `code.length > 0` check, silently
// defeating the multisig-only invariant the hook was meant to
// enforce. Now we additionally reject `code.length == 23` which is
// the 7702 delegation indicator length (genuine multisig contracts
// have non-23-byte runtime bytecode). This is the conservative-
// direction filter recommended by ERC-7702 §3. Length-only check
// avoids inline assembly + stack pressure — sufficient because no
// legitimate contract has exactly 23 bytes of runtime code.
uint256 codeLen = newOwner.code.length;
if (codeLen == 0 || codeLen == 23) revert OwnerNotContract(newOwner);
}
// AUDIT FIX FRESH-2026: F-40-ONR-1 — clear the pending-transfer
// expiry slot whenever ownership is finalized (initial set during
// construction OR `acceptOwnership` flow). The slot's invariant is
// "non-zero iff a pending transfer is awaiting acceptance"; on
// successful transition we collapse to zero.
ownershipTransferExpiresAt = 0;
super._transferOwnership(newOwner);
}
/// @notice AUDIT FIX FRESH-2026: F-40-ONR-1 — override
/// `transferOwnership` to stamp a 14-day expiry on the pending
/// slot. Without this, a malicious / misconfigured pendingOwner
/// (e.g. a contract whose `acceptOwnership` flow reverts) could
/// freeze the rotation surface indefinitely. After
/// `OWNERSHIP_TRANSFER_EXPIRY` elapses the pending slot is
/// treated as auto-cleared and `acceptOwnership` reverts with
/// `OwnershipTransferExpired()` — at which point the current
/// owner can `transferOwnership` to a different recipient
/// OR call `cancelOwnershipTransfer(reason)` to clear early.
/// @dev Calls super to preserve OZ Ownable2Step semantics
/// (`_pendingOwner = newOwner`, `OwnershipTransferStarted`).
function transferOwnership(address newOwner) public virtual override onlyOwner {
// AUDIT FIX FRESH-2026 [M-OWN-TRANSFER-ZERO-DESYNC]: reject the
// `transferOwnership(0)` "cancel via OZ semantics" path. OZ
// Ownable2Step documents `newOwner = address(0)` as the cancel
// primitive, but our override unconditionally stamps
// `ownershipTransferExpiresAt = now + 14d` regardless of newOwner.
// Post-cancel the state pair `_pendingOwner == 0 + expiry > 0` is
// inconsistent: `acceptOwnership` reverts on OZ pending-owner check
// (correct), but `pokeOwnershipExpiryWarning` would emit
// `OwnershipTransferExpiringIn(address(0), remaining)` during the
// final 24h window — polluting indexers / on-chain alerting with
// malformed pendingOwner == 0 events. The new
// `cancelOwnershipTransfer` is the canonical cancel path; reject the
// OZ-zero shortcut for clarity. ZeroAddress mirrors the existing
// typed-error pattern.
if (newOwner == address(0)) revert PendingOwnerZeroAddress();
super.transferOwnership(newOwner);
ownershipTransferExpiresAt = block.timestamp + OWNERSHIP_TRANSFER_EXPIRY;
}
/// @notice AUDIT FIX FRESH-2026: F-40-ONR-1 — override
/// `acceptOwnership` so the expiry guard fires before OZ's
/// pending-owner check.
/// @dev The current owner can pre-empt the expiry by calling
/// `cancelOwnershipTransfer(reason)` first; pendingOwner can
/// simply re-trigger by asking the owner to `transferOwnership`
/// again with a fresh window.
function acceptOwnership() public virtual override {
// Mirror OZ Ownable2Step.acceptOwnership() msg.sender == pendingOwner
// gate ordering: expiry comes first so an expired-but-still-set
// pending slot reverts with the typed `OwnershipTransferExpired`
// (more diagnostic) rather than `OwnableUnauthorizedAccount`.
uint256 expiry = ownershipTransferExpiresAt;
if (expiry != 0 && block.timestamp > expiry) {
revert OwnershipTransferExpired();
}
super.acceptOwnership();
}
/// @notice AUDIT FIX FRESH-2026: F-40-ONR-1 — current owner can
/// cancel a pending ownership transfer before the
/// pendingOwner accepts. Closes the bricked-rotation primitive
/// where a malicious / misconfigured pendingOwner could freeze
/// the rotation surface (OZ Ownable2Step has no native cancel
/// path — relies on the owner re-calling `transferOwnership` to
/// a different recipient, which may not be possible if the
/// pendingOwner is in a state where their reverts are
/// consuming gas before the new transfer lands).
/// @param reason Free-form string for off-chain audit trail; emitted
/// in the `OwnershipTransferCancelled` event.
function cancelOwnershipTransfer(string calldata reason) external virtual onlyOwner {
address prev = pendingOwner();
if (prev == address(0)) revert NoPendingOwnershipTransfer();
// Use OZ's internal API to clear the pending slot. Ownable2Step's
// `_transferOwnership` deletes `_pendingOwner` unconditionally at
// its head, so the safe way to "cancel" without rotating to a new
// owner is to call `_transferOwnership(owner())` — same owner,
// pendingOwner cleared as a side-effect. The `OwnershipTransferred`
// event will fire with identical previous/new params; the
// `OwnershipTransferCancelled` event below carries the diagnostic
// breadcrumb (the cancelled pendingOwner address + reason).
_transferOwnership(owner());
// Note: `_transferOwnership` zeros `ownershipTransferExpiresAt` via
// the override above, so the expiry slot is implicitly cleared.
// We emit the cancellation event AFTER the clear for canonical
// ordering (state → event).
emit OwnershipTransferCancelled(prev, reason);
}
/// @notice AUDIT FIX 2026-05-26 [M-20]: too-early-to-warn typed revert.
error PokeTooEarly();
/// @notice [L1] Poke called before the global cooldown window has elapsed.
error PokeRateLimited();
/// @notice AUDIT FIX 2026-05-26 [M-20]: poke event for off-chain monitors.
event OwnershipTransferExpiringIn(address indexed pendingOwner, uint256 secondsRemaining);
/// @notice [L1] Global cooldown between successive poke events — 1 hour.
/// Prevents spammers from flooding indexers / alert queues at zero cost.
/// Pattern: Compound TimelockController rate-limited notification surface.
uint256 public constant POKE_COOLDOWN = 1 hours;
/// @notice Timestamp of the most recent successful poke (0 = never poked).
uint256 public lastPokeTime;
/// @notice AUDIT FIX 2026-05-26 [M-20]: permissionless poke for off-chain
/// alerting on impending 14-day expiry. Fires only in the last
/// 24h of the window; allows monitors to subscribe to a single
/// event rather than poll `ownershipTransferExpiresAt` per-contract.
/// Pattern reference: Compound TimelockController surface for queue
/// visibility. [L1] Rate-limited to POKE_COOLDOWN (1 h) to prevent
/// event-log spam from permissionless callers.
function pokeOwnershipExpiryWarning() external {
uint256 expiry = ownershipTransferExpiresAt;
// AUDIT 2026-05-31 [slither incorrect-equality FP]: zero-sentinel check — `0`
// means no pending transfer. Standard sentinel pattern.
// slither-disable-next-line incorrect-equality
if (expiry == 0) revert NoPendingOwnershipTransfer();
if (block.timestamp >= expiry) revert OwnershipTransferExpired();
uint256 remaining = expiry - block.timestamp;
if (remaining > 1 days) revert PokeTooEarly();
// [L1] Rate-limit: one event per POKE_COOLDOWN regardless of caller.
if (block.timestamp < lastPokeTime + POKE_COOLDOWN) revert PokeRateLimited();
lastPokeTime = block.timestamp;
emit OwnershipTransferExpiringIn(pendingOwner(), remaining);
}
}
src/base/PauseGuardian.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title PauseGuardian — additive emergency-pause role distinct from owner
/// @notice Inspired by Aave V3's 5-of-9 Emergency Guardian and Lido's GateSeal.
/// The protocol owner (cold 4-of-7 multisig) holds Ownable role and can
/// pause AND unpause. The pause guardian (hot 3-of-5 multisig) can ONLY
/// pause — never unpause, never withdraw, never upgrade.
///
/// Threat model rationale:
/// - Cold owner multisig is slow on purpose: 4-of-7 cold-key signers
/// cannot react to an exploit-in-progress in time.
/// - Hot guardian is fast on purpose: 3-of-5 hot signers can pause in
/// minutes. Smaller blast radius if compromised (pause is recoverable
/// via owner's unpause; no funds at risk from the guardian alone).
/// - Owner is intentionally the strict superset of guardian's authority
/// so a compromised guardian can be re-set by the owner without an
/// upgrade.
///
/// Operational requirement: at deploy time, the guardian address MUST be
/// a multisig with a DISJOINT signer set from the owner multisig and the
/// treasury multisig. DeployMVP.s.sol asserts this address-level diversity
/// via the TREASURY / MULTISIG / PAUSE_GUARDIAN env-var disjoint check.
///
/// Pattern reference: Aave V3 EMERGENCY_ADMIN_ROLE (AccessControl.grantRole),
/// Lido GateSeal (limited-duration pause authority), MakerDAO ESM.
///
/// @dev Mixin design: this contract carries the pauseGuardian state and the
/// `onlyPauseGuardian` modifier ONLY. It does not interact with OZ
/// Pausable directly — each consumer wires `guardianPause()` to its own
/// `_pause()` override. This keeps the change purely additive: existing
/// `pause()`/`unpause()` ownership semantics are untouched, the consumer
/// simply gains a second public entry-point that the guardian can call.
///
/// @dev Owner can rotate the guardian instantly. The rationale is that if a
/// guardian's hot keys are compromised, the owner needs to be able to
/// react faster than any timelock would allow. The owner's own
/// rotation (acceptOwnership) is timelocked via OwnableNoRenounce, so
/// this asymmetry is intentional: guardian is faster to rotate than
/// owner. Compromising the guardian alone yields only nuisance-pause
/// risk (recoverable via owner.unpause), so a fast rotation is the
/// correct trade.
abstract contract PauseGuardian {
/// @notice The pause-only emergency multisig. address(0) before deploy-time
/// wiring. Setter is owner-gated in each consumer contract.
address public pauseGuardian;
event PauseGuardianSet(address indexed oldGuardian, address indexed newGuardian);
error NotPauseGuardian();
error ZeroPauseGuardian();
error PauseGuardianUnchanged();
/// @dev Internal setter. Consumers expose an external `setPauseGuardian`
/// gated by their own `onlyOwner` modifier (cannot be defined here
/// because Ownable lives in the consumer's inheritance chain via
/// OwnableNoRenounce, which we deliberately do NOT depend on so the
/// lib stays usable by non-OZ contracts).
function _setPauseGuardian(address _newGuardian) internal {
if (_newGuardian == address(0)) revert ZeroPauseGuardian();
address old = pauseGuardian;
if (old == _newGuardian) revert PauseGuardianUnchanged();
pauseGuardian = _newGuardian;
emit PauseGuardianSet(old, _newGuardian);
}
/// @notice AUDIT FIX 2026-05-26 [M-21]: documentation for the joint-failure
/// risk and the operational mitigation. The Lido GateSeal pattern
/// (auto-unpause after N days) would require each consumer to
/// implement consumer-specific `forceUnpause`, since the actual
/// pause state lives in each consumer's OZ Pausable storage — not
/// in this mixin. This change is intentionally documentation-only:
/// adding a `forceUnpause` here would require this mixin to take a
/// dependency on OZ Pausable, which the mixin's NatSpec explicitly
/// avoids ("the lib stays usable by non-OZ contracts"). Instead, we
/// codify the operational guarantee:
///
/// OPERATIONAL INVARIANT (governance-enforced):
/// - Owner multisig MUST monitor pause events on all consumer
/// contracts (TegridyStaking, RevenueDistributor, SwapFeeRouter,
/// POLAccumulator, TegridyRestaking).
/// - SLA: owner MUST resolve any pause within 30 days OR rotate
/// the guardian (instant per the L36 NatSpec) to neutralize a
/// pause-griefing key.
/// - On joint failure (owner unavailable AND guardian compromised),
/// the protocol enters degraded mode but no funds are at risk
/// because the guardian cannot withdraw, only pause.
///
/// If consumer-side forceUnpause is desired in a future wave, each
/// consumer adds a `MAX_PAUSE_DURATION` constant + permissionless
/// `forceUnpause()` that checks `block.timestamp > pausedAt +
/// MAX_PAUSE_DURATION` and calls `_unpause()`. Pattern reference:
/// Lido GateSeal contract.
uint256 public constant MAX_PAUSE_DURATION_RECOMMENDED = 30 days;
/// @dev Used by consumers to gate the public `guardianPause()` entry-point.
modifier onlyPauseGuardian() {
if (msg.sender != pauseGuardian) revert NotPauseGuardian();
_;
}
}
src/base/TimelockAdmin.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title TimelockAdmin — Generic inline timelock for admin parameter changes
/// @notice Inspired by MakerDAO DSPause propose/plot/exec pattern.
/// Provides a reusable propose → execute → cancel flow with configurable delays
/// and a universal 7-day proposal validity window.
/// @dev Each timelocked operation is identified by a bytes32 key. Inheriting contracts
/// wrap this with typed propose/execute/cancel functions for each parameter.
///
/// Source pattern: MakerDAO DSPause (billions TVL, never compromised)
/// - Mandatory delay between propose and execute
/// - Proposal expires after validity window (prevents stale proposals from lurking)
/// - Only one pending proposal per key (must cancel before re-proposing)
///
/// AUDIT FIX FRESH-2026 — F-75-9..15 review (negative findings):
/// - F-75-9 (boundary check at exact expiration): verified safe — `_execute`
/// uses `block.timestamp > readyAt + validity` (strict-`>`), so execution
/// at the exact expiry instant succeeds and `>` ensures expiry exclusive.
/// - F-75-10 (MIN_DELAY-1 attack): mitigated by `if (minD < MIN_DELAY) minD = MIN_DELAY`
/// hard floor on the `_minDelay()` hook return. Cannot be triggered.
/// - F-75-11 (executeAfter overflow): unreachable — `delay > maxD` is
/// rejected, MAX_DELAY = 30 days, and Solidity 0.8+ checked-math
/// prevents `block.timestamp + delay` overflow.
/// - F-75-12 (queue same proposal twice): per-key uniqueness via
/// `_executeAfter[key] != 0 → revert ExistingProposalPending`.
/// - F-75-13 (stale slot via idempotent re-propose): no exploit; child
/// contracts that short-circuit `propose*` on idempotent state have
/// their `_executeAfter` slot cleared by the prior `_execute`.
/// - F-75-14 (pendingStakingAdmin race): unreachable due to ordering.
/// - F-75-15 (force-cancel migration): all in-tree direct-write paths
/// use `_forceCancel(KEY)` which fires the canonical
/// `ProposalCancelled` event.
/// AUDIT FIX FRESH-2026 — F-40-TLA-2 (`_maxDelay` fallback): documented
/// LOW. The `if (maxD < minD) maxD = MAX_DELAY` fallback uses MAX_DELAY
/// (30 days) directly. A future child override returning `_minDelay > 30 days`
/// would still trip `DelayTooShort` on every propose since `MAX_DELAY < minD`
/// would short-circuit. In-tree no child does this — flagged for future
/// auditors. The mitigation is "use `max(MAX_DELAY, minD * 2)` instead",
/// but that requires the override-hook contract to declare both `_minDelay`
/// and `_maxDelay` consistently, which is on the child author.
/// AUDIT FIX FRESH-2026 — F-40-TLA-3 (`_executeAfter` direct-write):
/// `_executeAfter` is `internal` (not `private`) so child contracts CAN
/// direct-write `_executeAfter[KEY] = 0` to bypass the `ProposalCancelled`
/// event. Mitigation: every in-tree child has been audited and uses
/// `_forceCancel(KEY)` for out-of-band clears (see F-75-15). New child
/// contracts MUST use `_forceCancel`; direct-writes are forbidden.
abstract contract TimelockAdmin {
// ─── Errors ──────────────────────────────────────────────────────
error NoPendingProposal(bytes32 key);
error ProposalNotReady(bytes32 key);
error ProposalExpired(bytes32 key);
error ExistingProposalPending(bytes32 key);
error DelayTooShort(uint256 delay, uint256 minimum);
/// @dev AUDIT MICROSCOPE_2026_04_30 M-Lib1: caller passed a `delay` exceeding
/// `MAX_DELAY`. Closes the brief-key-compromise → indefinite-lockout
/// attack where a captured owner could call every typed propose with
/// `delay = type(uint256).max`, freezing the protocol's admin surface
/// for billions of years (since `_propose` rejects re-proposals while
/// a previous one is pending).
error DelayTooLong(uint256 delay, uint256 maximum);
// ─── Events ──────────────────────────────────────────────────────
event ProposalCreated(bytes32 indexed key, uint256 executeAfter, uint256 expiresAt);
event ProposalExecuted(bytes32 indexed key);
event ProposalCancelled(bytes32 indexed key);
// ─── Constants ───────────────────────────────────────────────────
/// @notice All proposals expire 7 days after they become executable.
/// Matches the universal validity window used across all Tegriddy contracts.
/// @dev AUDIT FIX: DEEP-LIB-L5 — kept as `constant` for backward
/// compatibility with downstream contracts that read this value
/// without parens (e.g. RevenueDistributor.executeClaimRecovery).
/// Children that need a different validity window should override
/// the `_proposalValidity()` virtual hook below — `_propose` and
/// `_execute` use the hook so an override widens the window
/// consistently across propose / execute paths.
uint256 public constant PROPOSAL_VALIDITY = 7 days;
/// @notice Minimum delay to prevent instant execution bypass.
/// Child contracts should use delays >= 1 hour for any sensitive parameter.
/// @dev AUDIT FIX: DEEP-LIB-M-Lib1 (027 M-01) — see `_minDelay()`
/// virtual hook below for child-overridable behaviour.
uint256 public constant MIN_DELAY = 1 hours;
/// @notice AUDIT MICROSCOPE_2026_04_30 M-Lib1: maximum delay cap. 30 days
/// matches Compound's `Timelock.MAXIMUM_DELAY` and bounds the
/// worst-case lockout from a single captured-owner propose call
/// to one month — long enough to be inconvenient but recoverable
/// via guardian-cancel within the validity window.
/// @dev AUDIT FIX: DEEP-LIB-L4 — see `_maxDelay()` virtual hook
/// below for child-overridable behaviour. Constant exposed for
/// backward compatibility (downstream contracts may reference it
/// in tests or off-chain tooling).
uint256 public constant MAX_DELAY = 30 days;
// ─── Virtual hooks (DEEP-LIB-L4 / L5 / M-Lib1) ───────────────────
// The lib uses these virtual hooks rather than the public constants so a
// child contract with a more conservative or more permissive policy can
// override without breaking external getters (constants stay as documented
// protocol-wide defaults). Children override the hook, NOT the constant.
/// @dev AUDIT FIX: DEEP-LIB-M-Lib1 — virtual minimum-delay hook.
function _minDelay() internal view virtual returns (uint256) {
return MIN_DELAY;
}
/// @dev AUDIT FIX: DEEP-LIB-L4 — virtual maximum-delay hook. Children
/// that genuinely need >30-day delays for treasury-class ops should
/// override this rather than encoding cap-evasion in their own typed
/// propose paths.
function _maxDelay() internal view virtual returns (uint256) {
return MAX_DELAY;
}
/// @dev AUDIT FIX: DEEP-LIB-L5 — virtual proposal-validity hook.
/// Emergency-class proposals (e.g. RevenueDistributor.executeEmergencyWithdrawExcess,
/// POLAccumulator.executeSweepETH) should override with a wider window
/// so a multisig-unavailability event doesn't expire the proposal
/// mid-incident-response.
function _proposalValidity() internal view virtual returns (uint256) {
return PROPOSAL_VALIDITY;
}
// ─── State ───────────────────────────────────────────────────────
/// @notice Maps operation key → timestamp after which the proposal can be executed.
/// Zero means no pending proposal for that key.
/// @dev AUDIT FIX: DEEP-LIB-H4 / DEEP-LIB-M5 — slot remains `internal`
/// for backward compatibility with the 17 child contracts that
/// currently read `_executeAfter[KEY]` directly in legacy view
/// helpers and event-emit paths. The structural defense against
/// direct-write bypass-of-`ProposalCancelled` is the new
/// `_forceCancel` helper below — child contracts that need to
/// clear a pending proposal "out of band" (e.g.
/// TegridyFactory.acceptFeeToSetter clearing a queued
/// old-setter proposal) MUST call `_forceCancel(KEY)` rather
/// than direct-writing zero. New child contracts SHOULD use
/// `_proposalReadyAt(KEY)` for reads to keep the surface
/// consistent. A future major version may demote this slot to
/// `private` once all callsites have migrated.
/// @dev AUDIT FIX 2026-05-26 [M-19]: SECURITY INVARIANT — child contracts MUST
/// use `_forceCancel(KEY)` for cancellation paths to emit the canonical
/// `ProposalCancelled(KEY)` event. Direct writes (`_executeAfter[KEY] = 0`)
/// bypass observability for any indexer subscribed to that event. Verified
/// safe in current consumers as of the 2026-05-26 swarm audit; future
/// contributors MUST preserve this convention. CI lint recommendation:
/// grep for direct writes outside `_propose`/`_execute`/`_cancel`/
/// `_forceCancel` and block PRs that introduce them.
mapping(bytes32 => uint256) internal _executeAfter;
// ─── Internal API ────────────────────────────────────────────────
/// @notice Create a timelocked proposal.
/// @param key Unique identifier for the operation (e.g., keccak256("FEE_CHANGE"))
/// @param delay Minimum seconds before the proposal becomes executable
/// @dev Reverts if a proposal for this key is already pending. Caller must cancel first.
/// @dev AUDIT FIX FRESH-2026: F-40-TLA-1 — the emitted `expiresAt` now
/// uses the FLOORED validity (max(_proposalValidity(), MIN_DELAY))
/// rather than the raw hook return. Pre-fix a child overriding
/// `_proposalValidity()` to return below MIN_DELAY would emit a
/// misleading `expiresAt` to off-chain indexers (apparent expiry
/// = readyAt + 0) while `_execute` actually allowed execution up
/// to readyAt + MIN_DELAY (via the M30 floor). On-chain and
/// off-chain views were divergent — a footgun for any future
/// override.
function _propose(bytes32 key, uint256 delay) internal {
uint256 minD = _minDelay();
// FRESH-EYES L: protocol-wide hard floor on the override-hook return value. Without
// this, a malicious or buggy child could override `_minDelay()` to return 0 and
// defeat the entire timelock invariant. The MIN_DELAY constant is the documented
// protocol-wide minimum ("1 hour minimum" — see line 51); enforcing it here makes
// the hook a UPPER-bound override (children can require longer delays via override,
// never shorter). Pattern of record: Compound Timelock.MINIMUM_DELAY is hard-coded
// and not overridable.
if (minD < MIN_DELAY) minD = MIN_DELAY;
uint256 maxD = _maxDelay();
// AUDIT FIX (BATCH-H M30): symmetric protocol-wide floor on `_maxDelay()`
// override. Pre-fix, a child returning maxD == 0 (or maxD < minD) would
// make `delay > maxD` trip on EVERY proposal, permanently bricking the
// child's admin surface. Mirror the MIN_DELAY hard-floor on minD above.
if (maxD < minD) maxD = MAX_DELAY;
if (delay < minD) revert DelayTooShort(delay, minD);
// AUDIT MICROSCOPE_2026_04_30 M-Lib1: cap the per-call delay.
if (delay > maxD) revert DelayTooLong(delay, maxD);
if (_executeAfter[key] != 0) revert ExistingProposalPending(key);
_executeAfter[key] = block.timestamp + delay;
// AUDIT FIX FRESH-2026: F-40-TLA-1 — floor the validity used in
// the event so off-chain indexers see the same window that
// `_execute` actually enforces. Without the floor, a child that
// overrides `_proposalValidity()` to return < MIN_DELAY would emit
// a tighter window than the contract honors at execute time —
// off-chain monitors would mark the proposal as expired before
// the contract actually rejects it, masking the divergence.
uint256 validityForEvent = _proposalValidity();
if (validityForEvent < MIN_DELAY) validityForEvent = MIN_DELAY;
emit ProposalCreated(key, _executeAfter[key], _executeAfter[key] + validityForEvent);
}
/// @notice Execute a previously proposed change.
/// @param key Unique identifier for the operation
/// @dev Reverts if no proposal exists, if the delay hasn't elapsed, or if the proposal expired.
/// Clears the pending state before returning so re-entrancy can't replay.
function _execute(bytes32 key) internal {
uint256 readyAt = _executeAfter[key];
if (readyAt == 0) revert NoPendingProposal(key);
if (block.timestamp < readyAt) revert ProposalNotReady(key);
// AUDIT FIX (BATCH-H M30): floor _proposalValidity() at MIN_DELAY (1h).
// Pre-fix, a child returning 0 would make this comparison `block.timestamp > readyAt`
// — a 1-second execution window. Floor mirrors the minD floor in _propose.
uint256 validity = _proposalValidity();
if (validity < MIN_DELAY) validity = MIN_DELAY;
if (block.timestamp > readyAt + validity) revert ProposalExpired(key);
_executeAfter[key] = 0; // Clear before external effects (CEI)
emit ProposalExecuted(key);
}
/// @notice Cancel a pending proposal.
/// @param key Unique identifier for the operation
/// @dev Reverts if no proposal exists for this key.
function _cancel(bytes32 key) internal {
if (_executeAfter[key] == 0) revert NoPendingProposal(key);
_executeAfter[key] = 0;
emit ProposalCancelled(key);
}
/// @notice AUDIT FIX: DEEP-LIB-H4 / DEEP-LIB-M5 — best-effort cancel that
/// silently no-ops when no proposal is pending and ALWAYS emits
/// the canonical `ProposalCancelled(key)` event when it does
/// clear state. Use this from child-contract paths that
/// "transitively" need to invalidate a pending proposal —
/// the canonical case is TegridyFactory.acceptFeeToSetter,
/// which clears the previous setter's queued FEE_TO_CHANGE on
/// setter rotation. Pre-fix that direct-wrote
/// `_executeAfter[FEE_TO_CHANGE] = 0`, suppressing the
/// ProposalCancelled event that off-chain monitors / Tenderly
/// alerts subscribe to. New child contracts MUST use this
/// helper rather than direct-writing zero.
/// @param key Unique identifier for the operation.
/// @return cancelled True iff a pending proposal was cleared by this call.
function _forceCancel(bytes32 key) internal returns (bool cancelled) {
if (_executeAfter[key] == 0) return false;
_executeAfter[key] = 0;
emit ProposalCancelled(key);
return true;
}
/// @notice Check whether a proposal is pending for a given key.
function hasPendingProposal(bytes32 key) external view returns (bool) {
return _executeAfter[key] != 0;
}
/// @notice Get the execute-after timestamp for a pending proposal.
/// @return 0 if no proposal is pending, otherwise the timestamp.
function proposalExecuteAfter(bytes32 key) external view returns (uint256) {
return _executeAfter[key];
}
/// @notice Canonical read accessor for child contracts. Returns the
/// timestamp after which the pending proposal for `key` becomes
/// executable, or 0 if no proposal is pending.
function _proposalReadyAt(bytes32 key) internal view returns (uint256) {
return _executeAfter[key];
}
/// @notice DEPRECATED — use `_proposalReadyAt` instead.
/// @dev Kept for back-compat with test harnesses that call this name.
// slither-disable-next-line dead-code
function _executeAfterOf(bytes32 key) internal view returns (uint256) {
return _executeAfter[key];
}
}
src/lib/SequencerCheck.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @notice Minimal subset of the Chainlink AggregatorV3Interface that L2 Sequencer
/// Uptime Feeds expose. We only need `latestRoundData()`.
/// @dev Reference: https://docs.chain.link/data-feeds/l2-sequencer-feeds
interface IChainlinkAggregator {
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
/// @title SequencerCheck — L2 Sequencer Uptime gating helper
/// @notice Library that lets price-sensitive consumers (TWAP consumers, LP harvesters,
/// dutch-auction price readers, lending grace-windows) refuse to read prices
/// when the L2 sequencer has been down or has just resumed within a grace
/// period. Without this, the moment a sequencer resumes after an outage all
/// AMM/oracle prices reflect the pre-outage state and an attacker can either
/// (a) buy/sell at stale prices before the chain catches up or (b) trigger
/// time-window checks (lending grace, drop dutch decay, bounty force-cancel)
/// that elapsed entirely while the chain was unavailable.
///
/// @dev Battle-tested model: Aave V3 PriceOracleSentinel (`isAnswerNotStale`).
/// Spec: Chainlink L2 Sequencer Uptime Feeds. The feed returns:
/// - `answer == 0` → sequencer is up
/// - `answer == 1` → sequencer is down OR was down recently
/// - `startedAt` → block.timestamp when the current `answer` was set;
/// used to enforce a post-resume grace window during which
/// oracle reads are still rejected so AMM reserves /
/// cumulative-price observations have time to refresh.
///
/// Per-chain feed addresses (canonical, immutable post-deploy):
/// - Ethereum mainnet (no sequencer): address(0) → no-op
/// - Arbitrum One: 0xFdB631F5EE196F0ed6FAa767959853A9F217697D
/// - Optimism: 0x371EAD81c9102C9BF4874A9075FFFf170F2Ee389
/// - Base: 0xBCF85224fc0756B9Fa45aA7892530B47e10b6433
///
/// Consumers MUST store the feed address as `immutable` (single-write, set in
/// constructor) and pass `address(0)` for chains without an L2 sequencer.
library SequencerCheck {
/// @dev Reverted when the sequencer is currently reporting "down" (answer != 0).
error SequencerDown();
/// @dev Reverted when the sequencer just resumed but the post-resume grace window
/// has not yet elapsed. Lets AMM reserves / TWAP observations refresh before
/// consumers trust the price.
error SequencerGracePeriodNotOver();
/// @dev AUDIT FIX FRESH-2026: H-9 [F-74-1, F-74-2] — reverted when a
/// consumer on a non-mainnet chain (i.e. an L2) calls
/// `checkSequencerUp` with `feed == address(0)`. Pre-fix, the
/// `feed == address(0)` branch silently no-op'd on every chain,
/// so a deploy script that omitted `setSequencerFeed(...)` (or
/// passed `vm.envOr("SEQUENCER_FEED", address(0))` with the env
/// unset) would ship with sequencer protection inert on L2 with
/// no on-chain warning. The lib now refuses the no-op on any
/// chain except `chainid == 1` (Ethereum mainnet, which has no
/// sequencer concept). Mainnet keeps the no-op fast path.
error SequencerFeedNotConfigured();
/// @dev AUDIT FIX 2026-05-26 [M-23] — reverted when a consumer passes a
/// `gracePeriod` below `MIN_GRACE_PERIOD` (60s). Pre-fix, callers
/// could pass `gracePeriod = 0` and the post-resume window check
/// collapsed to `block.timestamp - startedAt < 0` which is always
/// false → silent bypass of the entire post-resume buffer. Mirrors
/// TimelockAdmin's MIN_DELAY floor pattern (loud failure > silent
/// acceptance — single revert, no inline clamping).
error GraceTooShort();
/// @notice AUDIT FIX 2026-05-26 [M-23] — protocol-wide minimum on the
/// post-resume grace window passed to `checkSequencerUp`. 1 minute
/// is the floor below which the gate is effectively inert (a single
/// block can elapse on most L2s). Honest consumers use 1h+ (Aave
/// V3 stable-asset default); the floor only catches misconfigured
/// deploys and `gracePeriod = 0` bypass attempts.
uint256 internal constant MIN_GRACE_PERIOD = 60;
/// @notice AUDIT MICROSCOPE_2026_04_30 M-Lib2 / DEEP-LIB-M3: max acceptable
/// staleness on the uptime feed itself. Chainlink's L2 uptime feed is
/// keeper-updated; if the keeper lapses, `latestRoundData` returns a
/// previously-cached round whose `answer` may no longer reflect reality.
/// Aave V3 `PriceOracleSentinel` and the Chainlink "Handling Outages"
/// docs require `block.timestamp - updatedAt <= MAX_FEED_STALENESS`
/// AND `answeredInRound >= roundId` to defend against this. 24h matches
/// Aave's stable-asset default.
/// @dev DEEP-LIB-M3: per-consumer tuning is offered through the `staleness`
/// overload of `checkSequencerUp`. Lending / drop pricing should pick a
/// tighter window (e.g. 4h) so a keeper lapse trips earlier on
/// price-sensitive paths.
uint256 internal constant MAX_FEED_STALENESS = 24 hours;
// ─── Reasons reported by `tryCheckSequencerUp` (DEEP-LIB-M6) ─────
/// @dev Sequencer is up AND the post-resume grace window elapsed. Consumer
/// may safely consume the price/observation.
uint8 internal constant TRY_OK = 0;
/// @dev Round is not yet initialized (`updatedAt == 0`). Treat as "down".
uint8 internal constant TRY_ROUND_UNINIT = 1;
/// @dev `answeredInRound < roundId` — the answer pre-dates the round.
uint8 internal constant TRY_STALE_ROUND = 2;
/// @dev `block.timestamp - updatedAt > staleness` — keeper lapse.
uint8 internal constant TRY_KEEPER_LAPSED = 3;
/// @dev `answer != 0` — sequencer reporting down.
uint8 internal constant TRY_SEQ_DOWN = 4;
/// @dev `startedAt == 0` — round not yet initialized for the up answer.
uint8 internal constant TRY_NO_RESUME = 5;
/// @dev `block.timestamp - startedAt < gracePeriod` — within grace window.
uint8 internal constant TRY_IN_GRACE = 6;
// AUDIT FIX: V2-LIB-M1 — feed advertises a future-dated `updatedAt` /
// `startedAt` (clock skew on a bridged/relayed feed can post
// `updatedAt = block.timestamp + 1` on the very block of resume).
// Before this reason byte, the soft-fail path tripped a checked-math
// underflow `Panic(0x11)`, breaking the "non-reverting" promise that
// indexers / quoter eth_calls rely on.
uint8 internal constant TRY_CLOCK_SKEW = 7;
/// @notice Revert if the L2 sequencer is down or within `gracePeriod` of resume.
/// @dev Pass `feed == address(0)` to no-op (Ethereum mainnet and any chain
/// without a sequencer concept). `gracePeriod` is the buffer in seconds
/// after resume during which reads are still rejected; recommended value
/// is 1 hour (matches Aave V3 default for stable assets) but consumers
/// may tune up/down per use case.
/// @dev AUDIT FIX: DEEP-LIB-M3 — defaults to `MAX_FEED_STALENESS` (24h);
/// price-sensitive consumers can use the 3-argument overload to pass
/// a tighter staleness window.
/// @param feed Chainlink L2 Sequencer Uptime feed address (or 0 for no-op).
/// @param gracePeriod Seconds after sequencer resume during which reads still revert.
function checkSequencerUp(address feed, uint256 gracePeriod) internal view {
checkSequencerUp(feed, gracePeriod, MAX_FEED_STALENESS);
}
/// @notice AUDIT FIX: DEEP-LIB-M3 — overload that accepts a per-call
/// staleness window. Lending valuation, drop dutch-auction
/// pricing, and POL accumulator should call this with a tighter
/// window (e.g. 4h) so a Chainlink keeper outage trips before
/// the cached uptime answer drifts past safe-to-trust.
/// @param feed Chainlink L2 Sequencer Uptime feed address (or 0 for no-op).
/// @param gracePeriod Seconds after sequencer resume during which reads still revert.
/// @param staleness Max acceptable `block.timestamp - updatedAt` on the feed.
function checkSequencerUp(address feed, uint256 gracePeriod, uint256 staleness) internal view {
// AUDIT FIX 2026-05-26 [M-23] — Reject sub-minimum grace at function
// top. Pass-thru `gracePeriod = 0` would otherwise silently bypass
// the post-resume buffer (block.timestamp - startedAt < 0 is always
// false). Loud failure beats silent acceptance; mirrors
// TimelockAdmin's MIN_DELAY floor at line 167.
if (gracePeriod < MIN_GRACE_PERIOD) revert GraceTooShort();
// Mainnet / non-L2 deployments: feed = address(0) → skip entirely.
// AUDIT FIX FRESH-2026: H-9 [F-74-1, F-74-2] — but ONLY if we're
// actually on mainnet. Pre-fix every L2 chain that shipped without
// `setSequencerFeed(...)` got the no-op too, silently disabling
// sequencer protection. The deploy-side fix (Wave C) requires
// explicit feed wiring; this lib-side guard is the structural
// backstop that makes the failure visible at first call rather
// than silent at deploy time. NatSpec invariant: ANY non-mainnet
// deploy MUST configure the feed; this revert surfaces the gap.
if (feed == address(0)) {
if (block.chainid != 1) revert SequencerFeedNotConfigured();
return;
}
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = IChainlinkAggregator(feed).latestRoundData();
// AUDIT MICROSCOPE_2026_04_30 M-Lib2: round-validity / freshness checks
// PRECEDE the up/down decision so a stale feed can never fall through the
// `answer != 0` branch with a cached "up" reading. Pattern of record:
// Aave V3 PriceOracleSentinel + Chainlink "Handling Outages" docs.
if (updatedAt == 0) revert SequencerGracePeriodNotOver(); // round not initialized
if (answeredInRound < roundId) revert SequencerDown(); // answer pre-dates round
// AUDIT FIX: v3-LIB-M1 — directional ordering check BEFORE the
// subtraction. A future-dated `updatedAt` (sub-second clock skew on
// a bridged/relayed feed, common after sequencer replay on
// Arbitrum/Base) would have underflowed checked-math with
// `Panic(0x11)` — structurally distinct from the typed `SequencerDown`
// selector that off-chain decoders / wagmi / ethers / viem branch on.
// This restores typed-revert symmetry with `tryCheckSequencerUp` /
// `getSequencerOutageBuffer` (closed in v2-LIB-M1) so the same input
// class produces the same revert type across all three helpers.
if (updatedAt > block.timestamp) revert SequencerDown(); // clock skew → fail-closed
unchecked {
if (block.timestamp - updatedAt > staleness) revert SequencerDown(); // keeper lapse
}
// AUDIT MICROSCOPE_2026_04_30 M-Lib3: strict equality to UP. Pre-fix
// `answer == 1` only treats exactly 1 as down — values like 2 (a future
// "degraded" extension), -1 (typed-bug from a bridged feed), etc. would
// pass through as "up". The spec says `0` is up; canonical pattern is
// `answer != 0` → fail closed. Aligned with `getResumeTimestamp` below.
if (answer != 0) revert SequencerDown();
// Sequencer is up. Additionally require it has been up for at least
// `gracePeriod` seconds. A `startedAt` of 0 is treated as "no round yet".
if (startedAt == 0) revert SequencerGracePeriodNotOver();
// AUDIT FIX: v3-LIB-M1 — same future-dated guard for `startedAt` so
// a clock-skew event on the resume timestamp also produces the typed
// `SequencerGracePeriodNotOver` rather than `Panic(0x11)`.
if (startedAt > block.timestamp) revert SequencerGracePeriodNotOver(); // clock skew on grace
unchecked {
if (block.timestamp - startedAt < gracePeriod) {
revert SequencerGracePeriodNotOver();
}
}
}
/// @notice AUDIT FIX: DEEP-LIB-M6 — non-reverting sister of `checkSequencerUp`.
/// Returns `(ok, reason)` instead of reverting so view paths
/// (indexers, frontend `eth_call` simulators, aggregator quote paths)
/// can degrade gracefully during a sequencer outage instead of
/// gas-bombing every read.
/// @dev Security-critical write paths (lending liquidation, drop pricing,
/// POL harvest) MUST keep using the reverting `checkSequencerUp`.
/// This helper is for soft-fail UX scenarios only.
/// @param feed Chainlink L2 Sequencer Uptime feed address (or 0 for no-op).
/// @param gracePeriod Seconds after sequencer resume during which reads are still considered "in grace".
/// @return ok True iff the sequencer is up and outside the grace window.
/// @return reason One of TRY_OK..TRY_IN_GRACE describing the failure mode (TRY_OK on success).
function tryCheckSequencerUp(address feed, uint256 gracePeriod)
internal
view
returns (bool ok, uint8 reason)
{
return tryCheckSequencerUp(feed, gracePeriod, MAX_FEED_STALENESS);
}
/// @notice AUDIT FIX: DEEP-LIB-M6 — overload that accepts a per-call staleness window.
function tryCheckSequencerUp(address feed, uint256 gracePeriod, uint256 staleness)
internal
view
returns (bool ok, uint8 reason)
{
if (feed == address(0)) return (true, TRY_OK);
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = IChainlinkAggregator(feed).latestRoundData();
if (updatedAt == 0) return (false, TRY_ROUND_UNINIT);
if (answeredInRound < roundId) return (false, TRY_STALE_ROUND);
// AUDIT FIX: V2-LIB-M1 — directional ordering check BEFORE the
// subtraction. A future-dated `updatedAt` (clock skew on a bridged
// feed) made `block.timestamp - updatedAt` underflow with
// `Panic(0x11)`, breaking the "non-reverting" promise of this helper.
// Treat any future-dated round as a clock-skew event (fail closed).
if (updatedAt > block.timestamp) return (false, TRY_CLOCK_SKEW);
unchecked {
if (block.timestamp - updatedAt > staleness) return (false, TRY_KEEPER_LAPSED);
}
if (answer != 0) return (false, TRY_SEQ_DOWN);
if (startedAt == 0) return (false, TRY_NO_RESUME);
// AUDIT FIX: V2-LIB-M1 — same future-dated guard for `startedAt`.
if (startedAt > block.timestamp) return (false, TRY_CLOCK_SKEW);
unchecked {
if (block.timestamp - startedAt < gracePeriod) return (false, TRY_IN_GRACE);
}
return (true, TRY_OK);
}
/// @notice AUDIT FIX: DEEP-LIB-H2 — canonical "should we extend the grace
/// window?" helper for non-revert contexts. Returns `buffer` if
/// the sequencer is currently down OR within `buffer` of resume,
/// otherwise 0. Same staleness/direction gates as
/// `checkSequencerUp` so re-implementations elsewhere in the
/// protocol can be retired in favour of this single source of
/// truth (closes the M-Lib3 sibling-miss in MemeBountyBoard's
/// duplicated `_sequencerBuffer`).
/// @dev Used by bounty refund / emergency-cancel windows that widen
/// the grace period when an L2 sequencer outage prevented honest
/// participation. Returns 0 when `feed == address(0)` (mainnet no-op).
/// @param feed Chainlink L2 Sequencer Uptime feed address (or 0 for no-op).
/// @param buffer Seconds to extend the grace window when an outage is
/// detected. Returned as-is on outage; 0 otherwise.
/// @dev AUDIT FIX: V2-LIB-M2 — defaults to `MAX_FEED_STALENESS` (24h);
/// consumers that need a tighter staleness window (e.g. short-
/// deadline bounty refunds) should use the 3-argument overload
/// below for symmetry with `checkSequencerUp` /
/// `tryCheckSequencerUp`.
function getSequencerOutageBuffer(address feed, uint256 buffer)
internal
view
returns (uint256)
{
return getSequencerOutageBuffer(feed, buffer, MAX_FEED_STALENESS);
}
/// @notice AUDIT FIX: V2-LIB-M2 — overload that accepts a per-call
/// staleness window. Matches the (`feed, gracePeriod, staleness`)
/// shape of `checkSequencerUp` / `tryCheckSequencerUp` so the
/// helper trio shares a consistent API surface (closes the
/// M-Lib3 sibling-miss between the H2 helper and the M3
/// staleness fix).
/// @param feed Chainlink L2 Sequencer Uptime feed address (or 0 for no-op).
/// @param buffer Seconds to extend the grace window when an outage is detected.
/// @param staleness Max acceptable `block.timestamp - updatedAt` on the feed.
function getSequencerOutageBuffer(address feed, uint256 buffer, uint256 staleness)
internal
view
returns (uint256)
{
if (feed == address(0)) return 0;
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = IChainlinkAggregator(feed).latestRoundData();
// Mirror the same fail-closed gates as `checkSequencerUp`. Any feed
// anomaly (uninitialized round, stale answer, keeper lapse, non-zero
// answer, missing startedAt) is treated as "outage" → return buffer.
if (updatedAt == 0) return buffer; // round not initialized
if (answeredInRound < roundId) return buffer; // answer pre-dates round
// AUDIT FIX: V2-LIB-M1 — directional ordering check BEFORE the
// subtraction. A future-dated `updatedAt` (clock skew on a bridged
// feed) would have underflowed with `Panic(0x11)`, breaking the
// soft-fail contract this helper offers to non-reverting consumers
// (MemeBountyBoard refund / cancel paths).
if (updatedAt > block.timestamp) return buffer; // clock skew → treat as outage
unchecked {
if (block.timestamp - updatedAt > staleness) return buffer; // keeper lapse
}
if (answer != 0) return buffer; // sequencer down
if (startedAt == 0) return buffer; // no round yet
// AUDIT FIX: V2-LIB-M1 — same future-dated guard for `startedAt`.
if (startedAt > block.timestamp) return buffer; // clock skew → treat as outage
unchecked {
if (block.timestamp - startedAt < buffer) return buffer; // within grace
}
return 0;
}
/// @notice AUDIT R014 H-6: return the wall-clock timestamp at which the
/// sequencer most recently transitioned to "up". Sentinel
/// semantics differ by failure mode — see the return-value doc below.
///
/// @dev `checkSequencerUp` only proves the sequencer is currently up AND
/// the post-resume grace window has elapsed. It does NOT expose
/// WHEN the resume happened — so a downstream consumer can pass the
/// gate while still consuming a stale oracle observation that
/// pre-dates the resume. This is the core H-6 staleness gap.
/// @dev AUDIT FIX FRESH-2026: M-34 [F-40-SEQ-2] — on every STALE
/// path (uninitialized round, stale answer, keeper lapse,
/// clock-skew on `updatedAt`) the lib now returns
/// `type(uint256).max` (a fail-CLOSED sentinel) instead of 0.
/// Pre-fix consumers computed `resumeAt + GRACE` and compared
/// against observation timestamps; with `resumeAt == 0` the
/// comparison `observation.timestamp >= 0 + GRACE` passed for
/// any post-2024 timestamp, silently bypassing the H6
/// staleness gate. Returning `type(uint256).max` makes the
/// comparison fail closed: `observation.timestamp >= max + GRACE`
/// overflows checked-math (or stays false if the consumer uses
/// unchecked), forcing the consumer to refuse the read. Mainnet
/// (feed == address(0)) and the "sequencer currently down"
/// (answer != 0) branches still return 0 — those are the
/// "use the up/down decision from checkSequencerUp" paths.
/// @param feed Chainlink L2 Sequencer Uptime feed address.
/// @return resumeAt One of:
/// - `startedAt` (latest round's start) when the sequencer is
/// currently up and the feed is fresh — the resume gating
/// timestamp.
/// - 0 when `feed == address(0)` (mainnet no-op) OR the
/// sequencer is currently down (`answer != 0`); callers
/// must rely on `checkSequencerUp`'s typed revert for the
/// up/down decision.
/// - `type(uint256).max` when the feed is stale (round
/// uninitialized, keeper lapse, clock-skew, etc.); the
/// fail-closed sentinel makes any
/// `observation.timestamp >= resumeAt + GRACE` comparison
/// reject silently, preserving the H6 staleness gate.
function getResumeTimestamp(address feed) internal view returns (uint256 resumeAt) {
// Mainnet / non-L2: no feed → no resume timestamp to gate on. Return 0
// and let the caller skip the staleness comparison entirely.
if (feed == address(0)) return 0;
(
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
) = IChainlinkAggregator(feed).latestRoundData();
// AUDIT MICROSCOPE_2026_04_30 M-Lib2: same freshness gates as
// `checkSequencerUp`. A stale uptime feed must NOT contribute a
// post-resume timestamp that consumers then trust as "fresh enough".
// AUDIT FIX FRESH-2026: M-34 [F-40-SEQ-2] — return type(uint256).max
// on each stale path so the consumer's `resumeAt + GRACE` comparison
// fails closed (was: returned 0 → silently bypassed gate).
if (updatedAt == 0) return type(uint256).max;
if (answeredInRound < roundId) return type(uint256).max;
// AUDIT FIX: v3-LIB-M1 — directional ordering check BEFORE the
// subtraction so a future-dated `updatedAt` (clock skew on a
// bridged/relayed feed) cannot underflow checked-math and propagate
// a `Panic(0x11)` to consumers that expect this helper to return a
// sentinel on stale feeds. Treat any future-dated round as stale.
if (updatedAt > block.timestamp) return type(uint256).max;
unchecked {
if (block.timestamp - updatedAt > MAX_FEED_STALENESS) return type(uint256).max;
}
// If the sequencer is currently down, there is no meaningful "resume"
// timestamp — return 0 and let `checkSequencerUp` produce the typed
// revert. The H-6 staleness comparison is only relevant when the
// sequencer is up; in the down case we already block via SequencerDown.
if (answer != 0) return 0;
// AUDIT FIX (BATCH-I M5): symmetric directional check on `startedAt`.
// Pre-fix, `checkSequencerUp` rejected `startedAt > block.timestamp`
// (v3-LIB-M1) but `getResumeTimestamp` propagated it unmodified.
// Consumers compute `resumeAt + GRACE` for observation-validity
// gates (TWAP, POL, SwapFeeRouter); a future-dated startedAt would
// push that gate arbitrarily far into the future, blocking ALL
// existing observations until on-chain time catches up — an
// unintended DoS on bridged/relayed feeds with clock skew.
// AUDIT FIX FRESH-2026: M-34 [F-40-SEQ-2] — clock-skew on startedAt
// is also a stale-path → fail-closed sentinel.
if (startedAt > block.timestamp) return type(uint256).max;
return startedAt;
}
}
src/lib/WETHFallbackLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @notice Minimal WETH interface — deposit ETH and transfer as WETH.
/// Shared across all contracts that need WETH fallback.
interface IWETH {
function deposit() external payable;
function withdraw(uint256 amount) external;
function transfer(address to, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
/// @title WETHFallbackLib — Safe ETH transfer with automatic WETH fallback
/// @notice Pattern used by 5+ Tegriddy contracts (Router, SwapFeeRouter, Grants, Bounty, Referral).
/// Previously each contract defined its own IWETH interface variant and fallback logic.
///
/// Source patterns:
/// - Solmate SafeTransferLib (Uniswap V3/V4, Seaport)
/// - WETH fallback pattern from Aave V3, Convex
///
/// @dev Attempts a raw ETH transfer first. If the recipient reverts (e.g., a contract without
/// receive()), wraps the ETH as WETH and sends the WETH token instead.
/// This prevents funds from getting stuck when the recipient is a contract.
library WETHFallbackLib {
error ETHTransferFailed();
error WETHTransferFailed();
error ZeroWETHAddress();
/// @dev AUDIT FIX: DEEP-LIB-H1 — recipient cannot be the zero address.
/// Without this guard, a raw `to.call{value:..., gas:10000}("")`
/// against `address(0)` succeeds and silently BURNS the ETH (the EVM
/// lets you "send" ETH to 0x0). The lib then returned without a
/// revert, lying to callers that the transfer succeeded. Solmate's
/// SafeTransferLib reverts on failed transfer — the silent-burn here
/// was a structural divergence that turned every caller into a
/// latent ETH-burn primitive if the destination ever resolved to 0.
error ZeroRecipient();
// ─── AUDIT FIX FRESH-2026: M-36 [F-40-WFL-1] — stipend constant ────────
/// @notice AUDIT FIX FRESH-2026: M-36 [F-40-WFL-1] — gas stipend for the
/// raw ETH `.call` leg of `safeTransferETHOrWrap` / `safeTransferETH`.
/// Bumped from 10_000 → 30_000 to accommodate the cold-storage
/// SSTORE pattern at first-ingress sites (RevenueDistributor /
/// SwapFeeRouter / POLAccumulator `receive()` updates a cumulative
/// counter and emits LOG2 — the zero→non-zero SSTORE alone costs
/// 22_100 gas under EIP-2929/2200, exceeding the prior 10k floor
/// and silently flipping the path to WETH wrap on every fresh
/// deploy). 30k matches the Aerodrome / Bunni v2 distributor-
/// style receiver budget cushion (cold SLOAD 2100 + zero→non-zero
/// SSTORE 22100 + LOG2 ~1750 + dispatch overhead, with ~4k
/// cushion for compiler-generated boilerplate).
/// @dev Defense-in-depth against cross-contract reentrancy is
/// preserved: 30k is still far below any "complex external call"
/// budget (a single CALL opcode alone burns 700g + ~2.5k for
/// arg copy on top of any callee work); the canonical "no
/// external calls from receive" invariant is preserved.
uint256 internal constant ETH_TRANSFER_GAS_STIPEND = 30_000;
/// @notice AUDIT FIX: DEEP-LIB-L1 — emitted on the success path of
/// `safeTransferETHOrWrap` when the raw ETH `.call` succeeds.
/// Mirrors `ETHToWETHFallback` so off-chain indexers always see
/// a positive ack regardless of which leg delivered the funds.
/// Without this, indexers had to infer "ETH was paid" from the
/// absence of a fallback event, which is fragile against dropped
/// log subscriptions.
event ETHTransferred(address indexed to, uint256 amount);
/// @notice AUDIT MICROSCOPE_2026_04_30 H21: emitted whenever the raw 10k-gas ETH
/// send fails and the library wraps the amount as WETH instead. Indexers,
/// downstream accounting, and recipient contracts can subscribe to this
/// event to detect the asymmetric asset-type degradation. Without it,
/// a recipient contract whose `receive()` outgrew the 10k stipend would
/// silently start receiving WETH instead of ETH — every protocol caller
/// would inherit the inconsistency without any on-chain breadcrumb.
event ETHToWETHFallback(address indexed weth, address indexed to, uint256 amount);
/// @notice Reintroduced 2026-05-31 with safeTransferETHOrWrapNoRevert (see below).
/// mode==2: deposit succeeded but the WETH transfer failed, so WETH is
/// stranded in the caller and the caller MUST credit it (pull-pattern).
event WETHTransferStuck(address indexed weth, address indexed to, uint256 amount);
/// @notice Reintroduced 2026-05-31. mode==3: total failure, ETH untouched in caller.
event ETHWrapFailed(address indexed weth, address indexed to, uint256 amount);
/// @notice Transfer ETH to `to`. If the raw ETH send fails, wraps as WETH and sends that.
/// @param weth The canonical WETH contract address for this chain (must be set immutably at deploy time)
/// @param to Recipient address
/// @param amount Wei to transfer
/// @dev SECURITY: The `weth` parameter MUST be a trusted, immutable address set in the constructor.
/// Never pass user-supplied or dynamic WETH addresses — a malicious WETH could re-enter via deposit().
/// @dev AUDIT FIX FRESH-2026: M-37 [F-40-WFL-4] — `weth` is parametric on
/// purpose so the lib stays reusable; the relaunch is the right
/// moment to canonicalize per-deployment, NOT in the lib. Consumers
/// MUST verify `weth` ABI shape AND store it as `immutable` after
/// constructor verification (every in-tree consumer already does
/// this — RevenueDistributor.weth, SwapFeeRouter.WETH,
/// TegridyFeeHook.WETH, MemeBountyBoard.weth, ReferralSplitter.weth,
/// TegridyLending.weth, POLAccumulator.weth, CommunityGrants.weth,
/// TegridyNFTPool.weth). Pass-through here is sufficient defense-
/// in-depth for the lib boundary.
/// @dev AUDIT FIX FRESH-2026: M-36 [F-40-WFL-1] — gas stipend bumped
/// from 10_000 → ETH_TRANSFER_GAS_STIPEND (30_000). A cold-storage
/// SSTORE in a first-ingress receiver costs 22_100g under
/// EIP-2929/2200; the prior 10k floor silently fell through to the
/// WETH wrap path on every fresh ingress to RevenueDistributor /
/// SwapFeeRouter / POLAccumulator. Reentrancy defense preserved
/// (still far below any external CALL budget).
function safeTransferETHOrWrap(address weth, address to, uint256 amount) internal {
if (amount == 0) return;
// AUDIT FIX: DEEP-LIB-H1 — fail-closed on zero recipient. The
// amount==0 short-circuit above stays first since a no-op transfer
// is harmless; once we know we're moving real value, the destination
// MUST be non-zero or we'd burn ETH (raw `.call` to 0x0 succeeds).
if (to == address(0)) revert ZeroRecipient();
if (weth == address(0)) revert ZeroWETHAddress();
// AUDIT FIX FRESH-2026: M-36 [F-40-WFL-1] — 30k stipend (was 10k).
// Reentrancy defense preserved (still far below external-call budget);
// the bump accommodates first-ingress cold-SSTORE cost.
(bool ok,) = to.call{value: amount, gas: ETH_TRANSFER_GAS_STIPEND}("");
if (ok) {
// AUDIT FIX: DEEP-LIB-L1 — symmetric success-path event so
// off-chain indexers see ETH-delivered breadcrumbs regardless
// of which leg (raw call vs WETH wrap) handled the transfer.
emit ETHTransferred(to, amount);
return;
}
// Fallback: wrap as WETH and send the ERC20 token
IWETH(weth).deposit{value: amount}();
bool sent = IWETH(weth).transfer(to, amount);
if (!sent) revert WETHTransferFailed();
emit ETHToWETHFallback(weth, to, amount);
}
/// @notice Transfer ETH to `to` without WETH fallback. Reverts on failure.
/// @dev Use this when WETH fallback is not desired (e.g., refunds to EOAs).
/// @dev AUDIT FIX: DEEP-LIB-H1 — reverts on `to == address(0)` to prevent
/// silent ETH burn (mirror of the `safeTransferETHOrWrap` guard
/// above — same structural defense against future-importer omission).
/// @dev AUDIT FIX FRESH-2026: M-36 [F-40-WFL-1] — gas stipend bumped
/// to 30k for parity with `safeTransferETHOrWrap`. Same first-
/// ingress / cold-SSTORE rationale; reentrancy defense preserved.
function safeTransferETH(address to, uint256 amount) internal {
if (amount == 0) return;
if (to == address(0)) revert ZeroRecipient();
// AUDIT FIX FRESH-2026: M-36 [F-40-WFL-1] — 30k stipend (was 10k).
(bool ok,) = to.call{value: amount, gas: ETH_TRANSFER_GAS_STIPEND}("");
if (!ok) revert ETHTransferFailed();
// AUDIT FIX: V2-LIB-L3 — emit the same success-path event as
// `safeTransferETHOrWrap` so off-chain accounting infrastructure
// sees a consistent breadcrumb regardless of which variant the
// caller picked. Without this, a future caller that explicitly
// chooses the no-fallback variant (e.g. an EOA-only refund path)
// silently regresses the L1 accounting promise.
emit ETHTransferred(to, amount);
}
/// @notice No-revert ETH transfer with WETH fallback, for BATCHED-PAYEE
/// callsites (the NFT-AMM pool's swap/refund/sweep paths) where one
/// bad recipient must NOT brick the whole batch.
/// @dev REINTRODUCED 2026-05-31 for TegridyNFTPool, exactly per the
/// prior [H-WFL-NOREVERT-DELETE] note's carve-out ("if a future
/// BATCHED-PAYEE callsite needs the no-revert semantic, it can be
/// reintroduced ... with consumer-local tests proving the caller
/// credits the stranded path"). Restored verbatim from the pre-cut
/// revision (10e1dcc^); the consumer credits stranded WETH on
/// mode==2, proven by the TegridyNFTPool reentrancy / sandwich /
/// invariant suites that ship alongside it.
/// @return success true if `to` ended up with ETH (mode 0) or WETH (mode 1).
/// @return mode 0=ETH delivered, 1=wrapped to WETH, 2=deposit ok but WETH
/// transfer failed (WETH now stranded in caller — caller MUST
/// credit it), 3=total failure (ETH untouched in caller).
function safeTransferETHOrWrapNoRevert(address weth, address to, uint256 amount)
internal
returns (bool success, uint8 mode)
{
if (amount == 0) return (true, 0);
// Defense-in-depth: even the no-revert variant rejects zero-recipient. Sending to
// 0x0 would silently burn ETH; we surface that to the caller as a hard failure
// so they can route the amount to credit instead of accidentally accepting a
// burn as "success".
// AUDIT FIX FRESH-2026: H-12 — return mode==3 (total failure, ETH
// untouched) instead of overloaded mode==2 for the guard rejections.
if (to == address(0)) return (false, 3);
if (weth == address(0)) return (false, 3);
// AUDIT FIX FRESH-2026: M-36 [F-40-WFL-1] — 30k stipend (was 10k).
(bool okEth,) = to.call{value: amount, gas: ETH_TRANSFER_GAS_STIPEND}("");
if (okEth) {
emit ETHTransferred(to, amount);
return (true, 0);
}
// Try-catch the WETH leg too. `IWETH.deposit` is payable; if the canonical
// WETH ever pauses or the recipient's WETH-transfer hook reverts, we MUST NOT
// bubble — that's the whole point of this variant. Use a low-level call so
// we can capture failure without unwinding the caller's tx.
(bool okDeposit,) = weth.call{value: amount}(abi.encodeWithSelector(IWETH.deposit.selector));
if (!okDeposit) {
// AUDIT FIX FRESH-2026: H-12 [F-80-01, F-40-WFL-2] — deposit
// itself failed; ETH is still in caller's balance. Return
// mode==3 (total failure) and emit `ETHWrapFailed` so monitors
// can branch without inspecting return modes.
emit ETHWrapFailed(weth, to, amount);
return (false, 3);
}
(bool okTransfer, bytes memory data) =
weth.call(abi.encodeWithSelector(IWETH.transfer.selector, to, amount));
// Standard ERC20 returns bool; a few quirky tokens return nothing. Treat empty
// returndata as success only if the call itself didn't revert (parity with
// OZ SafeERC20's `_callOptionalReturn`).
bool wethOk = okTransfer && (data.length == 0 || abi.decode(data, (bool)));
if (!wethOk) {
// AUDIT FIX FRESH-2026: H-12 [F-80-01, F-40-WFL-2] — deposit
// SUCCEEDED but transfer FAILED. ETH is no longer in the
// caller's balance — it has been converted to WETH that now
// sits in the caller's runtime (the lib is internal so
// `address(this)` resolves to the caller). The caller MUST
// either sweep `IWETH(weth).balanceOf(address(this))` into a
// per-recipient pull-pattern slot OR credit `pendingStrandedWETH`
// / equivalent. Mode==2 now ONLY signals this physical state
// (was previously overloaded with deposit-fail). Distinct event
// `WETHTransferStuck` lets monitors auto-detect the stranded
// WETH without parsing return modes.
emit WETHTransferStuck(weth, to, amount);
return (false, 2);
}
emit ETHToWETHFallback(weth, to, amount);
return (true, 1);
}
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/uniswap-hooks/=lib/uniswap-hooks/",
"forge-std/=lib/forge-std/src/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"solmate/=lib/solmate/src/",
"solady/=lib/solady/src/",
"lib/v4-core:solmate/=lib/solmate/",
"lib/v4-periphery:solmate/=lib/solmate/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"ds-test/=lib/solmate/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"uniswap-hooks/=lib/uniswap-hooks/src/",
"v4-core/=lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.