Verified contractExactMIT
Vault
Address0xd4d809261e86eb422467c16bf03b3abe404e5aaa
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,953,159
- Creation transaction
- 0x025e988303…823798a4ef
20 files
- src/core/Vault.solmain38.4 KB
- lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol8.28 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol6.59 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol4.36 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol1.18 KB
- lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.26 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol880 B
- lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol6.72 KB
- lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol472 B
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol3.8 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol5.77 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.26 KB
- lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol3.93 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol869 B
- src/core/VaultBase.sol6.24 KB
- src/core/VaultStorage.sol6.31 KB
- src/interfaces/IVault.sol5.46 KB
src/core/Vault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {VaultBase} from "./VaultBase.sol";
import {IVault} from "../interfaces/IVault.sol";
/// @title Vault
/// @notice Main vault contract for DEX deposits and withdrawals (UUPS upgradeable)
/// @dev Inherits AccessControlUpgradeable for role-based access control (4 roles)
contract Vault is
Initializable,
UUPSUpgradeable,
AccessControlUpgradeable,
ReentrancyGuardUpgradeable,
VaultBase
{
using SafeERC20 for IERC20;
// ========== Events ==========
// Deposit
event Deposit(address indexed user, address indexed token, uint256 tokenAmount, uint256 usdcAmount);
// Insurance fund deposit — operator/treasury tops up the insurance fund.
// The USDC joins the vault pool; off-chain accounting earmarks it as
// insurance-fund capital (wallet-service credits SYSTEM:INSURANCE_FUND on
// this event, idempotent by tx hash). Distinct from Deposit so the off-chain
// side never mistakes it for a user deposit.
event InsuranceFundDeposit(address indexed depositor, uint256 amount);
// Instant withdrawal (Tier1/2)
event Withdrawal(address indexed operator, address indexed user, uint256 amount);
// Large withdrawal (Tier3/4)
event LargeWithdrawalCreated(
bytes32 indexed withdrawalId,
address indexed user,
uint256 amount,
uint256 executeAfter,
uint256 approvalsNeeded
);
event LargeWithdrawalExecuted(bytes32 indexed withdrawalId, address indexed user, uint256 amount);
event WithdrawalCancelled(bytes32 indexed withdrawalId, address indexed user, uint256 amount);
/// Distinct from WithdrawalCancelled: nobody decided this, the clock ran out.
event WithdrawalExpired(bytes32 indexed withdrawalId, address indexed user, uint256 amount);
// Bridge
event BridgeOut(address indexed bridge, uint32 destChainId, uint256 amount);
event SweepDestinationUpdated(address indexed destination);
event Sweep(address indexed destination, uint256 amount, uint256 totalSwept);
// Admin
event Paused(address indexed account);
event Unpaused(address indexed account);
event EmergencyWithdraw(address indexed to, uint256 amount);
event TimelockParamsUpdated(
uint256 timelockThreshold, uint256 largeWithdrawThreshold, uint256 timelockDuration, uint256 withdrawalExpiry
);
event ApprovalRequirementsUpdated(uint256 tier3Approvals, uint256 tier4Approvals);
event AggregatorWhitelistUpdated(address indexed aggregator, bool allowed);
event BridgeWhitelistUpdated(address indexed bridge, bool allowed);
event OperatorDailyLimitUpdated(address indexed operator, uint256 limit);
event CumulativeLimitsUpdated(uint256 instantCap, uint256 decayRate, uint32 timelockT2, uint32 timelockT3, uint32 timelockT4);
event GlobalBreakerUpdated(uint256 globalCap, uint256 globalDecayRate);
event LimitExemptUpdated(address indexed account, bool exempt);
event BreakerTripped(address indexed by);
event BreakerReset(address indexed by);
// Rescue (SC-03)
event TokenRescued(address indexed token, address indexed to, uint256 amount);
event ETHRescued(address indexed to, uint256 amount);
// ========== Constructor ==========
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
// ========== Initializer ==========
/// @notice UUPS proxy initialization, replaces constructor
/// @param _usdc USDC token address
/// @param _guardian DEFAULT_ADMIN_ROLE holder (Gnosis Safe)
/// @param _timelockThreshold Tier1/2 upper bound
/// @param _largeWithdrawThreshold Tier3 upper bound
/// @param _timelockDuration On-chain timelock duration
/// @param _withdrawalExpiry Timelock withdrawal expiry
function initialize(
address _usdc,
address _guardian,
uint256 _timelockThreshold,
uint256 _largeWithdrawThreshold,
uint32 _timelockDuration,
uint32 _withdrawalExpiry
) external initializer {
__UUPSUpgradeable_init();
__AccessControl_init();
__ReentrancyGuard_init();
// USDC and the guardian are the two that cannot be deferred: a vault with
// no admin can never be configured, upgraded or rescued.
if (_usdc == address(0) || _guardian == address(0)) revert ZeroAddress();
usdc = IERC20(_usdc);
// Guardian gets DEFAULT_ADMIN_ROLE (manages all other roles)
_grantRole(DEFAULT_ADMIN_ROLE, _guardian);
timelockThreshold = _timelockThreshold;
largeWithdrawThreshold = _largeWithdrawThreshold;
timelockDuration = _timelockDuration;
withdrawalExpiry = _withdrawalExpiry;
tier3ApprovalsRequired = 2;
tier4ApprovalsRequired = 3;
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
}
// ========== Deposit Functions ==========
/// @notice Deposit ERC20 token (requires prior approve)
/// @dev Unified entry: if token == USDC, direct transfer; otherwise swap -> USDC
/// @param token Token contract address (pass USDC address for direct deposit)
/// @param amount Token amount
/// @param minUsdcOut Minimum USDC output (ignored for USDC direct deposit)
/// @param aggregator Whitelisted aggregator address (ignored for USDC, pass address(0))
/// @param swapData Aggregator calldata (ignored for USDC, pass empty bytes)
function depositToken(
address token,
uint256 amount,
uint256 minUsdcOut,
address aggregator,
bytes calldata swapData
) external whenNotPaused nonReentrant {
_depositToken(token, amount, minUsdcOut, aggregator, swapData);
}
/// @notice Deposit USDC directly into the insurance fund.
/// @dev USDC only (the insurance fund is USDC-denominated, no swap). The
/// funds join the vault pool; off-chain accounting credits the
/// SYSTEM:INSURANCE_FUND account via the InsuranceFundDeposit event, keyed
/// on the tx hash for idempotency. Permissionless — anyone may add backing
/// to the insurance fund (it can only increase protocol solvency).
/// @param amount USDC amount (6 decimals) to contribute to the insurance fund.
function depositInsuranceFund(uint256 amount) external whenNotPaused nonReentrant {
if (amount == 0) revert ZeroAmount();
usdc.safeTransferFrom(msg.sender, address(this), amount);
emit InsuranceFundDeposit(msg.sender, amount);
}
/// @notice Deposit ERC20 token with EIP-2612 permit (no prior approve needed)
/// @param token Token contract address
/// @param amount Token amount
/// @param minUsdcOut Minimum USDC output
/// @param aggregator Whitelisted aggregator address
/// @param swapData Aggregator calldata
/// @param deadline Permit deadline
/// @param v Permit signature v
/// @param r Permit signature r
/// @param s Permit signature s
function depositTokenWithPermit(
address token,
uint256 amount,
uint256 minUsdcOut,
address aggregator,
bytes calldata swapData,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external whenNotPaused nonReentrant {
// Permit authorization (try-catch: handles front-running and non-EIP2612 tokens)
try IERC20Permit(token).permit(msg.sender, address(this), amount, deadline, v, r, s) {} catch {}
_depositToken(token, amount, minUsdcOut, aggregator, swapData);
}
/// @dev Shared body of `depositToken` and `depositTokenWithPermit`. The two
/// entrypoints differ only in HOW the vault is authorised to pull the token
/// -- a prior `approve` versus an EIP-2612 `permit` -- and not at all in what
/// happens afterwards. They were once two copies of these same 21 statements,
/// which meant the SC-01 fee-on-transfer hardening had to be written twice and
/// nothing but reviewer attention kept the second copy in step. One body means
/// the next fix cannot land on one deposit path and miss the other.
/// @dev Carries no `whenNotPaused` / `nonReentrant` of its own by design: every
/// caller is an external function already holding both, and re-applying
/// `nonReentrant` here would revert on entry. Any future caller MUST hold them.
function _depositToken(
address token,
uint256 amount,
uint256 minUsdcOut,
address aggregator,
bytes calldata swapData
) internal {
if (amount == 0) revert ZeroAmount();
if (token == address(usdc)) {
// USDC direct deposit, skip swap
usdc.safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, address(usdc), amount, amount);
return;
}
// Other tokens -> swap -> USDC
if (!whitelistedAggregators[aggregator]) revert InvalidAggregator();
// 1. Collect token
uint256 tokenBalBefore = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
// SC-01 fix: Track actual received amount after transfer to handle fee-on-transfer tokens.
// For FoT tokens, the vault receives less than `amount`, so we must verify
// the aggregator consumed from the actual received tokens, not the nominal `amount`.
uint256 tokenBalAfterTransfer = IERC20(token).balanceOf(address(this));
uint256 tokenReceived = tokenBalAfterTransfer - tokenBalBefore;
// 2. Swap -> USDC
uint256 usdcBefore = usdc.balanceOf(address(this));
IERC20(token).forceApprove(aggregator, tokenReceived);
(bool success,) = aggregator.call(swapData);
if (!success) revert SwapFailed();
IERC20(token).forceApprove(aggregator, 0); // Clear residual approval
uint256 usdcReceived = usdc.balanceOf(address(this)) - usdcBefore;
// 3. Verify aggregator consumed at least some of the deposited tokens (SC-01 fix)
uint256 tokenBalAfter = IERC20(token).balanceOf(address(this));
if (tokenBalAfter >= tokenBalAfterTransfer) revert AggregatorTokenNotConsumed();
// 4. Slippage protection
if (usdcReceived < minUsdcOut) revert SlippageExceeded(usdcReceived, minUsdcOut);
emit Deposit(msg.sender, token, amount, usdcReceived);
}
/// @notice Deposit ETH (auto-swap -> USDC)
/// @param minUsdcOut Minimum USDC output
/// @param aggregator Whitelisted aggregator address
/// @param swapData Aggregator calldata
function depositETH(
uint256 minUsdcOut,
address aggregator,
bytes calldata swapData
) external payable whenNotPaused nonReentrant {
if (msg.value == 0) revert ZeroAmount();
if (!whitelistedAggregators[aggregator]) revert InvalidAggregator();
// SC-02 fix: Record ETH balance before aggregator call to verify consumption.
uint256 ethBalBefore = address(this).balance;
uint256 usdcBefore = usdc.balanceOf(address(this));
(bool success,) = aggregator.call{value: msg.value}(swapData);
if (!success) revert SwapFailed();
uint256 usdcReceived = usdc.balanceOf(address(this)) - usdcBefore;
// SC-02 fix: Verify the aggregator consumed the ETH (did not return it to the vault).
// After the call, the vault's ETH balance should be less than before (ETH was sent out).
if (address(this).balance >= ethBalBefore) revert AggregatorETHNotConsumed();
if (usdcReceived < minUsdcOut) revert SlippageExceeded(usdcReceived, minUsdcOut);
emit Deposit(msg.sender, address(0), msg.value, usdcReceived);
}
// ========== Withdrawal Functions ==========
/// @notice Instant USDC withdrawal (Tier1/2, executed by Operator)
/// @param user Recipient user address
/// @param amount USDC amount
function withdrawTo(address user, uint256 amount) external whenNotPaused nonReentrant {
_checkRole(WITHDRAW_OPERATOR_ROLE);
if (user == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
_checkOperatorDaily(msg.sender, amount);
_accrueGlobal(amount);
// Model A: instant path is gated by the per-recipient ROLLING cumulative,
// not the single amount — so structuring small withdrawals can't bypass the
// timelock/approval path. Over the cap -> forced to createLargeWithdrawal.
if (!limitExempt[user]) {
uint256 cum = _level(user) + amount;
if (cum > instantCap) revert UseTimelockWithdraw();
windowSpent[user] = Bucket(uint128(cum), uint64(block.timestamp)); // effects before transfer
}
usdc.safeTransfer(user, amount);
emit Withdrawal(msg.sender, user, amount);
}
// ========== Large Withdrawal Functions (Tier3/4) ==========
/// @notice Create large withdrawal request (on-chain timelock + multi-sig approval)
/// @param user Recipient user address
/// @param amount USDC amount
/// @return withdrawalId The withdrawal request ID
function createLargeWithdrawal(
address user,
uint256 amount
) external whenNotPaused nonReentrant returns (bytes32 withdrawalId) {
_checkRole(WITHDRAW_OPERATOR_ROLE);
if (user == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
// Model A: tier is driven by the per-recipient ROLLING cumulative, not the
// single amount. timelockThreshold==T2, largeWithdrawThreshold==T3.
uint256 cum = (limitExempt[user] ? 0 : _level(user)) + amount;
if (cum <= instantCap) revert UseSmallWithdraw(); // instant-eligible -> use withdrawTo
uint256 approvalsNeeded = cum > largeWithdrawThreshold ? tier4ApprovalsRequired
: cum > timelockThreshold ? tier3ApprovalsRequired
: 0; // (T1, T2] band -> timelock only, no approvals
uint32 tl = cum > largeWithdrawThreshold ? timelockT4
: cum > timelockThreshold ? timelockT3
: timelockT2;
if (tl == 0) tl = timelockDuration; // pre-config fallback (>= 1h)
uint256 nonce = withdrawalNonce++;
// SC-05 fix: Use block.prevrandao instead of block.timestamp for better entropy.
withdrawalId = keccak256(abi.encodePacked(user, amount, nonce, block.prevrandao));
LargeWithdrawal storage lw = largeWithdrawals[withdrawalId];
if (lw.user != address(0)) revert WithdrawalAlreadyExists();
lw.user = user;
lw.amount = amount;
lw.executeAfter = block.timestamp + tl;
lw.approvalsNeeded = approvalsNeeded;
lw.executed = false;
lw.cancelled = false;
// Reserve the cumulative immediately so concurrent creates can't under-count.
// Released again by cancelWithdraw / releaseExpired; an executed request keeps
// its reservation because the funds actually left.
//
// Only UNAPPROVED requests are charged to the window. The bucket exists to
// catch withdrawals that route around the approval gate by staying small,
// so its budget should be spent only by withdrawals that obtained no
// signatures: the instant path, and the (T1, T2] band which is timelock-only.
// A T3/T4 request already paid the higher price -- two or three approvers and
// a 24h timelock -- and charging it the anti-structuring budget as well bills
// one withdrawal twice. It also made recovery scale with size without bound:
// at a decayRate sized for instantCap, a 500k withdrawal blocked the instant
// path for fifty days and a 5M one for five hundred.
//
// What this preserves: the most an address can take with NO signatures is
// still timelockThreshold (instant cap, then the T2 band), after which it is
// forced into the approval path. That budget is untouched. What it gives up
// is escalation BETWEEN already-approved tiers -- splitting 1M into two 500k
// requests now costs four signatures over two days instead of three over one,
// so the split buys the splitter nothing.
if (!limitExempt[user] && approvalsNeeded == 0) {
windowSpent[user] = Bucket(uint128(cum), uint64(block.timestamp));
windowReserved[withdrawalId] = true;
}
emit LargeWithdrawalCreated(withdrawalId, user, amount, block.timestamp + tl, approvalsNeeded);
}
/// @notice Execute large withdrawal (timelock expired + off-chain approval signatures)
/// @dev Operator collects EIP-712 signatures from approvers and submits in one tx
/// @param withdrawalId Withdrawal ID
/// @param approvalSignatures Approver signature array (signer addresses must be ascending, no duplicates)
function executeLargeWithdraw(
bytes32 withdrawalId,
bytes[] calldata approvalSignatures
) external whenNotPaused nonReentrant {
_checkRole(WITHDRAW_OPERATOR_ROLE);
LargeWithdrawal storage lw = largeWithdrawals[withdrawalId];
if (lw.user == address(0)) revert WithdrawalNotFound();
if (lw.executed) revert WithdrawalAlreadyExecuted();
if (lw.cancelled) revert WithdrawalAlreadyCancelled();
if (block.timestamp < lw.executeAfter) {
revert TimelockNotExpired(lw.executeAfter, block.timestamp);
}
if (block.timestamp > lw.executeAfter + withdrawalExpiry) revert TimelockExpired();
// Verify approval signatures
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", _domainSeparator(), keccak256(abi.encode(APPROVE_TYPEHASH, withdrawalId)))
);
// SC-06 fix: Require ALL submitted signatures to be valid approvers in ascending order.
// The old "skip invalid" pattern could mask off-chain bugs where duplicate or
// malformed signatures are submitted, making it appear that enough approvals
// were collected when fewer unique signers actually approved.
uint256 validApprovals = 0;
address lastSigner = address(0);
for (uint256 i = 0; i < approvalSignatures.length; i++) {
address signer = _recover(digest, approvalSignatures[i]);
require(hasRole(APPROVER_ROLE, signer), "signer is not an approver");
require(signer > lastSigner, "signatures not in ascending signer order");
lastSigner = signer;
validApprovals++;
}
if (validApprovals < lw.approvalsNeeded) {
revert InsufficientApprovals(validApprovals, lw.approvalsNeeded);
}
// Execute
_accrueGlobal(lw.amount); // global breaker counts the actual disbursement
lw.executed = true;
usdc.safeTransfer(lw.user, lw.amount);
emit LargeWithdrawalExecuted(withdrawalId, lw.user, lw.amount);
}
/// @notice Cancel large withdrawal (Guardian only)
/// @param withdrawalId Withdrawal ID
function cancelWithdraw(bytes32 withdrawalId) external onlyRole(DEFAULT_ADMIN_ROLE) {
LargeWithdrawal storage lw = largeWithdrawals[withdrawalId];
if (lw.user == address(0)) revert WithdrawalNotFound();
if (lw.executed) revert WithdrawalAlreadyExecuted();
if (lw.cancelled) revert WithdrawalAlreadyCancelled();
lw.cancelled = true;
_releaseWindowReservation(withdrawalId, lw.user, lw.amount);
emit WithdrawalCancelled(withdrawalId, lw.user, lw.amount);
}
/// @notice Clear a request that can no longer be executed, returning the window
/// budget it reserved.
/// @dev Permissionless by design. Past `executeAfter + withdrawalExpiry` the
/// request is already dead to `executeLargeWithdraw`, so this moves no funds and
/// grants nothing -- it only stops a reservation for a withdrawal that never
/// happened from throttling the recipient indefinitely. Leaving that to an admin
/// call would make a user's own limits depend on ops remembering to tidy up.
function releaseExpired(bytes32 withdrawalId) external {
LargeWithdrawal storage lw = largeWithdrawals[withdrawalId];
if (lw.user == address(0)) revert WithdrawalNotFound();
if (lw.executed) revert WithdrawalAlreadyExecuted();
if (lw.cancelled) revert WithdrawalAlreadyCancelled();
if (block.timestamp <= lw.executeAfter + withdrawalExpiry) revert WithdrawalNotExpired();
lw.cancelled = true;
_releaseWindowReservation(withdrawalId, lw.user, lw.amount);
emit WithdrawalExpired(withdrawalId, lw.user, lw.amount);
}
/// @dev Return the window budget a request reserved, if it reserved any. The
/// per-request flag -- not `limitExempt[user]`, which can be flipped in the
/// meantime, nor the tier, which depends on a level that has since moved -- is
/// what says whether anything was taken. Latched off so a release cannot repeat.
function _releaseWindowReservation(bytes32 withdrawalId, address user, uint256 amount) private {
if (!windowReserved[withdrawalId]) return;
windowReserved[withdrawalId] = false;
uint256 level = _level(user);
uint256 remaining = level > amount ? level - amount : 0;
windowSpent[user] = Bucket(uint128(remaining), uint64(block.timestamp));
}
// ========== Rebalance Functions ==========
/// @notice Bridge out for cross-chain rebalancing (BRIDGE_OPERATOR_ROLE only)
/// @param bridge Whitelisted bridge contract address
/// @param amount USDC amount
/// @param destChainId Destination chain ID
/// @param bridgeData Bridge contract calldata
function bridgeOut(
address bridge,
uint256 amount,
uint32 destChainId,
bytes calldata bridgeData
) external whenNotPaused nonReentrant {
_checkRole(BRIDGE_OPERATOR_ROLE);
if (!whitelistedBridges[bridge]) revert InvalidBridge();
if (amount == 0) revert ZeroAmount();
_checkOperatorDaily(msg.sender, amount);
_accrueGlobal(amount); // rebalance outflow also counts toward the global breaker
uint256 balBefore = usdc.balanceOf(address(this));
usdc.forceApprove(bridge, amount);
(bool success,) = bridge.call(bridgeData);
if (!success) revert BridgeFailed();
usdc.forceApprove(bridge, 0);
uint256 balAfter = usdc.balanceOf(address(this));
// Verify balance decreased by exactly amount (C-02/H-05 fix)
if (balBefore - balAfter != amount) revert BridgeAmountMismatch();
emit BridgeOut(bridge, destChainId, amount);
}
// ========== Treasury sweep ==========
/// @notice Pin where sweeps go. Governance, not operations: this is the
/// same signature that could rotate every role, and it is the only
/// signature that can move the pin.
function setSweepDestination(address destination) external onlyRole(DEFAULT_ADMIN_ROLE) {
// The vault as its own destination would make sweep() a self-transfer
// that inflates totalSwept while moving nothing.
if (destination == address(0) || destination == address(this)) revert InvalidSweepDestination();
sweepDestination = destination;
emit SweepDestinationUpdated(destination);
}
/// @notice Move vault funds to the pinned destination. SWEEP_OPERATOR_ROLE
/// holds execution rights only: a stolen sweep key can do nothing
/// worse than sweep early, into the treasury's own account.
/// @dev Deliberately touches neither the recipient buckets, the operator
/// daily limits, nor the global breaker — those are sized for user
/// withdrawals, and with the destination pinned none of them adds
/// anything against theft. Contrast bridgeOut, whose destination is
/// any whitelisted bridge with arbitrary calldata, and which
/// therefore does accrue the breaker.
function sweep(uint256 amount) external whenNotPaused nonReentrant {
_checkRole(SWEEP_OPERATOR_ROLE);
address destination = sweepDestination;
if (destination == address(0)) revert SweepNotConfigured();
if (amount == 0) revert ZeroAmount();
totalSwept += amount;
usdc.safeTransfer(destination, amount);
emit Sweep(destination, amount, totalSwept);
}
// ========== Admin Functions ==========
/// @notice Pause all deposits and withdrawals
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
paused = true;
emit Paused(msg.sender);
}
/// @notice Unpause contract operations
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
paused = false;
emit Unpaused(msg.sender);
}
/// @notice Emergency withdraw USDC to safe address (must be paused first)
/// @param to Destination address
/// @param amount Amount to withdraw
function emergencyWithdraw(address to, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) whenPaused {
if (to == address(0)) revert ZeroAddress();
usdc.safeTransfer(to, amount);
emit EmergencyWithdraw(to, amount);
}
/// @notice SC-03 fix: Rescue non-USDC ERC20 tokens stuck in the vault (e.g., from partial swaps
/// or accidental transfers). Cannot be used to drain USDC -- use emergencyWithdraw for that.
/// @param token ERC20 token address (must not be USDC)
/// @param to Destination address
/// @param amount Amount to rescue
function rescueToken(address token, address to, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (token == address(usdc)) revert CannotRescueUSDC();
if (to == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
IERC20(token).safeTransfer(to, amount);
emit TokenRescued(token, to, amount);
}
/// @notice SC-03 fix: Rescue native ETH stuck in the vault (e.g., from failed ETH deposits).
/// @param to Destination address
/// @param amount Amount of ETH to rescue
function rescueETH(address payable to, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (to == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
(bool success,) = to.call{value: amount}("");
require(success, "ETH transfer failed");
emit ETHRescued(to, amount);
}
/// @notice Set timelock and threshold parameters
function setTimelockParams(
uint256 _timelockThreshold,
uint256 _largeWithdrawThreshold,
uint32 _timelockDuration,
uint32 _withdrawalExpiry
) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (_timelockDuration < 1 hours) revert TimelockTooShort();
if (_withdrawalExpiry < 1 days) revert ExpiryTooShort();
if (_timelockThreshold == 0) revert ZeroThreshold();
// SC-10 fix: Require largeWithdrawThreshold to be non-zero. A zero value would
// make all amounts above timelockThreshold require tier4 approval, which is
// almost certainly a misconfiguration rather than intended behavior.
if (_largeWithdrawThreshold == 0) revert ZeroThreshold();
// SC-07 fix: largeWithdrawThreshold must be >= timelockThreshold to preserve the
// tier ordering. Otherwise amounts between the two thresholds would use incorrect
// tier4 approval requirements instead of tier3.
if (_largeWithdrawThreshold < _timelockThreshold) revert LargeThresholdBelowTimelock();
// The ladder is configured by two setters; neither is meaningful alone.
// instantCap lives in setCumulativeLimits, so lowering the threshold here
// could silently swallow the whole timelock band.
if (instantCap >= _timelockThreshold) revert InstantCapAboveTimelockThreshold();
timelockThreshold = _timelockThreshold;
largeWithdrawThreshold = _largeWithdrawThreshold;
timelockDuration = _timelockDuration;
withdrawalExpiry = _withdrawalExpiry;
emit TimelockParamsUpdated(_timelockThreshold, _largeWithdrawThreshold, _timelockDuration, _withdrawalExpiry);
}
/// @notice Set approval requirements for Tier3/4
function setApprovalRequirements(
uint8 _tier3Approvals,
uint8 _tier4Approvals
) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (_tier3Approvals == 0 || _tier4Approvals == 0) revert ZeroApprovals();
if (_tier4Approvals < _tier3Approvals) revert InvalidApprovalOrder();
tier3ApprovalsRequired = _tier3Approvals;
tier4ApprovalsRequired = _tier4Approvals;
emit ApprovalRequirementsUpdated(_tier3Approvals, _tier4Approvals);
}
/// @notice Set aggregator whitelist status
function setAggregatorWhitelist(address aggregator, bool allowed) external onlyRole(DEFAULT_ADMIN_ROLE) {
whitelistedAggregators[aggregator] = allowed;
emit AggregatorWhitelistUpdated(aggregator, allowed);
}
/// @notice Set bridge whitelist status
function setBridgeWhitelist(address bridge, bool allowed) external onlyRole(DEFAULT_ADMIN_ROLE) {
whitelistedBridges[bridge] = allowed;
emit BridgeWhitelistUpdated(bridge, allowed);
}
/// @notice Set an operator's daily withdrawal limit.
/// @dev ZERO MEANS BLOCKED, NOT UNLIMITED. `_checkOperatorDaily` reverts with
/// `OperatorLimitNotSet` when the limit is 0, so an operator holding the role
/// but no limit cannot withdraw at all — the fail-closed posture that removes
/// the "role granted, limit not yet set" drain window. Two consequences worth
/// knowing before touching this in production:
/// - A newly granted operator is INERT until a positive limit is set here.
/// Granting the role alone does not enable withdrawals.
/// - Setting 0 is therefore how an operator is DE-AUTHORISED without
/// revoking its role, and it takes effect on the next call.
/// For an effectively-unlimited operator, set an explicitly large value.
/// @param op Operator address
/// @param limit Daily limit in USDC units; 0 blocks the operator entirely
function setOperatorDailyLimit(address op, uint256 limit) external onlyRole(DEFAULT_ADMIN_ROLE) {
operatorDailyLimit[op] = limit;
emit OperatorDailyLimitUpdated(op, limit);
}
// ========== Cumulative limit + circuit breaker config (Model A) ==========
/// @notice Configure the per-recipient rolling instant cap, decay rate and
/// per-tier on-chain timelock durations. Until set, instantCap==0 makes EVERY
/// withdrawal route through the timelock path (fail-closed, no drain risk).
function setCumulativeLimits(
uint256 _instantCap,
uint256 _decayRate,
uint32 _timelockT2,
uint32 _timelockT3,
uint32 _timelockT4
) external onlyRole(DEFAULT_ADMIN_ROLE) {
if (_instantCap == 0) revert ZeroThreshold();
// Mirror of the check in setTimelockParams: raising instantCap to or above
// the timelock threshold routes everything below it through the instant
// path, disabling timelock and approvals for that whole range.
if (_instantCap >= timelockThreshold) revert InstantCapAboveTimelockThreshold();
// A zero rate never drains the bucket, so every recipient's usage becomes
// permanent: past instantCap they lose the instant path for good, with no
// reset path short of limitExempt. Slow is a policy choice; never is not.
if (_decayRate == 0) revert ZeroDecayRate();
if (_timelockT2 < 1 hours || _timelockT3 < 1 hours || _timelockT4 < 1 hours) revert TimelockTooShort();
instantCap = _instantCap;
decayRate = _decayRate;
timelockT2 = _timelockT2;
timelockT3 = _timelockT3;
timelockT4 = _timelockT4;
emit CumulativeLimitsUpdated(_instantCap, _decayRate, _timelockT2, _timelockT3, _timelockT4);
}
/// @notice Configure the global net-outflow circuit breaker. globalCap == 0
/// disables it. Resets the running counter window to now.
function setGlobalBreaker(uint256 _globalCap, uint256 _globalDecayRate) external onlyRole(DEFAULT_ADMIN_ROLE) {
globalCap = _globalCap;
globalDecayRate = _globalDecayRate;
globalLastUpdate = block.timestamp;
emit GlobalBreakerUpdated(_globalCap, _globalDecayRate);
}
/// @notice Exempt a system/ops address from the per-recipient limit. Guardian
/// only; should point at a contract/multisig, not a hot wallet. Exempt
/// addresses still count toward the global breaker.
function setLimitExempt(address account, bool exempt) external onlyRole(DEFAULT_ADMIN_ROLE) {
limitExempt[account] = exempt;
emit LimitExemptUpdated(account, exempt);
}
/// @notice Manually trip the breaker — a withdrawal-only hard stop (Guardian).
/// Use on an off-chain anomaly alert; unlike pause() this leaves deposits open.
/// (The auto rate-limit cannot self-latch: its revert would roll back the flag.)
function tripBreaker() external onlyRole(DEFAULT_ADMIN_ROLE) {
breakerTripped = true;
emit BreakerTripped(msg.sender);
}
/// @notice Reset a tripped global breaker (Guardian only) after investigation.
function resetBreaker() external onlyRole(DEFAULT_ADMIN_ROLE) {
breakerTripped = false;
globalSpent = 0;
globalLastUpdate = block.timestamp;
emit BreakerReset(msg.sender);
}
// ========== View Functions ==========
/// @notice Predict how a withdrawal to `user` of `amount` would be routed, so
/// the operator/UI can pick the right entrypoint and show the expected handling.
/// @return instant true -> use withdrawTo; false -> use createLargeWithdrawal
function previewWithdrawal(address user, uint256 amount)
external
view
returns (bool instant, uint8 tier, uint32 timelock, uint256 approvalsNeeded)
{
uint256 cum = (limitExempt[user] ? 0 : _level(user)) + amount;
if (cum <= instantCap) return (true, 1, 0, 0);
if (cum > largeWithdrawThreshold) {
return (false, 4, timelockT4 == 0 ? timelockDuration : timelockT4, tier4ApprovalsRequired);
}
if (cum > timelockThreshold) {
return (false, 3, timelockT3 == 0 ? timelockDuration : timelockT3, tier3ApprovalsRequired);
}
return (false, 2, timelockT2 == 0 ? timelockDuration : timelockT2, 0);
}
/// @notice Query large withdrawal status
function getLargeWithdrawalInfo(bytes32 withdrawalId)
external
view
returns (address user, uint256 amount, uint256 executeAfter, uint256 approvalsNeeded, bool executed, bool cancelled)
{
LargeWithdrawal storage lw = largeWithdrawals[withdrawalId];
return (lw.user, lw.amount, lw.executeAfter, lw.approvalsNeeded, lw.executed, lw.cancelled);
}
/// @notice Query Vault USDC balance
function vaultBalance() external view returns (uint256) {
return usdc.balanceOf(address(this));
}
/// @notice Query Operator daily usage and limit
function getOperatorDailyUsage(address op)
external
view
returns (uint256 used, uint256 limit, uint256 resetTime)
{
limit = operatorDailyLimit[op];
DailyUsage storage usage = operatorDailyUsage[op];
if (block.timestamp >= usage.resetTime) {
return (0, limit, (block.timestamp / 1 days + 1) * 1 days);
}
return (usage.amount, limit, usage.resetTime);
}
// ========== Role Protection ==========
/// @notice Prevent renouncing DEFAULT_ADMIN_ROLE (M-01 fix)
function renounceRole(bytes32 role, address callerConfirmation) public virtual override {
if (role == DEFAULT_ADMIN_ROLE) revert CannotRenounceAdmin();
super.renounceRole(role, callerConfirmation);
}
// ========== EIP-712 Helpers ==========
/// @dev Returns the domain separator, recomputing if chain ID changed (C-03 fix)
function _domainSeparator() internal view returns (bytes32) {
if (block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
}
return _buildDomainSeparator();
}
/// @dev Build EIP-712 domain separator
function _buildDomainSeparator() internal view returns (bytes32) {
return keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("DEX Vault")),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
// ========== UUPS ==========
// SC-09 fix: Emit event so off-chain monitoring can detect upgrades.
event UpgradeAuthorized(address indexed newImplementation, address indexed authorizedBy);
/// @notice Authorize upgrade (Guardian / DEFAULT_ADMIN_ROLE only)
/// SC-09 fix: Emit an event with the new implementation address for off-chain monitoring.
/// A timelock (e.g., OpenZeppelin TimelockController as admin) is recommended for production.
function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) {
emit UpgradeAuthorized(newImplementation, msg.sender);
}
/// @notice Receive ETH
receive() external payable {}
}
lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC1967-compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
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-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.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 you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// 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;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* 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;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
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) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* 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[EIP 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);
}
src/core/VaultBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {VaultStorage} from "./VaultStorage.sol";
/// @title VaultBase
/// @notice Modifiers and internal helpers for the Vault contract
abstract contract VaultBase is VaultStorage {
// ========== Modifiers ==========
modifier whenNotPaused() {
if (paused) revert ContractPaused();
_;
}
modifier whenPaused() {
if (!paused) revert ContractNotPaused();
_;
}
// ========== Internal Helpers ==========
/// @dev Check and update Operator daily usage (resets at UTC 00:00).
/// Fail-closed: an operator with no explicit limit (0) CANNOT withdraw. This
/// removes the "role granted but limit not yet set = unlimited drain" window
/// between grantRole and setOperatorDailyLimit (e.g. a wrong or compromised
/// operator address). To operate, a positive limit MUST be set first; for an
/// effectively-unlimited operator set an explicitly large value.
/// (Reverses the prior SC-04 limit==0 bypass — pending re-audit.)
function _checkOperatorDaily(address op, uint256 amount) internal {
uint256 limit = operatorDailyLimit[op];
if (limit == 0) revert OperatorLimitNotSet(op);
DailyUsage storage usage = operatorDailyUsage[op];
if (block.timestamp >= usage.resetTime) {
usage.amount = 0;
usage.resetTime = (block.timestamp / 1 days + 1) * 1 days;
}
uint256 newAmount = usage.amount + amount;
if (newAmount > limit) revert OperatorDailyLimitExceeded(usage.amount, limit);
usage.amount = newAmount;
}
/// @dev Current rolling-window level for a recipient (leaky-bucket decay).
function _level(address to) internal view returns (uint256) {
Bucket memory b = windowSpent[to];
if (b.spent == 0) return 0;
uint256 decay = decayRate * (block.timestamp - b.lastUpdate);
return b.spent > decay ? b.spent - decay : 0;
}
/// @dev Global net-outflow circuit breaker. Called on every actual outflow
/// (withdrawTo / executeLargeWithdraw / bridgeOut). globalCap == 0 disables it.
/// On breach it latches `breakerTripped` and reverts ALL outflow until a
/// guardian resets — the last-resort backstop for operator/key compromise.
function _accrueGlobal(uint256 amount) internal {
if (globalCap == 0) return; // disabled
if (breakerTripped) revert CircuitBreakerTripped(); // manual guardian kill-switch
uint256 decay = globalDecayRate * (block.timestamp - globalLastUpdate);
uint256 decayed = globalSpent > decay ? globalSpent - decay : 0;
uint256 cum = decayed + amount;
// Soft rolling rate-limit: reject over-cap (auto-recovers as the bucket
// decays). A self-latching AUTO trip is impossible here — the revert would
// roll back the latch — so the hard stop is the guardian's manual
// tripBreaker() / pause() instead.
if (cum > globalCap) revert GlobalOutflowCapExceeded(cum, globalCap);
globalSpent = cum;
globalLastUpdate = block.timestamp;
}
/// @dev Recover signer address from EIP-712 signature
function _recover(bytes32 digest, bytes calldata signature) internal pure returns (address) {
if (signature.length != 65) return address(0);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 32))
v := byte(0, calldataload(add(signature.offset, 64)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) return address(0);
return ecrecover(digest, v, r, s);
}
// ========== Errors ==========
// General
error ZeroAmount();
error ZeroAddress();
error InvalidSweepDestination();
error SweepNotConfigured();
error ContractPaused();
error ContractNotPaused();
// Tier configuration
/// The tier ladder must stay strictly ordered: instantCap < timelockThreshold.
/// At equality the (T1, T2] band is empty and everything up to timelockThreshold
/// leaves through the INSTANT path with no timelock at all -- a fail-open
/// collapse, unlike an empty T3 band which merely escalates to T4.
error InstantCapAboveTimelockThreshold();
/// A zero decay rate freezes every recipient's usage permanently.
error ZeroDecayRate();
/// releaseExpired called on a request that can still be executed.
error WithdrawalNotExpired();
// Deposit
error InvalidAggregator();
error SlippageExceeded(uint256 received, uint256 minimum);
error SwapFailed();
// Withdrawal
error UseTimelockWithdraw();
error UseSmallWithdraw();
error OperatorDailyLimitExceeded(uint256 used, uint256 limit);
// Fail-closed: operator has no daily limit configured (limit == 0) → blocked.
error OperatorLimitNotSet(address operator);
// Timelock
error WithdrawalNotFound();
error WithdrawalAlreadyExists();
error WithdrawalAlreadyExecuted();
error WithdrawalAlreadyCancelled();
error TimelockNotExpired(uint256 executeAfter, uint256 currentTime);
error TimelockExpired();
error InsufficientApprovals(uint256 have, uint256 need);
// Bridge
error InvalidBridge();
error BridgeFailed();
error BridgeAmountMismatch();
// Admin validation
error ZeroApprovals();
error InvalidApprovalOrder();
error TimelockTooShort();
error ExpiryTooShort();
error ZeroThreshold();
error CannotRenounceAdmin();
// Aggregator
error AggregatorTokenNotConsumed();
error AggregatorETHNotConsumed();
// SC-07: largeWithdrawThreshold must be >= timelockThreshold
error LargeThresholdBelowTimelock();
// Cumulative limit / global circuit breaker (Model A)
error CircuitBreakerTripped(); // manual guardian trip active
error GlobalOutflowCapExceeded(uint256 attempted, uint256 cap); // soft rolling rate-limit breach
// Rescue
error CannotRescueUSDC();
}
src/core/VaultStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title VaultStorage
/// @notice All state variables centralized for stable storage layout across upgrades
abstract contract VaultStorage {
// ========== Role Constants (AccessControl 4 roles) ==========
// DEFAULT_ADMIN_ROLE = 0x00 -> Guardian (Gnosis Safe), manages all roles
bytes32 public constant WITHDRAW_OPERATOR_ROLE = keccak256("WITHDRAW_OPERATOR_ROLE");
bytes32 public constant BRIDGE_OPERATOR_ROLE = keccak256("BRIDGE_OPERATOR_ROLE");
bytes32 public constant APPROVER_ROLE = keccak256("APPROVER_ROLE");
/// Execution rights over sweep() and nothing else: it can move funds only
/// to the admin-pinned sweepDestination, so the key can run hot.
bytes32 public constant SWEEP_OPERATOR_ROLE = keccak256("SWEEP_OPERATOR_ROLE");
// ========== Token ==========
IERC20 public usdc;
// ========== Withdrawal Tier Thresholds ==========
/// @dev Tier1: amount <= timelockThreshold -> withdrawTo() instant
/// Tier2: off-chain timelock (backend timelock_until), contract still uses withdrawTo()
/// Tier3: timelockThreshold < amount <= largeWithdrawThreshold -> createLargeWithdrawal()
/// Tier4: amount > largeWithdrawThreshold -> createLargeWithdrawal() (higher approval)
uint256 public timelockThreshold;
uint256 public largeWithdrawThreshold;
// ========== Timelock + Approvals (compact packing, 1 slot) ==========
uint32 public timelockDuration;
uint32 public withdrawalExpiry;
uint8 public tier3ApprovalsRequired;
uint8 public tier4ApprovalsRequired;
// ========== Operator Daily Limits ==========
mapping(address => uint256) public operatorDailyLimit;
mapping(address => DailyUsage) internal operatorDailyUsage;
// ========== Large Withdrawals (Tier3/4) ==========
mapping(bytes32 => LargeWithdrawal) public largeWithdrawals;
// ========== Whitelists ==========
mapping(address => bool) public whitelistedAggregators;
mapping(address => bool) public whitelistedBridges;
// ========== State ==========
bool public paused;
uint256 public withdrawalNonce; // auto-increment for unique withdrawalId
// ========== EIP-712 (only for approval signature verification) ==========
bytes32 internal _cachedDomainSeparator;
uint256 internal _cachedChainId;
bytes32 internal constant APPROVE_TYPEHASH = keccak256("ApproveWithdrawal(bytes32 withdrawalId)");
// ========== Structs ==========
struct LargeWithdrawal {
address user;
uint256 amount;
uint256 executeAfter;
uint256 approvalsNeeded;
bool executed;
bool cancelled;
}
struct DailyUsage {
uint256 amount;
uint256 resetTime;
}
// ========== Cumulative per-address withdrawal limits (Model A) ==========
/// @dev Per-recipient rolling counter (leaky bucket) of UNAPPROVED outflow --
/// the instant path plus the timelock-only (T1, T2] band. Withdrawals that
/// obtained approver signatures are gated by those signatures and are not
/// charged here. The CONTRACT itself escalates over-window addresses to the
/// timelock+approval path, so even a compromised operator cannot bypass
/// approval by structuring small withdrawals. Because everything counted here
/// really was drawn from the decayRate budget, recovery time is always exactly
/// (amount spent / decayRate) and is bounded by timelockThreshold / decayRate.
/// approvalThreshold(T2)==timelockThreshold, guardianThreshold(T3)==largeWithdrawThreshold
/// (reused slots, already 100k/500k). instantCap(T1) is new.
struct Bucket { uint128 spent; uint64 lastUpdate; }
mapping(address => Bucket) internal windowSpent;
uint256 public instantCap; // T1: cumAfter <= this -> instant withdrawTo
uint256 public decayRate; // raw USDC units decayed per second
uint32 public timelockT2; // (T1, T2] -> timelock only
uint32 public timelockT3; // (T2, T3] -> timelock + tier3 approvals
uint32 public timelockT4; // > T3 -> timelock + tier4 (guardian)
mapping(address => bool) public limitExempt; // system/ops addresses (guardian-set)
// ========== Global net-outflow circuit breaker ==========
uint256 public globalSpent;
uint256 public globalLastUpdate;
uint256 public globalDecayRate;
uint256 public globalCap; // 0 = breaker disabled
bool public breakerTripped;
// ========== Treasury sweep ==========
/// Admin-pinned; sweep() can pay only here. address(0) = sweeps disabled.
address public sweepDestination;
/// Cumulative amount ever swept. Never reset, including across destination
/// changes: with totalDeposited/totalWithdrawn-style figures it completes
/// the identity a reconciler checks the balance against.
uint256 public totalSwept;
// ========== Large-withdrawal window reservations ==========
/// @dev Whether a given large-withdrawal request consumed window budget when
/// it was created. `createLargeWithdrawal` reserves only for a non-exempt
/// recipient AND only when the request needs no approvals, and both of those
/// inputs move: `limitExempt` can be flipped, and the tier is derived from a
/// level that changes with every later withdrawal. Neither can be re-derived at
/// release time, so the decision is recorded here when it is made. Records
/// created before this field existed read false and keep the old no-release
/// behaviour -- the fail-safe direction: never hand back budget never taken.
mapping(bytes32 => bool) internal windowReserved;
// ========== Storage Gap (upgrade reserved) ==========
/// @dev Rebased to 50 while the contract is still pre-mainnet. Nothing is
/// declared after VaultStorage -- VaultBase and Vault hold no state of their
/// own -- so widening the gap moves no existing slot; it only reserves more
/// empty ones. That freedom ends at the first mainnet deployment: from then
/// on every variable added above must take one slot OUT of this count, so the
/// total footprint stays fixed.
uint256[50] private __gap;
}
src/interfaces/IVault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @title IVault
/// @notice Interface for the Vault contract
interface IVault {
// ========== Structs ==========
struct LargeWithdrawal {
address user;
uint256 amount;
uint256 executeAfter;
uint256 approvalsNeeded;
bool executed;
bool cancelled;
}
struct DailyUsage {
uint256 amount;
uint256 resetTime;
}
// ========== Events ==========
event Deposit(address indexed user, address indexed token, uint256 tokenAmount, uint256 usdcAmount);
event Withdrawal(address indexed operator, address indexed user, uint256 amount);
event LargeWithdrawalCreated(
bytes32 indexed withdrawalId,
address indexed user,
uint256 amount,
uint256 executeAfter,
uint256 approvalsNeeded
);
event LargeWithdrawalExecuted(bytes32 indexed withdrawalId, address indexed user, uint256 amount);
event WithdrawalCancelled(bytes32 indexed withdrawalId, address indexed user, uint256 amount);
event BridgeOut(address indexed bridge, uint32 destChainId, uint256 amount);
event Paused(address indexed account);
event Unpaused(address indexed account);
event EmergencyWithdraw(address indexed to, uint256 amount);
event TimelockParamsUpdated(
uint256 timelockThreshold, uint256 largeWithdrawThreshold, uint256 timelockDuration, uint256 withdrawalExpiry
);
event ApprovalRequirementsUpdated(uint256 tier3Approvals, uint256 tier4Approvals);
event AggregatorWhitelistUpdated(address indexed aggregator, bool allowed);
event BridgeWhitelistUpdated(address indexed bridge, bool allowed);
event OperatorDailyLimitUpdated(address indexed operator, uint256 limit);
event TokenRescued(address indexed token, address indexed to, uint256 amount);
event ETHRescued(address indexed to, uint256 amount);
// ========== Deposit Functions ==========
function depositToken(
address token,
uint256 amount,
uint256 minUsdcOut,
address aggregator,
bytes calldata swapData
) external;
function depositTokenWithPermit(
address token,
uint256 amount,
uint256 minUsdcOut,
address aggregator,
bytes calldata swapData,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function depositETH(uint256 minUsdcOut, address aggregator, bytes calldata swapData) external payable;
// ========== Withdrawal Functions ==========
function withdrawTo(address user, uint256 amount) external;
function createLargeWithdrawal(address user, uint256 amount) external returns (bytes32 withdrawalId);
function executeLargeWithdraw(bytes32 withdrawalId, bytes[] calldata approvalSignatures) external;
function cancelWithdraw(bytes32 withdrawalId) external;
// ========== Rebalance Functions ==========
function bridgeOut(address bridge, uint256 amount, uint32 destChainId, bytes calldata bridgeData) external;
// ========== Admin Functions ==========
function pause() external;
function unpause() external;
function emergencyWithdraw(address to, uint256 amount) external;
function rescueToken(address token, address to, uint256 amount) external;
function rescueETH(address payable to, uint256 amount) external;
function setTimelockParams(
uint256 _timelockThreshold,
uint256 _largeWithdrawThreshold,
uint32 _timelockDuration,
uint32 _withdrawalExpiry
) external;
function setApprovalRequirements(uint8 _tier3Approvals, uint8 _tier4Approvals) external;
function setAggregatorWhitelist(address aggregator, bool allowed) external;
function setBridgeWhitelist(address bridge, bool allowed) external;
/// @notice Pin where sweeps go (admin only).
function setSweepDestination(address destination) external;
/// @notice Move vault funds to the pinned destination (sweep operator only).
function sweep(uint256 amount) external;
function setOperatorDailyLimit(address op, uint256 limit) external;
// ========== View Functions ==========
function usdc() external view returns (address);
function timelockThreshold() external view returns (uint256);
function largeWithdrawThreshold() external view returns (uint256);
function timelockDuration() external view returns (uint32);
function withdrawalExpiry() external view returns (uint32);
function tier3ApprovalsRequired() external view returns (uint8);
function tier4ApprovalsRequired() external view returns (uint8);
function operatorDailyLimit(address op) external view returns (uint256);
function whitelistedAggregators(address aggregator) external view returns (bool);
function whitelistedBridges(address bridge) external view returns (bool);
function paused() external view returns (bool);
function getLargeWithdrawalInfo(bytes32 withdrawalId)
external
view
returns (
address user,
uint256 amount,
uint256 executeAfter,
uint256 approvalsNeeded,
bool executed,
bool cancelled
);
function vaultBalance() external view returns (uint256);
function getOperatorDailyUsage(address op)
external
view
returns (uint256 used, uint256 limit, uint256 resetTime);
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"forge-std/=lib/forge-std/src/",
"ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.