Source Code
Overview
MON Balance
MON Value
$0.00| Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
Advanced mode:
| Parent Transaction Hash | Block | From | To | |||
|---|---|---|---|---|---|---|
| 37059867 | 68 days ago | Contract Creation | 0 MON |
Loading...
Loading
Contract Name:
RedeemQueue
Compiler Version
v0.8.25+commit.b61c2a91
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "../interfaces/queues/IRedeemQueue.sol";
import "../libraries/TransferLibrary.sol";
import "./Queue.sol";
contract RedeemQueue is IRedeemQueue, Queue {
using EnumerableMap for EnumerableMap.UintToUintMap;
using Checkpoints for Checkpoints.Trace224;
bytes32 private immutable _redeemQueueStorageSlot;
constructor(string memory name_, uint256 version_) Queue(name_, version_) {
_redeemQueueStorageSlot = SlotLibrary.getSlot("RedeemQueue", name_, version_);
}
// View functions
/// @inheritdoc IRedeemQueue
function getState() public view returns (uint256, uint256, uint256, uint256) {
RedeemQueueStorage storage $ = _redeemQueueStorage();
return ($.batchIterator, $.batches.length, $.totalDemandAssets, $.totalPendingShares);
}
/// @inheritdoc IRedeemQueue
function batchAt(uint256 index) public view returns (uint256 assets, uint256 shares) {
RedeemQueueStorage storage $ = _redeemQueueStorage();
if (index >= $.batches.length) {
return (0, 0);
}
Batch storage batch = $.batches[index];
return (batch.assets, batch.shares);
}
/// @inheritdoc IRedeemQueue
function requestsOf(address account, uint256 offset, uint256 limit)
public
view
returns (Request[] memory requests)
{
RedeemQueueStorage storage $ = _redeemQueueStorage();
EnumerableMap.UintToUintMap storage callerRequests = $.requestsOf[account];
uint256 length = callerRequests.length();
if (length <= offset) {
return new Request[](0);
}
limit = Math.min(length - offset, limit);
requests = new Request[](limit);
uint256 batchIterator = $.batchIterator;
(, uint32 latestEligibleTimestamp,) = $.prices.latestCheckpoint();
Batch memory batch;
for (uint256 i = 0; i < limit; i++) {
(uint256 timestamp, uint256 shares) = callerRequests.at(i + offset);
requests[i].timestamp = timestamp;
requests[i].shares = shares;
if (timestamp > latestEligibleTimestamp) {
continue;
}
uint256 index = $.prices.lowerLookup(uint32(timestamp));
batch = $.batches[index];
requests[i].assets = Math.mulDiv(shares, batch.assets, batch.shares);
requests[i].isClaimable = index < batchIterator;
}
}
/// @inheritdoc IQueue
function canBeRemoved() external view returns (bool) {
RedeemQueueStorage storage $ = _redeemQueueStorage();
return _timestamps().length() == $.handledIndices && $.batchIterator == $.batches.length;
}
// Mutable functions
receive() external payable {}
/// @inheritdoc IFactoryEntity
function initialize(bytes calldata data) external initializer {
(address asset_, address shareModule_,) = abi.decode(data, (address, address, bytes));
__Queue_init(asset_, shareModule_);
emit Initialized(data);
}
/// @inheritdoc IRedeemQueue
function redeem(uint256 shares) external nonReentrant {
if (shares == 0) {
revert ZeroValue();
}
address caller = _msgSender();
address vault_ = vault();
if (IShareModule(vault_).isPausedQueue(address(this))) {
revert QueuePaused();
}
IShareManager shareManager_ = IShareManager(IShareModule(vault_).shareManager());
shareManager_.lock(caller, shares);
IFeeManager feeManager_ = IShareModule(vault_).feeManager();
address feeRecipient_ = feeManager_.feeRecipient();
if (caller != feeRecipient_) {
uint256 fees = feeManager_.calculateRedeemFee(shares);
if (fees > 0) {
shareManager_.mint(feeRecipient_, fees);
shares -= fees;
}
}
RedeemQueueStorage storage $ = _redeemQueueStorage();
uint32 timestamp = uint32(block.timestamp);
Checkpoints.Trace224 storage timestamps = _timestamps();
uint256 index = timestamps.length();
(, uint32 latestTimestamp,) = timestamps.latestCheckpoint();
if (latestTimestamp < timestamp) {
timestamps.push(timestamp, uint224(index));
$.prefixSum[index] = shares + $.prefixSum[index - 1];
} else {
$.prefixSum[--index] += shares;
}
EnumerableMap.UintToUintMap storage callerRequests = $.requestsOf[caller];
(, uint256 pendingShares) = callerRequests.tryGet(timestamp);
callerRequests.set(timestamp, pendingShares + shares);
$.totalPendingShares += shares;
emit RedeemRequested(caller, shares, timestamp);
}
/// @inheritdoc IRedeemQueue
function claim(address receiver, uint32[] calldata timestamps) external nonReentrant returns (uint256 assets) {
RedeemQueueStorage storage $ = _redeemQueueStorage();
address account = _msgSender();
EnumerableMap.UintToUintMap storage callerRequests = $.requestsOf[account];
(, uint32 latestReportTimestamp,) = $.prices.latestCheckpoint();
if (latestReportTimestamp == 0) {
return 0;
}
uint256 batchIterator = $.batchIterator;
for (uint256 i = 0; i < timestamps.length; i++) {
uint32 timestamp = timestamps[i];
if (timestamp > latestReportTimestamp) {
continue;
}
(bool hasRequest, uint256 shares) = callerRequests.tryGet(timestamp);
if (!hasRequest) {
continue;
}
if (shares != 0) {
uint256 index = $.prices.lowerLookup(timestamp);
if (index >= batchIterator) {
continue;
}
Batch storage batch = $.batches[index];
uint256 assets_ = Math.mulDiv(shares, batch.assets, batch.shares);
assets += assets_;
batch.assets -= assets_;
batch.shares -= shares;
emit RedeemRequestClaimed(account, receiver, assets_, timestamp);
}
callerRequests.remove(timestamp);
}
TransferLibrary.sendAssets(asset(), receiver, assets);
}
/// @inheritdoc IRedeemQueue
function handleBatches(uint256 batches) external nonReentrant returns (uint256 counter) {
RedeemQueueStorage storage $ = _redeemQueueStorage();
uint256 iterator_ = $.batchIterator;
uint256 length = $.batches.length;
if (iterator_ >= length || batches == 0) {
return 0;
}
batches = Math.min(batches, length - iterator_);
IShareModule vault_ = IShareModule(vault());
uint256 liquidAssets = vault_.getLiquidAssets();
uint256 demand = 0;
uint256 shares = 0;
Batch memory batch;
for (uint256 i = 0; i < batches; i++) {
batch = $.batches[iterator_ + i];
if (demand + batch.assets > liquidAssets) {
break;
}
demand += batch.assets;
shares += batch.shares;
counter++;
}
if (counter > 0) {
if (demand > 0) {
vault_.callHook(demand);
IVaultModule(address(vault_)).riskManager().modifyVaultBalance(asset(), -int256(uint256(demand)));
$.totalDemandAssets -= demand;
}
$.batchIterator += counter;
emit RedeemRequestsHandled(counter, demand);
}
}
// Internal functions
function _handleReport(uint224 priceD18, uint32 timestamp) internal override {
RedeemQueueStorage storage $ = _redeemQueueStorage();
Checkpoints.Trace224 storage timestamps = _timestamps();
(, uint32 latestTimestamp, uint224 latestIndex) = timestamps.latestCheckpoint();
uint256 latestEligibleIndex;
if (latestTimestamp <= timestamp) {
latestEligibleIndex = latestIndex;
} else {
latestEligibleIndex = uint256(timestamps.upperLookupRecent(timestamp));
if (latestEligibleIndex == 0 && timestamp < timestamps.at(0)._key) {
return;
}
}
uint256 handledIndices_ = $.handledIndices;
if (latestEligibleIndex < handledIndices_) {
return;
}
uint256 shares =
$.prefixSum[latestEligibleIndex] - (handledIndices_ == 0 ? 0 : $.prefixSum[handledIndices_ - 1]);
$.handledIndices = latestEligibleIndex + 1;
if (shares == 0) {
return;
}
uint256 index = $.prices.length();
$.totalPendingShares -= shares;
IShareManager shareManager_ = IShareModule(vault()).shareManager();
shareManager_.burn(address(shareManager_), shares);
$.prices.push(timestamp, uint224(index));
uint256 assets_ = Math.mulDiv(shares, 1 ether, priceD18);
$.batches.push(Batch(assets_, shares));
$.totalDemandAssets += assets_;
}
function _redeemQueueStorage() internal view returns (RedeemQueueStorage storage $) {
bytes32 slot = _redeemQueueStorageSlot;
assembly {
$.slot := slot
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/structs/Checkpoints.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol";
import "../modules/IVaultModule.sol";
import "./IQueue.sol";
/// @title IRedeemQueue
/// @notice Interface for redeem queues that manage time-delayed redemptions of vault shares into underlying assets.
/// @dev Handles request creation, price-based batch processing, and asynchronous liquidity settlement.
///
/// # Overview
/// A `RedeemQueue` allows users to request conversion of their vault shares into assets. It introduces a delay enforced by an oracle (`redeemInterval`), and ensures the following invariants:
/// 1. Each request is defined by `(shares, timestamp)`.
/// 2. Requests are **not cancellable**, to prevent griefing (e.g., by requesting redemption and cancelling after unstaking starts).
/// 3. Users may have multiple independent redemption requests.
///
/// Once an oracle report is submitted at `reportTimestamp`, it processes all requests with `timestamp <= reportTimestamp - redeemInterval`, converting vault shares into asset values using the reported price.
///
/// # Liquidity Processing (Two-Stage)
/// Redemption handling is decoupled from actual asset movement to allow asynchronous liquidity management:
/// - After a request is created, vault curators may pull liquidity from external protocols.
/// - Once oracle report is submitted and enough liquidity is available, vault curator (or any other actor) calls `handleReport()` on the redeem queue.
/// - This pulls required amount of assets from the Vault (and Subvaults) processing created redemption requests.
///
/// # Scalability Approach
/// Unlike deposits, redemption requests are never cancelled. This allows the system to use a **prefix sum array** to track requests over time.
///
/// # Redemption Processing
/// - When a user redeems `amount` shares at time `T`, the system records `prefixSum[T] += shares`.
/// - At oracle report time `reportTimestamp`, all requests with `timestamp <= reportTimestamp - redeemInterval` are marked as processed.
/// - Curator pushes the required assets to the queue by managin vault liquidity and calling `handleBatches` function afterwards.
/// - Users call `claim(receiver, timestamps[])` to redeem their processed shares for assets.
interface IRedeemQueue is IQueue {
/// @notice Redemption request metadata for a user.
/// @dev Represents a single request to convert vault shares into underlying assets.
struct Request {
/// @notice Timestamp when the redemption request was submitted.
/// @dev Determines eligibility for processing based on oracle report timing and `redeemInterval`.
uint256 timestamp;
/// @notice Amount of vault shares submitted for redemption.
uint256 shares;
/// @notice Whether the request has been processed and is now claimable.
/// @dev Set to `true` after liquidity has been allocated via `handleBatches`.
bool isClaimable;
/// @notice Amount of assets that can be claimed by the user.
/// @dev Calculated and stored after a matching oracle report has been processed via `handleReport`.
uint256 assets;
}
/// @notice Redemption batch result with total matched shares and corresponding assets.
/// @dev Represents a single price batch where multiple redemption requests are settled at the same oracle-reported price.
struct Batch {
/// @notice Total amount of assets allocated for this redemption batch.
/// @dev Calculated during `handleReport` using the reported price and total matched shares.
uint256 assets;
/// @notice Total number of vault shares handled in this batch.
/// @dev Includes all user requests processed at the same oracle report.
uint256 shares;
}
/// @notice Storage layout for the RedeemQueue contract.
/// @dev Tracks redemption request state, oracle-based batch settlements, and pricing checkpoints.
struct RedeemQueueStorage {
/// @notice Number of timestamp-based redemption checkpoints that have been processed.
/// @dev Ensures sequential handling of oracle reports.
uint256 handledIndices;
/// @notice Number of claimable batches.
/// @dev Increments as batches are handled via `handleBatches` and become claimable.
uint256 batchIterator;
/// @notice Total amount of assets needed to fulfill all currently batched redemption requests.
/// @dev Equals the sum of `batches[i].assets` for all indices `i` such that `batchIterator <= i < batches.length`.
uint256 totalDemandAssets;
/// @notice Total shares from redemption requests that are not yet claimable.
/// @dev Increases when users create new redemption requests and decreases after they are processed via `handleBatches`.
uint256 totalPendingShares;
/// @notice Mapping of redemption requests per user.
/// @dev Each user maps to a set of `(timestamp => shares)` representing open requests.
mapping(address => EnumerableMap.UintToUintMap) requestsOf;
/// @notice Prefix sum of requested shares grouped by timestamp.
/// @dev Enables efficient calculation of total demand in a redemption window.
mapping(uint256 => uint256) prefixSum;
/// @notice Batches created from processed oracle reports.
/// @dev Each batch maps total requested shares to the equivalent amount of assets.
Batch[] batches;
/// @notice Historical oracle pricing checkpoints for batch processing.
/// @dev Associates report timestamps with their respective batch index.
Checkpoints.Trace224 prices;
}
/// @notice Returns a paginated list of redemption requests for a user.
/// @dev Returned requests can be in one of the following states:
/// - Pending: Awaiting processing by an oracle report.
/// - Handled: Processed by oracle report but not yet claimable (assets not yet pulled from the Vault).
/// - Claimable: Processed and fully settled; assets are ready to be claimed.
/// @param account Address of the user.
/// @param offset Starting index for pagination.
/// @param limit Maximum number of requests to return.
/// @return requests Array of user's redemption requests with full status metadata.
function requestsOf(address account, uint256 offset, uint256 limit)
external
view
returns (Request[] memory requests);
/// @notice Returns assets and shares for a redemption batch at a given index.
/// @param batchIndex Index of the redemption batch.
/// @return assets Total assets corresponding to this batch.
/// @return shares Total shares redeemed in this batch.
function batchAt(uint256 batchIndex) external view returns (uint256 assets, uint256 shares);
/// @notice Returns the current state of the redeem queue system.
/// @return batchIterator Current index of the batch iterator (i.e., next batch to process).
/// @return batches Total number of recorded redemption batches.
/// @return totalDemandAssets Aggregate amount of redeem requests (in assets) awaiting fulfillment.
/// @return totalPendingShares Total number of shares across all redemption requests that are not yet claimable.
function getState()
external
view
returns (uint256 batchIterator, uint256 batches, uint256 totalDemandAssets, uint256 totalPendingShares);
/// @notice Initiates a new redemption by queuing shares for future asset claims.
/// @param shares Amount of shares to redeem.
function redeem(uint256 shares) external;
/// @notice Claims redemption requests for a user based on the provided timestamps.
/// @dev A request is successfully claimed only if:
/// - The associated timestamp has been processed by an oracle report, and
/// - The corresponding batch has been settled via `handleBatches`.
///
/// The function is idempotent — requests that are already claimed or not yet eligible are skipped without reverting.
///
/// @param account Address of the user claiming the redemptions.
/// @param timestamps List of request timestamps to claim.
/// @return assets Total amount of assets successfully claimed.
function claim(address account, uint32[] calldata timestamps) external returns (uint256 assets);
/// @notice Processes pending redemption batches by pulling required liquidity from the Vault.
/// @dev This function fulfills the asset side of redemption requests that have already been priced
/// via oracle reports. For each processed batch:
/// - Assets are pulled from the Vault to the RedeemQueue contract.
/// - Matching shares are marked as claimable for users.
///
/// This function enables asynchronous coordination between oracle reporting and vault liquidity management.
///
/// @param batches Maximum number of batches to process in this call.
/// @return counter Number of successfully processed redemption batches.
function handleBatches(uint256 batches) external returns (uint256 counter);
/// @notice Emitted when a new redemption request is requested.
event RedeemRequested(address indexed account, uint256 shares, uint256 timestamp);
/// @notice Emitted when redemption is claimed by a user.
event RedeemRequestClaimed(address indexed account, address indexed receiver, uint256 assets, uint32 timestamp);
/// @notice Emitted when oracle price reports are processed.
event RedeemRequestsHandled(uint256 counter, uint256 demand);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/// @title TransferLibrary
/// @notice Library for unified handling of native ETH and ERC20 asset transfers.
/// @dev Provides safe and abstracted methods for sending and receiving both ETH and ERC20 tokens.
///
/// # ETH Convention
/// Uses the constant `ETH = 0xEeee...EeE` to distinguish native ETH from ERC20 tokens.
library TransferLibrary {
using SafeERC20 for IERC20;
/// @notice Error thrown when `msg.value` does not match expected ETH amount
error InvalidValue();
/// @dev Placeholder address used to represent native ETH transfers
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Safely sends assets (ETH or ERC20) to a recipient
/// @param asset Address of the asset to send (use `ETH` constant for native ETH)
/// @param to Recipient address
/// @param assets Amount of assets to send
/// @dev Uses `Address.sendValue` for ETH and `safeTransfer` for ERC20
function sendAssets(address asset, address to, uint256 assets) internal {
if (asset == ETH) {
Address.sendValue(payable(to), assets);
} else {
IERC20(asset).safeTransfer(to, assets);
}
}
/// @notice Safely receives assets (ETH or ERC20) from a sender
/// @param asset Address of the asset to receive (use `ETH` constant for native ETH)
/// @param from Sender address (only used for ERC20)
/// @param assets Amount of assets expected to receive
/// @dev Reverts if `msg.value` is incorrect for ETH or uses `safeTransferFrom` for ERC20
function receiveAssets(address asset, address from, uint256 assets) internal {
if (asset == ETH) {
if (msg.value != assets) {
revert InvalidValue();
}
} else {
IERC20(asset).safeTransferFrom(from, address(this), assets);
}
}
/// @notice Returns the balance of an account for a given asset
/// @param asset Address of the asset to check the balance of (use `ETH` constant for native ETH)
/// @param account Address of the account to check the balance of
/// @return Balance of the account for the given asset
function balanceOf(address asset, address account) internal view returns (uint256) {
if (asset == ETH) {
return account.balance;
} else {
return IERC20(asset).balanceOf(account);
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "../interfaces/modules/IShareModule.sol";
import "../interfaces/queues/IQueue.sol";
import "../libraries/SlotLibrary.sol";
abstract contract Queue is IQueue, ContextUpgradeable, ReentrancyGuardUpgradeable {
using Checkpoints for Checkpoints.Trace224;
bytes32 private immutable _queueStorageSlot;
constructor(string memory name_, uint256 version_) {
_queueStorageSlot = SlotLibrary.getSlot("Queue", name_, version_);
_disableInitializers();
}
// View functions
/// @inheritdoc IQueue
function vault() public view returns (address) {
return _queueStorage().vault;
}
/// @inheritdoc IQueue
function asset() public view returns (address) {
return _queueStorage().asset;
}
// Mutable functions
/// @inheritdoc IQueue
function handleReport(uint224 priceD18, uint32 timestamp) external {
if (_msgSender() != vault()) {
revert Forbidden();
}
if (priceD18 == 0 || timestamp >= block.timestamp) {
revert InvalidReport();
}
_handleReport(priceD18, timestamp);
emit ReportHandled(priceD18, timestamp);
}
// Internal functions
function __Queue_init(address asset_, address vault_) internal onlyInitializing {
__ReentrancyGuard_init();
if (asset_ == address(0) || vault_ == address(0)) {
revert ZeroValue();
}
QueueStorage storage $ = _queueStorage();
$.asset = asset_;
$.vault = vault_;
$.timestamps.push(uint32(block.timestamp), uint224(0));
}
function _timestamps() internal view returns (Checkpoints.Trace224 storage) {
return _queueStorage().timestamps;
}
function _queueStorage() private view returns (QueueStorage storage qs) {
bytes32 slot = _queueStorageSlot;
assembly {
qs.slot := slot
}
}
function _handleReport(uint224 priceD18, uint32 latestEligibleTimestamp) internal virtual;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
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;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/structs/Checkpoints.sol)
// This file was procedurally generated from scripts/generate/templates/Checkpoints.js.
pragma solidity ^0.8.20;
import {Math} from "../math/Math.sol";
/**
* @dev This library defines the `Trace*` struct, for checkpointing values as they change at different points in
* time, and later looking up past values by block number. See {Votes} as an example.
*
* To create a history of checkpoints define a variable type `Checkpoints.Trace*` in your contract, and store a new
* checkpoint for the current transaction block using the {push} function.
*/
library Checkpoints {
/**
* @dev A value was attempted to be inserted on a past checkpoint.
*/
error CheckpointUnorderedInsertion();
struct Trace224 {
Checkpoint224[] _checkpoints;
}
struct Checkpoint224 {
uint32 _key;
uint224 _value;
}
/**
* @dev Pushes a (`key`, `value`) pair into a Trace224 so that it is stored as the checkpoint.
*
* Returns previous value and new value.
*
* IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint32).max` key set will disable the
* library.
*/
function push(
Trace224 storage self,
uint32 key,
uint224 value
) internal returns (uint224 oldValue, uint224 newValue) {
return _insert(self._checkpoints, key, value);
}
/**
* @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if
* there is none.
*/
function lowerLookup(Trace224 storage self, uint32 key) internal view returns (uint224) {
uint256 len = self._checkpoints.length;
uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);
return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*/
function upperLookup(Trace224 storage self, uint32 key) internal view returns (uint224) {
uint256 len = self._checkpoints.length;
uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*
* NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high
* keys).
*/
function upperLookupRecent(Trace224 storage self, uint32 key) internal view returns (uint224) {
uint256 len = self._checkpoints.length;
uint256 low = 0;
uint256 high = len;
if (len > 5) {
uint256 mid = len - Math.sqrt(len);
if (key < _unsafeAccess(self._checkpoints, mid)._key) {
high = mid;
} else {
low = mid + 1;
}
}
uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
*/
function latest(Trace224 storage self) internal view returns (uint224) {
uint256 pos = self._checkpoints.length;
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value
* in the most recent checkpoint.
*/
function latestCheckpoint(Trace224 storage self) internal view returns (bool exists, uint32 _key, uint224 _value) {
uint256 pos = self._checkpoints.length;
if (pos == 0) {
return (false, 0, 0);
} else {
Checkpoint224 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);
return (true, ckpt._key, ckpt._value);
}
}
/**
* @dev Returns the number of checkpoints.
*/
function length(Trace224 storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
/**
* @dev Returns checkpoint at given position.
*/
function at(Trace224 storage self, uint32 pos) internal view returns (Checkpoint224 memory) {
return self._checkpoints[pos];
}
/**
* @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
* or by updating the last one.
*/
function _insert(
Checkpoint224[] storage self,
uint32 key,
uint224 value
) private returns (uint224 oldValue, uint224 newValue) {
uint256 pos = self.length;
if (pos > 0) {
Checkpoint224 storage last = _unsafeAccess(self, pos - 1);
uint32 lastKey = last._key;
uint224 lastValue = last._value;
// Checkpoint keys must be non-decreasing.
if (lastKey > key) {
revert CheckpointUnorderedInsertion();
}
// Update or push new checkpoint
if (lastKey == key) {
last._value = value;
} else {
self.push(Checkpoint224({_key: key, _value: value}));
}
return (lastValue, value);
} else {
self.push(Checkpoint224({_key: key, _value: value}));
return (0, value);
}
}
/**
* @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _upperBinaryLookup(
Checkpoint224[] storage self,
uint32 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key > key) {
high = mid;
} else {
low = mid + 1;
}
}
return high;
}
/**
* @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _lowerBinaryLookup(
Checkpoint224[] storage self,
uint32 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key < key) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
/**
* @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
*/
function _unsafeAccess(
Checkpoint224[] storage self,
uint256 pos
) private pure returns (Checkpoint224 storage result) {
assembly {
mstore(0, self.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
struct Trace208 {
Checkpoint208[] _checkpoints;
}
struct Checkpoint208 {
uint48 _key;
uint208 _value;
}
/**
* @dev Pushes a (`key`, `value`) pair into a Trace208 so that it is stored as the checkpoint.
*
* Returns previous value and new value.
*
* IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint48).max` key set will disable the
* library.
*/
function push(
Trace208 storage self,
uint48 key,
uint208 value
) internal returns (uint208 oldValue, uint208 newValue) {
return _insert(self._checkpoints, key, value);
}
/**
* @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if
* there is none.
*/
function lowerLookup(Trace208 storage self, uint48 key) internal view returns (uint208) {
uint256 len = self._checkpoints.length;
uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);
return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*/
function upperLookup(Trace208 storage self, uint48 key) internal view returns (uint208) {
uint256 len = self._checkpoints.length;
uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*
* NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high
* keys).
*/
function upperLookupRecent(Trace208 storage self, uint48 key) internal view returns (uint208) {
uint256 len = self._checkpoints.length;
uint256 low = 0;
uint256 high = len;
if (len > 5) {
uint256 mid = len - Math.sqrt(len);
if (key < _unsafeAccess(self._checkpoints, mid)._key) {
high = mid;
} else {
low = mid + 1;
}
}
uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
*/
function latest(Trace208 storage self) internal view returns (uint208) {
uint256 pos = self._checkpoints.length;
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value
* in the most recent checkpoint.
*/
function latestCheckpoint(Trace208 storage self) internal view returns (bool exists, uint48 _key, uint208 _value) {
uint256 pos = self._checkpoints.length;
if (pos == 0) {
return (false, 0, 0);
} else {
Checkpoint208 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);
return (true, ckpt._key, ckpt._value);
}
}
/**
* @dev Returns the number of checkpoints.
*/
function length(Trace208 storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
/**
* @dev Returns checkpoint at given position.
*/
function at(Trace208 storage self, uint32 pos) internal view returns (Checkpoint208 memory) {
return self._checkpoints[pos];
}
/**
* @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
* or by updating the last one.
*/
function _insert(
Checkpoint208[] storage self,
uint48 key,
uint208 value
) private returns (uint208 oldValue, uint208 newValue) {
uint256 pos = self.length;
if (pos > 0) {
Checkpoint208 storage last = _unsafeAccess(self, pos - 1);
uint48 lastKey = last._key;
uint208 lastValue = last._value;
// Checkpoint keys must be non-decreasing.
if (lastKey > key) {
revert CheckpointUnorderedInsertion();
}
// Update or push new checkpoint
if (lastKey == key) {
last._value = value;
} else {
self.push(Checkpoint208({_key: key, _value: value}));
}
return (lastValue, value);
} else {
self.push(Checkpoint208({_key: key, _value: value}));
return (0, value);
}
}
/**
* @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _upperBinaryLookup(
Checkpoint208[] storage self,
uint48 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key > key) {
high = mid;
} else {
low = mid + 1;
}
}
return high;
}
/**
* @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _lowerBinaryLookup(
Checkpoint208[] storage self,
uint48 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key < key) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
/**
* @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
*/
function _unsafeAccess(
Checkpoint208[] storage self,
uint256 pos
) private pure returns (Checkpoint208 storage result) {
assembly {
mstore(0, self.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
struct Trace160 {
Checkpoint160[] _checkpoints;
}
struct Checkpoint160 {
uint96 _key;
uint160 _value;
}
/**
* @dev Pushes a (`key`, `value`) pair into a Trace160 so that it is stored as the checkpoint.
*
* Returns previous value and new value.
*
* IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint96).max` key set will disable the
* library.
*/
function push(
Trace160 storage self,
uint96 key,
uint160 value
) internal returns (uint160 oldValue, uint160 newValue) {
return _insert(self._checkpoints, key, value);
}
/**
* @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if
* there is none.
*/
function lowerLookup(Trace160 storage self, uint96 key) internal view returns (uint160) {
uint256 len = self._checkpoints.length;
uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len);
return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*/
function upperLookup(Trace160 storage self, uint96 key) internal view returns (uint160) {
uint256 len = self._checkpoints.length;
uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero
* if there is none.
*
* NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high
* keys).
*/
function upperLookupRecent(Trace160 storage self, uint96 key) internal view returns (uint160) {
uint256 len = self._checkpoints.length;
uint256 low = 0;
uint256 high = len;
if (len > 5) {
uint256 mid = len - Math.sqrt(len);
if (key < _unsafeAccess(self._checkpoints, mid)._key) {
high = mid;
} else {
low = mid + 1;
}
}
uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high);
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints.
*/
function latest(Trace160 storage self) internal view returns (uint160) {
uint256 pos = self._checkpoints.length;
return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value;
}
/**
* @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value
* in the most recent checkpoint.
*/
function latestCheckpoint(Trace160 storage self) internal view returns (bool exists, uint96 _key, uint160 _value) {
uint256 pos = self._checkpoints.length;
if (pos == 0) {
return (false, 0, 0);
} else {
Checkpoint160 storage ckpt = _unsafeAccess(self._checkpoints, pos - 1);
return (true, ckpt._key, ckpt._value);
}
}
/**
* @dev Returns the number of checkpoints.
*/
function length(Trace160 storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
/**
* @dev Returns checkpoint at given position.
*/
function at(Trace160 storage self, uint32 pos) internal view returns (Checkpoint160 memory) {
return self._checkpoints[pos];
}
/**
* @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint,
* or by updating the last one.
*/
function _insert(
Checkpoint160[] storage self,
uint96 key,
uint160 value
) private returns (uint160 oldValue, uint160 newValue) {
uint256 pos = self.length;
if (pos > 0) {
Checkpoint160 storage last = _unsafeAccess(self, pos - 1);
uint96 lastKey = last._key;
uint160 lastValue = last._value;
// Checkpoint keys must be non-decreasing.
if (lastKey > key) {
revert CheckpointUnorderedInsertion();
}
// Update or push new checkpoint
if (lastKey == key) {
last._value = value;
} else {
self.push(Checkpoint160({_key: key, _value: value}));
}
return (lastValue, value);
} else {
self.push(Checkpoint160({_key: key, _value: value}));
return (0, value);
}
}
/**
* @dev Return the index of the first (oldest) checkpoint with key strictly bigger than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _upperBinaryLookup(
Checkpoint160[] storage self,
uint96 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key > key) {
high = mid;
} else {
low = mid + 1;
}
}
return high;
}
/**
* @dev Return the index of the first (oldest) checkpoint with key greater or equal than the search key, or `high`
* if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive
* `high`.
*
* WARNING: `high` should not be greater than the array's length.
*/
function _lowerBinaryLookup(
Checkpoint160[] storage self,
uint96 key,
uint256 low,
uint256 high
) private view returns (uint256) {
while (low < high) {
uint256 mid = Math.average(low, high);
if (_unsafeAccess(self, mid)._key < key) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
/**
* @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds.
*/
function _unsafeAccess(
Checkpoint160[] storage self,
uint256 pos
) private pure returns (Checkpoint160 storage result) {
assembly {
mstore(0, self.slot)
result.slot := add(keccak256(0, 0x20), pos)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/structs/EnumerableMap.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableMap.js.
pragma solidity ^0.8.20;
import {EnumerableSet} from "./EnumerableSet.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
* - Map can be cleared (all entries removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* The following map types are supported:
*
* - `uint256 -> address` (`UintToAddressMap`) since v3.0.0
* - `address -> uint256` (`AddressToUintMap`) since v4.6.0
* - `bytes32 -> bytes32` (`Bytes32ToBytes32Map`) since v4.6.0
* - `uint256 -> uint256` (`UintToUintMap`) since v4.7.0
* - `bytes32 -> uint256` (`Bytes32ToUintMap`) since v4.7.0
* - `uint256 -> bytes32` (`UintToBytes32Map`) since v5.1.0
* - `address -> address` (`AddressToAddressMap`) since v5.1.0
* - `address -> bytes32` (`AddressToBytes32Map`) since v5.1.0
* - `bytes32 -> address` (`Bytes32ToAddressMap`) since v5.1.0
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableMap.
* ====
*/
library EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// To implement this library for multiple types with as little code repetition as possible, we write it in
// terms of a generic Map type with bytes32 keys and values. The Map implementation uses private functions,
// and user-facing implementations such as `UintToAddressMap` are just wrappers around the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit in bytes32.
/**
* @dev Query for a nonexistent map key.
*/
error EnumerableMapNonexistentKey(bytes32 key);
struct Bytes32ToBytes32Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 key => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internal returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Removes all the entries from a map. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32ToBytes32Map storage map) internal {
uint256 len = length(map);
for (uint256 i = 0; i < len; ++i) {
delete map._values[map._keys.at(i)];
}
map._keys.clear();
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32 key, bytes32 value) {
bytes32 atKey = map._keys.at(index);
return (atKey, map._values[atKey]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool exists, bytes32 value) {
bytes32 val = map._values[key];
if (val == bytes32(0)) {
return (contains(map, key), bytes32(0));
} else {
return (true, val);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {
bytes32 value = map._values[key];
if (value == 0 && !contains(map, key)) {
revert EnumerableMapNonexistentKey(key);
}
return value;
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(Bytes32ToBytes32Map storage map) internal view returns (bytes32[] memory) {
return map._keys.values();
}
// UintToUintMap
struct UintToUintMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToUintMap storage map, uint256 key, uint256 value) internal returns (bool) {
return set(map._inner, bytes32(key), bytes32(value));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToUintMap storage map, uint256 key) internal returns (bool) {
return remove(map._inner, bytes32(key));
}
/**
* @dev Removes all the entries from a map. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintToUintMap storage map) internal {
clear(map._inner);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToUintMap storage map, uint256 key) internal view returns (bool) {
return contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToUintMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToUintMap storage map, uint256 index) internal view returns (uint256 key, uint256 value) {
(bytes32 atKey, bytes32 val) = at(map._inner, index);
return (uint256(atKey), uint256(val));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(UintToUintMap storage map, uint256 key) internal view returns (bool exists, uint256 value) {
(bool success, bytes32 val) = tryGet(map._inner, bytes32(key));
return (success, uint256(val));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) {
return uint256(get(map._inner, bytes32(key)));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(UintToUintMap storage map) internal view returns (uint256[] memory) {
bytes32[] memory store = keys(map._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintToAddressMap
struct UintToAddressMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return remove(map._inner, bytes32(key));
}
/**
* @dev Removes all the entries from a map. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintToAddressMap storage map) internal {
clear(map._inner);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256 key, address value) {
(bytes32 atKey, bytes32 val) = at(map._inner, index);
return (uint256(atKey), address(uint160(uint256(val))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool exists, address value) {
(bool success, bytes32 val) = tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(val))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(get(map._inner, bytes32(key)))));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(UintToAddressMap storage map) internal view returns (uint256[] memory) {
bytes32[] memory store = keys(map._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintToBytes32Map
struct UintToBytes32Map {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToBytes32Map storage map, uint256 key, bytes32 value) internal returns (bool) {
return set(map._inner, bytes32(key), value);
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToBytes32Map storage map, uint256 key) internal returns (bool) {
return remove(map._inner, bytes32(key));
}
/**
* @dev Removes all the entries from a map. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintToBytes32Map storage map) internal {
clear(map._inner);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToBytes32Map storage map, uint256 key) internal view returns (bool) {
return contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToBytes32Map storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToBytes32Map storage map, uint256 index) internal view returns (uint256 key, bytes32 value) {
(bytes32 atKey, bytes32 val) = at(map._inner, index);
return (uint256(atKey), val);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(UintToBytes32Map storage map, uint256 key) internal view returns (bool exists, bytes32 value) {
(bool success, bytes32 val) = tryGet(map._inner, bytes32(key));
return (success, val);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToBytes32Map storage map, uint256 key) internal view returns (bytes32) {
return get(map._inner, bytes32(key));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(UintToBytes32Map storage map) internal view returns (uint256[] memory) {
bytes32[] memory store = keys(map._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressToUintMap
struct AddressToUintMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(AddressToUintMap storage map, address key, uint256 value) internal returns (bool) {
return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToUintMap storage map, address key) internal returns (bool) {
return remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Removes all the entries from a map. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressToUintMap storage map) internal {
clear(map._inner);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
return contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToUintMap storage map, uint256 index) internal view returns (address key, uint256 value) {
(bytes32 atKey, bytes32 val) = at(map._inner, index);
return (address(uint160(uint256(atKey))), uint256(val));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(AddressToUintMap storage map, address key) internal view returns (bool exists, uint256 value) {
(bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, uint256(val));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
return uint256(get(map._inner, bytes32(uint256(uint160(key)))));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(AddressToUintMap storage map) internal view returns (address[] memory) {
bytes32[] memory store = keys(map._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressToAddressMap
struct AddressToAddressMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(AddressToAddressMap storage map, address key, address value) internal returns (bool) {
return set(map._inner, bytes32(uint256(uint160(key))), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToAddressMap storage map, address key) internal returns (bool) {
return remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Removes all the entries from a map. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressToAddressMap storage map) internal {
clear(map._inner);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToAddressMap storage map, address key) internal view returns (bool) {
return contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToAddressMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToAddressMap storage map, uint256 index) internal view returns (address key, address value) {
(bytes32 atKey, bytes32 val) = at(map._inner, index);
return (address(uint160(uint256(atKey))), address(uint160(uint256(val))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(AddressToAddressMap storage map, address key) internal view returns (bool exists, address value) {
(bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, address(uint160(uint256(val))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToAddressMap storage map, address key) internal view returns (address) {
return address(uint160(uint256(get(map._inner, bytes32(uint256(uint160(key)))))));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(AddressToAddressMap storage map) internal view returns (address[] memory) {
bytes32[] memory store = keys(map._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressToBytes32Map
struct AddressToBytes32Map {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(AddressToBytes32Map storage map, address key, bytes32 value) internal returns (bool) {
return set(map._inner, bytes32(uint256(uint160(key))), value);
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToBytes32Map storage map, address key) internal returns (bool) {
return remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Removes all the entries from a map. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressToBytes32Map storage map) internal {
clear(map._inner);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToBytes32Map storage map, address key) internal view returns (bool) {
return contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToBytes32Map storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToBytes32Map storage map, uint256 index) internal view returns (address key, bytes32 value) {
(bytes32 atKey, bytes32 val) = at(map._inner, index);
return (address(uint160(uint256(atKey))), val);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(AddressToBytes32Map storage map, address key) internal view returns (bool exists, bytes32 value) {
(bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, val);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToBytes32Map storage map, address key) internal view returns (bytes32) {
return get(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(AddressToBytes32Map storage map) internal view returns (address[] memory) {
bytes32[] memory store = keys(map._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// Bytes32ToUintMap
struct Bytes32ToUintMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(Bytes32ToUintMap storage map, bytes32 key, uint256 value) internal returns (bool) {
return set(map._inner, key, bytes32(value));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Bytes32ToUintMap storage map, bytes32 key) internal returns (bool) {
return remove(map._inner, key);
}
/**
* @dev Removes all the entries from a map. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32ToUintMap storage map) internal {
clear(map._inner);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool) {
return contains(map._inner, key);
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(Bytes32ToUintMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32ToUintMap storage map, uint256 index) internal view returns (bytes32 key, uint256 value) {
(bytes32 atKey, bytes32 val) = at(map._inner, index);
return (atKey, uint256(val));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool exists, uint256 value) {
(bool success, bytes32 val) = tryGet(map._inner, key);
return (success, uint256(val));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Bytes32ToUintMap storage map, bytes32 key) internal view returns (uint256) {
return uint256(get(map._inner, key));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(Bytes32ToUintMap storage map) internal view returns (bytes32[] memory) {
bytes32[] memory store = keys(map._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// Bytes32ToAddressMap
struct Bytes32ToAddressMap {
Bytes32ToBytes32Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(Bytes32ToAddressMap storage map, bytes32 key, address value) internal returns (bool) {
return set(map._inner, key, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Bytes32ToAddressMap storage map, bytes32 key) internal returns (bool) {
return remove(map._inner, key);
}
/**
* @dev Removes all the entries from a map. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the map grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32ToAddressMap storage map) internal {
clear(map._inner);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (bool) {
return contains(map._inner, key);
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(Bytes32ToAddressMap storage map) internal view returns (uint256) {
return length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the map. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32ToAddressMap storage map, uint256 index) internal view returns (bytes32 key, address value) {
(bytes32 atKey, bytes32 val) = at(map._inner, index);
return (atKey, address(uint160(uint256(val))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function tryGet(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (bool exists, address value) {
(bool success, bytes32 val) = tryGet(map._inner, key);
return (success, address(uint160(uint256(val))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (address) {
return address(uint160(uint256(get(map._inner, key))));
}
/**
* @dev Return the an array containing all the keys
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the map grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function keys(Bytes32ToAddressMap storage map) internal view returns (bytes32[] memory) {
bytes32[] memory store = keys(map._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "../factories/IFactory.sol";
import "../managers/IRiskManager.sol";
import "./IACLModule.sol";
import "./IShareModule.sol";
import "./ISubvaultModule.sol";
import "./IVerifierModule.sol";
/// @title IVaultModule
/// @notice Interface for a VaultModule that manages and coordinates asset flows
/// and sub-vault connections within a modular vault architecture.
interface IVaultModule is IACLModule {
/// @dev Thrown when trying to reconnect a subvault that is already connected.
error AlreadyConnected(address subvault);
/// @dev Thrown when trying to disconnect a subvault that is not currently connected.
error NotConnected(address subvault);
/// @dev Thrown when the provided address is not a valid factory-deployed entity.
error NotEntity(address subvault);
/// @dev Thrown when a given subvault is not correctly configured.
error InvalidSubvault(address subvault);
/// @notice Storage structure used to track vault state and subvaults.
struct VaultModuleStorage {
address riskManager;
EnumerableSet.AddressSet subvaults;
}
/// @notice Role that allows the creation of new subvaults.
function CREATE_SUBVAULT_ROLE() external view returns (bytes32);
/// @notice Role that allows disconnecting existing subvaults.
function DISCONNECT_SUBVAULT_ROLE() external view returns (bytes32);
/// @notice Role identifier for reconnecting subvaults.
/// @dev Grants permission to reattach a subvault to the vault system.
/// This includes both re-connecting a previously disconnected subvault
/// and connecting a new, properly configured subvault for the first time.
/// Used to maintain modularity and support hot-swapping of subvaults.
function RECONNECT_SUBVAULT_ROLE() external view returns (bytes32);
/// @notice Role that allows pulling assets from subvaults.
function PULL_LIQUIDITY_ROLE() external view returns (bytes32);
/// @notice Role that allows pushing assets into subvaults.
function PUSH_LIQUIDITY_ROLE() external view returns (bytes32);
/// @notice Returns the factory used to deploy new subvaults.
function subvaultFactory() external view returns (IFactory);
/// @notice Returns the factory used to deploy verifiers.
function verifierFactory() external view returns (IFactory);
/// @notice Returns the total number of connected subvaults.
function subvaults() external view returns (uint256);
/// @notice Returns the address of the subvault at a specific index.
/// @param index Index in the set of subvaults.
function subvaultAt(uint256 index) external view returns (address);
/// @notice Checks whether a given address is currently an active subvault.
/// @param subvault Address to check.
function hasSubvault(address subvault) external view returns (bool);
/// @notice Returns the address of the risk manager module.
function riskManager() external view returns (IRiskManager);
/// @notice Creates and connects a new subvault.
/// @param version Version of the subvault contract to deploy.
/// @param owner Owner of the newly created subvault.
/// @param verifier Verifier contract used for permissions within the subvault.
/// @return subvault Address of the newly created subvault.
function createSubvault(uint256 version, address owner, address verifier) external returns (address subvault);
/// @notice Disconnects a subvault from the vault.
/// @param subvault Address of the subvault to disconnect.
function disconnectSubvault(address subvault) external;
/// @notice Reconnects a subvault to the main vault system.
/// @dev Can be used to reattach either:
/// - A previously disconnected subvault, or
/// - A newly created and properly configured subvault.
/// Requires the caller to have the `RECONNECT_SUBVAULT_ROLE`.
/// @param subvault The address of the subvault to reconnect.
function reconnectSubvault(address subvault) external;
/// @notice Sends a specified amount of assets from the vault to a connected subvault.
/// @param subvault Address of the destination subvault.
/// @param asset Address of the asset to transfer.
/// @param value Amount of the asset to send.
function pushAssets(address subvault, address asset, uint256 value) external;
/// @notice Pulls a specified amount of assets from a connected subvault into the vault.
/// @param subvault Address of the source subvault.
/// @param asset Address of the asset to transfer.
/// @param value Amount of the asset to receive.
function pullAssets(address subvault, address asset, uint256 value) external;
/// @notice Internally used function that transfers assets from the vault to a connected subvault.
/// @dev Must be invoked by the vault itself via hook execution logic.
/// @param subvault Address of the destination subvault.
/// @param asset Address of the asset being transferred.
/// @param value Amount of the asset being transferred.
function hookPushAssets(address subvault, address asset, uint256 value) external;
/// @notice Internally used function that pulls assets from a connected subvault into the vault.
/// @dev Must be invoked by the vault itself via hook execution logic.
/// @param subvault Address of the source subvault.
/// @param asset Address of the asset being pulled.
/// @param value Amount of the asset being pulled.
function hookPullAssets(address subvault, address asset, uint256 value) external;
/// @notice Emitted when a new subvault is created.
event SubvaultCreated(address indexed subvault, uint256 version, address indexed owner, address indexed verifier);
/// @notice Emitted when a subvault is disconnected.
event SubvaultDisconnected(address indexed subvault);
/// @notice Emitted when a subvault is reconnected.
event SubvaultReconnected(address indexed subvault, address indexed verifier);
/// @notice Emitted when assets are pulled from a subvault into the vault.
event AssetsPulled(address indexed asset, address indexed subvault, uint256 value);
/// @notice Emitted when assets are pushed from the vault into a subvault.
event AssetsPushed(address indexed asset, address indexed subvault, uint256 value);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "../factories/IFactoryEntity.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/utils/structs/Checkpoints.sol";
/// @title IQueue
/// @notice Base interface for deposit and redeem queues.
/// @dev Provides common structure and logic for queue operations such as pricing and vault association.
interface IQueue is IFactoryEntity {
/// @notice Reverts when a zero input value is supplied where non-zero is required.
error ZeroValue();
/// @notice Reverts when caller is not authorized to perform an action.
error Forbidden();
/// @notice Reverts when an oracle price report is invalid.
error InvalidReport();
/// @notice Reverts when queue interactions are restricted due to governance or ACL pause.
error QueuePaused();
/// @notice Storage layout for a generic queue contract (deposit or redeem).
struct QueueStorage {
/// @notice The asset managed by this queue (ERC20 or ETH).
address asset;
/// @notice The vault that this queue is connected to. Only this vault can trigger `handleReport`.
address vault;
/// @notice Timeline of user request checkpoints.
/// @dev Stores a sorted series of (timestamp, value) pairs, where the meaning of `value` is defined by the specific queue implementation.
Checkpoints.Trace224 timestamps;
}
/// @notice Returns the associated vault address.
function vault() external view returns (address vault);
/// @notice Returns the asset handled by this queue (ERC20 or ETH).
function asset() external view returns (address asset);
/// @notice Returns true if this queue is eligible for removal by the vault.
/// @return removable True if the queue is safe to remove.
function canBeRemoved() external view returns (bool removable);
/// @notice Handles a new price report from the oracle.
/// @dev Only callable by the vault. Validates input timestamp and price.
/// @param priceD18 Price reported with 18 decimal precision (shares = price * assets).
/// @param timestamp Timestamp when the report becomes effective.
function handleReport(uint224 priceD18, uint32 timestamp) external;
/// @notice Emitted when a price report is successfully processed by the queue.
/// @param priceD18 Reported price in 18-decimal fixed-point format (shares = assets * price).
/// @param timestamp All unprocessed requests with timestamps <= this value were handled using this report.
event ReportHandled(uint224 priceD18, uint32 timestamp);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity 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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
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 silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @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 Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @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
* {Errors.FailedCall} 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 Errors.InsufficientBalance(address(this).balance, value);
}
(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 {Errors.FailedCall}) 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 {Errors.FailedCall} 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 {Errors.FailedCall}.
*/
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
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "../factories/IFactory.sol";
import "../hooks/IRedeemHook.sol";
import "../managers/IFeeManager.sol";
import "../managers/IShareManager.sol";
import "../oracles/IOracle.sol";
import "../queues/IDepositQueue.sol";
import "../queues/IQueue.sol";
import "../queues/IRedeemQueue.sol";
import "./IBaseModule.sol";
/// @title IShareModule
/// @notice Manages user-facing interactions with the vault via deposit/redeem queues, hooks, and share accounting.
/// @dev Coordinates oracle report handling, hook invocation, fee calculation, and queue lifecycle.
interface IShareModule is IBaseModule {
/// @notice Thrown when an unsupported asset is used for queue creation.
error UnsupportedAsset(address asset);
/// @notice Thrown when the number of queues exceeds the allowed system-wide maximum.
error QueueLimitReached();
/// @notice Thrown when an operation is attempted with a zero-value parameter.
error ZeroValue();
/// @dev Storage structure for the ShareModule.
struct ShareModuleStorage {
address shareManager; // Address of the ShareManager responsible for minting/burning shares
address feeManager; // Address of the FeeManager that calculates and collects protocol fees
address oracle; // Address of the Oracle
address defaultDepositHook; // Optional hook that is called by default after DepositQueue requests are processed
address defaultRedeemHook; // Optional hook that is called by default before RedeemQueue requests are processed
uint256 queueCount; // Total number of queues across all assets
uint256 queueLimit; // Maximum number of queues allowed in the system
mapping(address => address) customHooks; // Optional queue-specific hooks
mapping(address => bool) isDepositQueue; // Whether the queue is a deposit queue
mapping(address => bool) isPausedQueue; // Whether queue operations are currently paused
mapping(address => EnumerableSet.AddressSet) queues; // Mapping of asset to its associated queues
EnumerableSet.AddressSet assets; // Set of all supported assets with queues
}
/// @notice Role identifier for managing per-queue and default hooks
function SET_HOOK_ROLE() external view returns (bytes32);
/// @notice Role identifier for creating new queues
function CREATE_QUEUE_ROLE() external view returns (bytes32);
/// @notice Role identifier for changing the active/paused status of queues
function SET_QUEUE_STATUS_ROLE() external view returns (bytes32);
/// @notice Role identifier for modifying the global queue limit
function SET_QUEUE_LIMIT_ROLE() external view returns (bytes32);
/// @notice Role identifier for removing existing queues
function REMOVE_QUEUE_ROLE() external view returns (bytes32);
/// @notice Returns the ShareManager used for minting and burning shares
function shareManager() external view returns (IShareManager);
/// @notice Returns the FeeManager contract used for fee calculations
function feeManager() external view returns (IFeeManager);
/// @notice Returns the Oracle contract used for handling reports and managing supported assets.
function oracle() external view returns (IOracle);
/// @notice Returns the factory used for deploying deposit queues
function depositQueueFactory() external view returns (IFactory);
/// @notice Returns the factory used for deploying redeem queues
function redeemQueueFactory() external view returns (IFactory);
/// @notice Returns total number of distinct assets with queues
function getAssetCount() external view returns (uint256);
/// @notice Returns the address of the asset at the given index
function assetAt(uint256 index) external view returns (address);
/// @notice Returns whether the given asset is associated with any queues
function hasAsset(address asset) external view returns (bool);
/// @notice Returns whether the given queue is registered
function hasQueue(address queue) external view returns (bool);
/// @notice Returns whether the given queue is a deposit queue
function isDepositQueue(address queue) external view returns (bool);
/// @notice Returns whether the given queue is currently paused
function isPausedQueue(address queue) external view returns (bool);
/// @notice Returns number of queues associated with a given asset
function getQueueCount(address asset) external view returns (uint256);
/// @notice Returns the total number of queues across all assets
function getQueueCount() external view returns (uint256);
/// @notice Returns the queue at the given index for the specified asset
function queueAt(address asset, uint256 index) external view returns (address);
/// @notice Returns the hook assigned to a queue (customHook or defaultHook as a fallback)
function getHook(address queue) external view returns (address hook);
/// @notice Returns the default hook for deposit queues
function defaultDepositHook() external view returns (address);
/// @notice Returns the default hook for redeem queues
function defaultRedeemHook() external view returns (address);
/// @notice Returns the current global queue limit
function queueLimit() external view returns (uint256);
/// @notice Returns the total number of claimable shares for a given user
function claimableSharesOf(address account) external view returns (uint256 shares);
/// @notice Called by redeem queues to check the amount of assets available for instant withdrawal
function getLiquidAssets() external view returns (uint256);
/// @notice Claims all claimable shares from deposit queues for the specified account
function claimShares(address account) external;
/// @notice Assigns a custom hook contract to a specific queue
function setCustomHook(address queue, address hook) external;
/// @notice Sets the global default deposit hook
function setDefaultDepositHook(address hook) external;
/// @notice Sets the global default redeem hook
function setDefaultRedeemHook(address hook) external;
/// @notice Creates a new deposit or redeem queue for a given asset
function createQueue(uint256 version, bool isDepositQueue, address owner, address asset, bytes calldata data)
external;
/// @notice Removes a queue from the system if its `canBeRemoved()` function returns true
function removeQueue(address queue) external;
/// @notice Sets the maximum number of allowed queues across the module
function setQueueLimit(uint256 limit) external;
/// @notice Pauses or resumes a queue's operation
function setQueueStatus(address queue, bool isPaused) external;
/// @notice Invokes a queue's hook (also transfers assets to the queue for redeem queues)
function callHook(uint256 assets) external;
/// @notice Handles an oracle price report, distributes fees and calls internal hooks
function handleReport(address asset, uint224 priceD18, uint32 depositTimestamp, uint32 redeemTimestamp) external;
/// @notice Emitted when a user successfully claims shares from deposit queues
event SharesClaimed(address indexed account);
/// @notice Emitted when a queue-specific custom hook is updated
event CustomHookSet(address indexed queue, address indexed hook);
/// @notice Emitted when a new queue is created
event QueueCreated(address indexed queue, address indexed asset, bool isDepositQueue);
/// @notice Emitted when a queue is removed
event QueueRemoved(address indexed queue, address indexed asset);
/// @notice Emitted after a queue hook is successfully called
event HookCalled(address indexed queue, address indexed asset, uint256 assets, address hook);
/// @notice Emitted when the global queue limit is updated
event QueueLimitSet(uint256 limit);
/// @notice Emitted when a queue's paused status changes
event SetQueueStatus(address indexed queue, bool indexed isPaused);
/// @notice Emitted when a new default hook is configured
event DefaultHookSet(address indexed hook, bool isDepositHook);
/// @notice Emitted after processing a price report and fee distribution
event ReportHandled(
address indexed asset, uint224 indexed priceD18, uint32 depositTimestamp, uint32 redeemTimestamp, uint256 fees
);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
/// @title SlotLibrary
/// @notice Library for computing deterministic and collision-resistant storage slots
/// @dev Used to generate unique storage slots for upgradeable modules using string identifiers
library SlotLibrary {
/// @notice Computes a unique storage slot based on the module's identifiers
/// @param contractName Logical contract/module name (e.g., "ShareModule")
/// @param name Human-readable instance name (e.g., "Mellow")
/// @param version Version number for the module configuration
/// @return A bytes32 value representing the derived storage slot
function getSlot(string memory contractName, string memory name, uint256 version) internal pure returns (bytes32) {
return keccak256(
abi.encode(
uint256(keccak256(abi.encodePacked("mellow.flexible-vaults.storage.", contractName, name, version))) - 1
)
) & ~bytes32(uint256(0xff));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 reinitialization) 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 Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
import {Arrays} from "../Arrays.sol";
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
* - Set can be cleared (all elements removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function _clear(Set storage set) private {
uint256 len = _length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32Set storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "./IFactoryEntity.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/// @title IFactory
/// @notice Interface for a factory that manages deployable upgradeable proxies and implementation governance.
interface IFactory is IFactoryEntity {
/// @notice Thrown when attempting to access an index outside the valid range.
error OutOfBounds(uint256 index);
/// @notice Thrown when trying to use an implementation version that is blacklisted.
error BlacklistedVersion(uint256 version);
/// @notice Thrown when an implementation is already in the accepted list.
error ImplementationAlreadyAccepted(address implementation);
/// @notice Thrown when an implementation has already been proposed.
error ImplementationAlreadyProposed(address implementation);
/// @notice Thrown when attempting to accept an implementation that was never proposed.
error ImplementationNotProposed(address implementation);
/// @dev Internal storage structure for tracking factory state.
struct FactoryStorage {
EnumerableSet.AddressSet entities; // Set of deployed upgradeable proxies
EnumerableSet.AddressSet implementations; // Set of accepted implementation addresses
EnumerableSet.AddressSet proposals; // Set of currently proposed (but not yet accepted) implementations
mapping(uint256 version => bool) isBlacklisted; // Tracks whether a given version is blacklisted
}
/// @notice Returns the total number of deployed entities (proxies).
function entities() external view returns (uint256);
/// @notice Returns the address of the deployed entity at a given index.
function entityAt(uint256 index) external view returns (address);
/// @notice Returns whether the given address is a deployed entity.
function isEntity(address entity) external view returns (bool);
/// @notice Returns the total number of accepted implementation contracts.
function implementations() external view returns (uint256);
/// @notice Returns the implementation address at the given index.
function implementationAt(uint256 index) external view returns (address);
/// @notice Returns the number of currently proposed (pending) implementations.
function proposals() external view returns (uint256);
/// @notice Returns the address of a proposed implementation at a given index.
function proposalAt(uint256 index) external view returns (address);
/// @notice Returns whether the given implementation version is blacklisted.
function isBlacklisted(uint256 version) external view returns (bool);
/// @notice Updates the blacklist status for a specific implementation version.
/// @param version The version index to update.
/// @param flag True to blacklist, false to unblacklist.
function setBlacklistStatus(uint256 version, bool flag) external;
/// @notice Proposes a new implementation for future deployment.
/// @param implementation The address of the proposed implementation contract.
function proposeImplementation(address implementation) external;
/// @notice Approves a previously proposed implementation, allowing it to be used for deployments.
/// @param implementation The address of the proposed implementation to approve.
function acceptProposedImplementation(address implementation) external;
/// @notice Deploys a new TransparentUpgradeableProxy using an accepted implementation.
/// @param version The version index of the implementation to use.
/// @param owner The address that will become the owner of the proxy.
/// @param initParams Calldata to be passed for initialization of the new proxy instance.
/// @return instance The address of the newly deployed proxy contract.
function create(uint256 version, address owner, bytes calldata initParams) external returns (address instance);
/// @notice Emitted when the blacklist status of a version is updated.
event SetBlacklistStatus(uint256 version, bool flag);
/// @notice Emitted when a new implementation is proposed.
event ProposeImplementation(address implementation);
/// @notice Emitted when a proposed implementation is accepted.
event AcceptProposedImplementation(address implementation);
/// @notice Emitted when a new proxy instance is successfully deployed.
event Created(address indexed instance, uint256 indexed version, address indexed owner, bytes initParams);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../factories/IFactoryEntity.sol";
import "../modules/IACLModule.sol";
import "../modules/IShareModule.sol";
import "../modules/IVaultModule.sol";
import "../oracles/IOracle.sol";
/// @notice Interface for the RiskManager contract
/// @dev Handles vault and subvault balance limits, pending asset tracking, and asset permissioning
interface IRiskManager is IFactoryEntity {
/// @notice Thrown when the caller lacks appropriate permission
error Forbidden();
/// @notice Thrown when a price report is flagged as suspicious, or has not been set yet.
error InvalidReport();
/// @notice Thrown when attempting to allow an already allowed asset
error AlreadyAllowedAsset(address asset);
/// @notice Thrown when attempting to disallow or use a non-allowed asset
error NotAllowedAsset(address asset);
/// @notice Thrown when a vault or subvault exceeds its configured limit
error LimitExceeded(int256 newValue, int256 maxValue);
/// @notice Thrown when a given address is not recognized as a valid subvault
error NotSubvault(address subvault);
/// @notice Thrown when a zero address is passed as a parameter
error ZeroValue();
/// @notice Tracks current and maximum balance for a vault or subvault
struct State {
int256 balance; // Current approximate shares held
int256 limit; // Maximum allowable approximate shares
}
/// @notice Storage layout for RiskManager.
struct RiskManagerStorage {
address vault; // Address of the Vault associated with this risk manager.
State vaultState; // Tracks the share balance and limit for the Vault.
int256 pendingBalance;
/// Cumulative approximate share balance from all pending requests in all deposit queues. Used to track unprocessed inflows.
mapping(address asset => int256) pendingAssets; // Pending inflow amount per asset.
mapping(address asset => int256) pendingShares; // Pending inflow amount in shares per asset converted by the last oracle report.
mapping(address subvault => State) subvaultStates; // Share state tracking for each connected subvault.
mapping(address subvault => EnumerableSet.AddressSet) allowedAssets; // List of assets that each subvault is allowed to interact with.
}
/// @notice Reverts if the given subvault is not valid for the vault
function requireValidSubvault(address vault_, address subvault) external view;
/// @notice Returns the address of the Vault
function vault() external view returns (address);
/// @notice Returns the approximate share balance and the share limit limit of the vault.
function vaultState() external view returns (State memory);
/// @notice Returns the pending share balance across all assets and deposit queues.
function pendingBalance() external view returns (int256);
/// @notice Returns the pending asset value for a specific asset
function pendingAssets(address asset) external view returns (int256);
/// @notice Returns the pending shares equivalent of a specific asset converted by the last oracle report for the given asset.
function pendingShares(address asset) external view returns (int256);
/// @notice Returns the approximate balance and the limit of a specific subvault
function subvaultState(address subvault) external view returns (State memory);
/// @notice Returns number of assets allowed for a given subvault
function allowedAssets(address subvault) external view returns (uint256);
/// @notice Returns the allowed asset at a given index for a subvault
function allowedAssetAt(address subvault, uint256 index) external view returns (address);
/// @notice Checks if an asset is allowed for the specified subvault
function isAllowedAsset(address subvault, address asset) external view returns (bool);
/// @notice Converts an asset amount into its equivalent share representation by the last oracle report
/// @param asset Asset being valued
/// @param value Amount in asset units (can be positive or negative)
/// @return shares Share amount
function convertToShares(address asset, int256 value) external view returns (int256 shares);
/// @notice Returns the maximum amount that can be deposited into a subvault for a specific asset
function maxDeposit(address subvault, address asset) external view returns (uint256 limit);
/// @notice Modifies the vault's internal balance by a signed delta (in asset terms)
function modifyVaultBalance(address asset, int256 delta) external;
/// @notice Modifies a subvault's internal balance by a signed delta (in asset terms)
function modifySubvaultBalance(address subvault, address asset, int256 delta) external;
/// @notice Sets the maximum allowable approximate (soft) balance for the entire vault in shares
function setVaultLimit(int256 limit) external;
/// @notice Sets the maximum allowable approximate (soft) balance for a specific subvault
function setSubvaultLimit(address subvault, int256 limit) external;
/// @notice Allows specific assets to be used in a subvault
function allowSubvaultAssets(address subvault, address[] calldata assets) external;
/// @notice Disallows specific assets from being used in a subvault
function disallowSubvaultAssets(address subvault, address[] calldata assets) external;
/// @notice Modifies the vault's pending balances by a signed delta (in asset terms)
function modifyPendingAssets(address asset, int256 change) external;
/// @notice Sets the vault address this RiskManager is associated with
function setVault(address vault_) external;
/// @notice Emitted when a limit is set for a specific subvault
event SetSubvaultLimit(address indexed subvault, int256 limit);
/// @notice Emitted when the vault limit is updated
event SetVaultLimit(int256 limit);
/// @notice Emitted when assets are newly allowed for a subvault
event AllowSubvaultAssets(address indexed subvault, address[] assets);
/// @notice Emitted when assets are disallowed from a subvault
event DisallowSubvaultAssets(address indexed subvault, address[] assets);
/// @notice Emitted when pending asset balances are updated
event ModifyPendingAssets(
address indexed asset, int256 change, int256 pendingAssetsAfter, int256 pendingSharesAfter
);
/// @notice Emitted when the vault balance is changed
event ModifyVaultBalance(address indexed asset, int256 shares, int256 newBalance);
/// @notice Emitted when a subvault's balance is changed
event ModifySubvaultBalance(address indexed subvault, address indexed asset, int256 change, int256 newBalance);
/// @notice Emitted when the associated vault address is set
event SetVault(address indexed vault);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "../permissions/IMellowACL.sol";
import "./IBaseModule.sol";
/// @notice Interface for the ACLModule, implements IMellowACL
interface IACLModule is IMellowACL {
/// @notice Thrown when a zero address is provided
error ZeroAddress();
/// @notice Thrown when an unauthorized caller attempts a restricted operation
error Forbidden();
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "../factories/IFactory.sol";
/// @title ISubvaultModule
/// @notice Interface for a Subvault module used in modular vault architecture.
/// @dev A Subvault is a child vault that holds assets and can release them to its parent vault upon request.
/// Each Subvault is isolated and may integrate with external protocols through its own Verifier & CallModule, enabling
/// fine-grained delegation of liquidity while maintaining separation between subvaults.
interface ISubvaultModule {
/// @notice Reverts when a caller is not the associated vault.
error NotVault();
/// @notice Storage laylout of ISubvaultModule.
/// @dev Stores the address of the parent vault that has permission to pull assets.
struct SubvaultModuleStorage {
address vault;
}
/// @notice Returns the address of the parent vault contract.
/// @return address The vault address allowed to interact with this subvault.
function vault() external view returns (address);
/// @notice Transfers a specified amount of an asset to the vault.
/// @dev Can only be called by the parent vault.
/// @param asset Address of the ERC20 token or native ETH.
/// @param value Amount of the asset to transfer.
function pullAssets(address asset, uint256 value) external;
/// @notice Emitted when assets are pulled from the subvault to the vault.
/// @param asset Address of the asset that was pulled.
/// @param to Recipient address (must be the vault).
/// @param value Amount of the asset that was pulled.
event AssetsPulled(address indexed asset, address indexed to, uint256 value);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "../permissions/IVerifier.sol";
import "./IBaseModule.sol";
/// @notice Interface for the VerifierModule, which integrates with an external IVerifier contract
/// @dev Used in modular systems to delegate permission checks or validation to a shared verifier
interface IVerifierModule is IBaseModule {
/// @notice Thrown when a zero address is provided
error ZeroAddress();
/// @notice Internal storage structure for VerifierModule
struct VerifierModuleStorage {
address verifier; // Address of the IVerifier contract used for external call validation
}
/// @notice Returns the current verifier contract used by the module
/// @return Address of the IVerifier contract
function verifier() external view returns (IVerifier);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
/// @title IFactoryEntity
interface IFactoryEntity {
/// @notice Initializes the factory-created entity with arbitrary initialization data.
/// @param initParams The initialization parameters.
function initialize(bytes calldata initParams) external;
/// @notice Emitted once the entity has been initialized.
/// @param initParams The initialization parameters.
event Initialized(bytes initParams);
}// 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;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "./IHook.sol";
/// @title IRedeemHook
/// @notice Interface for redeem-side hooks that implement custom logic during asset redemptions.
interface IRedeemHook is IHook {
/// @notice Returns the amount of liquid (immediately withdrawable) assets available for a given token.
/// @dev Used by queues to determine how much can be processed in the current redemption cycle.
/// @param asset The address of the ERC20 asset to check.
/// @return assets The amount of the asset that is liquid and available.
function getLiquidAssets(address asset) external view returns (uint256 assets);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "../factories/IFactoryEntity.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
/// @notice Interface for the FeeManager contract
/// @dev Handles deposit, redeem, performance, and protocol fees for vaults, and tracks per-vault price/timestamp states
interface IFeeManager is IFactoryEntity {
/// @notice Thrown when a required address is zero
error ZeroAddress();
/// @notice Thrown when the sum of all fees exceeds 100% (1e6 in D6 precision)
error InvalidFees(uint24 depositFeeD6, uint24 redeemFeeD6, uint24 performanceFeeD6, uint24 protocolFeeD6);
/// @notice Thrown when trying to overwrite a vault's base asset that was already set
error BaseAssetAlreadySet(address vault, address baseAsset);
/// @notice Storage layout used internally by FeeManager
struct FeeManagerStorage {
address feeRecipient; // Address that collects all fee shares
uint24 depositFeeD6; // Deposit fee in 6 decimals (e.g. 10000 = 1%)
uint24 redeemFeeD6; // Redeem fee in 6 decimals
uint24 performanceFeeD6; // Performance fee applied on price increase (6 decimals)
uint24 protocolFeeD6; // Protocol fee applied over time (6 decimals annualized)
mapping(address vault => uint256) timestamps; // Last update timestamp for protocol fee accrual
mapping(address vault => uint256) minPriceD18; // Lowests price seen for performance fee trigger (price * assets = shares)
mapping(address vault => address) baseAsset; // Base asset used to evaluate price-based fees
}
/// @notice Returns the current fee recipient address
function feeRecipient() external view returns (address);
/// @notice Returns the configured deposit fee (in D6 precision)
function depositFeeD6() external view returns (uint24);
/// @notice Returns the configured redeem fee (in D6 precision)
function redeemFeeD6() external view returns (uint24);
/// @notice Returns the configured performance fee (in D6 precision)
function performanceFeeD6() external view returns (uint24);
/// @notice Returns the configured protocol fee (in D6 precision per year)
function protocolFeeD6() external view returns (uint24);
/// @notice Returns the last recorded timestamp for a given vault (used for protocol fee accrual)
function timestamps(address vault) external view returns (uint256);
/// @notice Returns the last recorded min price for a vault's base asset (used for performance fee)
function minPriceD18(address vault) external view returns (uint256);
/// @notice Returns the base asset configured for a vault
function baseAsset(address vault) external view returns (address);
/// @notice Calculates the deposit fee in shares based on the amount
/// @param amount Number of shares being deposited
/// @return Fee in shares to be deducted
function calculateDepositFee(uint256 amount) external view returns (uint256);
/// @notice Calculates the redeem fee in shares based on the amount
/// @param amount Number of shares being redeemed
/// @return Fee in shares to be deducted
function calculateRedeemFee(uint256 amount) external view returns (uint256);
/// @notice Calculates the combined performance and protocol fee in shares
/// @param vault Address of the vault
/// @param asset Asset used for pricing
/// @param priceD18 Current vault share price for the specific `asset` (price = shares / assets)
/// @param totalShares Total shares of the vault
/// @return shares Fee to be added in shares
function calculateFee(address vault, address asset, uint256 priceD18, uint256 totalShares)
external
view
returns (uint256 shares);
/// @notice Sets the recipient address for all collected fees
/// @param feeRecipient_ Address to receive fees
function setFeeRecipient(address feeRecipient_) external;
/// @notice Sets the global fee configuration (deposit, redeem, performance, protocol)
/// @dev Total of all fees must be <= 1e6 (i.e. 100%)
function setFees(uint24 depositFeeD6_, uint24 redeemFeeD6_, uint24 performanceFeeD6_, uint24 protocolFeeD6_)
external;
/// @notice Sets the base asset for a vault, required for performance fee calculation
/// @dev Can only be set once per vault
function setBaseAsset(address vault, address baseAsset_) external;
/// @notice Updates the vault's state (min price and timestamp) based on asset price only if `asset` == `baseAssets[vault]`
/// @dev Used by the vault to notify FeeManager of new price highs or protocol fee accrual checkpoints
function updateState(address asset, uint256 priceD18) external;
/// @notice Emitted when the fee recipient is changed
event SetFeeRecipient(address indexed feeRecipient);
/// @notice Emitted when the fee configuration is updated
event SetFees(uint24 depositFeeD6, uint24 redeemFeeD6, uint24 performanceFeeD6, uint24 protocolFeeD6);
/// @notice Emitted when a vault's base asset is set
event SetBaseAsset(address indexed vault, address indexed baseAsset);
/// @notice Emitted when the vault's min price or timestamp is updated
event UpdateState(address indexed vault, address indexed asset, uint256 priceD18);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "../factories/IFactoryEntity.sol";
import "../modules/IACLModule.sol";
import "../modules/IShareModule.sol";
/// @title IShareManager
/// @notice Interface for managing share allocations, permissions, minting, burning, and user restrictions
interface IShareManager is IFactoryEntity {
/// @notice Unauthorized call
error Forbidden();
/// @notice Attempted to mint more shares than pre-allocated
error InsufficientAllocatedShares(uint256 value, uint256 allocated);
/// @notice Global lockup not yet expired
error GlobalLockupNotExpired(uint256 timestamp, uint32 globalLockup);
/// @notice Blacklisted account tried to interact
error Blacklisted(address account);
/// @notice Transfers are currently paused
error TransferPaused();
/// @notice Minting is currently paused
error MintPaused();
/// @notice Burning is currently paused
error BurnPaused();
/// @notice Mint would exceed share limit
error LimitExceeded(uint256 value, uint256 limit);
/// @notice Account is not whitelisted to deposit
error NotWhitelisted(address account);
/// @notice Transfer between accounts not allowed by whitelist
error TransferNotAllowed(address from, address to);
/// @notice Provided value was zero
error ZeroValue();
/// @notice Storage layout for ShareManager.
struct ShareManagerStorage {
/// @notice Address of the vault associated with this ShareManager.
address vault;
/// @notice Bitpacked configuration flags controlling global minting, burning, transfers, whitelists and lockups.
uint256 flags;
/// @notice Total shares allocated to all accounts (includes pending shares).
uint256 allocatedShares;
/// @notice Merkle root for verifying account permissions (used for deposits if whitelist flags are active).
bytes32 whitelistMerkleRoot;
/// @notice Tracks individual account permissions, blacklist status, and lockup.
mapping(address account => AccountInfo) accounts;
}
/// @notice Per-account permission and state tracking.
struct AccountInfo {
/// @notice Whether the account is allowed to deposit when the `hasWhitelist` flag is active.
bool canDeposit;
/// @notice Whether the account is allowed to transfer (send or receive) shares when the `hasTransferWhitelist` flag is active.
bool canTransfer;
/// @notice Whether the account is disallowed to send or receive shares.
bool isBlacklisted;
}
/// @notice Decoded configuration flags from `ShareManagerStorage.flags`.
struct Flags {
/// @notice If true, minting is globally paused.
bool hasMintPause;
/// @notice If true, burning of shares is globally paused.
bool hasBurnPause;
/// @notice If true, transfers of shares between accounts are globally paused (only for TokenizedShareManager).
bool hasTransferPause;
/// @notice If true, deposit access is controlled via onchain whitelist (mapping `accounts`).
bool hasWhitelist;
/// @notice If true, transfer access is controlled via offchain whitelist (`whitelistMerkleRoot`).
bool hasTransferWhitelist;
/// @notice Global lockup duration (timestamp in seconds) applied to all users in the vault.
uint32 globalLockup;
}
/// @return bytes32 Returns role required to set global flags
function SET_FLAGS_ROLE() external view returns (bytes32);
/// @return bytes32 Returns role required to set per-user flags
function SET_ACCOUNT_INFO_ROLE() external view returns (bytes32);
/// @return bytes32 Returns role required to set new merkle root for whitelist validation
function SET_WHITELIST_MERKLE_ROOT_ROLE() external view returns (bytes32);
/// @return address Returns address of the vault using this ShareManager
function vault() external view returns (address);
/// @return uint256 Total allocated shares
function allocatedShares() external view returns (uint256);
/// @return f Returns current flag structure
function flags() external view returns (Flags memory f);
/// @return bytes32 Returns Merkle root used for deposit whitelist verification
function whitelistMerkleRoot() external view returns (bytes32);
/// @return bool Returns true whether depositor is allowed under current Merkle root and flag settings
function isDepositorWhitelisted(address account, bytes32[] calldata merkleProof) external view returns (bool);
/// @return shares Returns total shares (active + claimable) for an account
function sharesOf(address account) external view returns (uint256 shares);
/// @return shares Returns claimable shares for an account
function claimableSharesOf(address account) external view returns (uint256 shares);
/// @return shares Returns active shares for an account
function activeSharesOf(address account) external view returns (uint256 shares);
/// @return shares Returns total active shares across the vault
function activeShares() external view returns (uint256 shares);
/// @return shares Total shares including active and claimable
function totalShares() external view returns (uint256 shares);
/// @return info Returns account-specific configuration and permissions
function accounts(address account) external view returns (AccountInfo memory info);
/// @notice Internal checks for mint/burn/transfer under flags, lockups, blacklists, etc.
function updateChecks(address from, address to) external view;
/// @notice Triggers share claiming from queue to user
function claimShares(address account) external;
/// @notice Sets permissions and flags for a specific account
function setAccountInfo(address account, AccountInfo memory info) external;
/// @notice Sets global flag bitmask controlling mints, burns, lockups, etc.
function setFlags(Flags calldata flags) external;
/// @notice Sets new whitelist merkle root
function setWhitelistMerkleRoot(bytes32 whitelistMerkleRoot) external;
/// @notice Allocates `shares` that can be later minted via `mintAllocatedShares`
function allocateShares(uint256 shares) external;
/// @notice Mints shares from the allocated pool
function mintAllocatedShares(address to, uint256 shares) external;
/// @notice Mints new shares to a user directly
function mint(address to, uint256 shares) external;
/// @notice Burns user's shares
function burn(address account, uint256 amount) external;
/// @notice 'Locks' user's shares by transferring them to the vault balance
function lock(address acount, uint256 amount) external;
/// @notice One-time vault assignment during initialization
function setVault(address vault_) external;
/// @notice Emitted when shares are allocated or removed (positive/negative)
event AllocateShares(int256 value);
/// @notice Emitted when new shares are minted
event Mint(address indexed account, uint256 shares);
/// @notice Emitted when shares are burned
event Burn(address indexed account, uint256 shares);
/// @notice Emitted when shares are locked
event Lock(address account, uint256 value);
/// @notice Emitted when global flag configuration is changed
event SetFlags(Flags flags);
/// @notice Emitted when whitelist merkle root is changed
event SetWhitelistMerkleRoot(bytes32 newWhitelistMerkleRoot);
/// @notice Emitted when a user account is updated
event SetAccountInfo(address indexed account, AccountInfo info);
/// @notice Emitted when vault is set
event SetVault(address indexed vault);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/access/IAccessControl.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../factories/IFactoryEntity.sol";
import "../modules/IShareModule.sol";
/// @title IOracle
/// @notice Interface for the vault price oracle responsible for submitting, validating, and propagating price reports.
/// @dev The reported price is structured such that the invariant `shares = assets * price` holds true.
/// @dev Typically used to coordinate deposit, redemption and limit operations across queues, the vault and subvaults.
interface IOracle is IFactoryEntity {
/// @notice Thrown when an asset is not supported by the oracle.
/// @param asset The address of the unsupported asset.
error UnsupportedAsset(address asset);
/// @notice Thrown when attempting to register an asset that is already supported.
/// @param asset The address of the already supported asset.
error AlreadySupportedAsset(address asset);
/// @notice Thrown when a suspicious report fails validation due to unexpected data.
/// @dev This includes mismatches in price, timestamp, or incorrect `isSuspicios` flag.
error InvalidReport();
/// @notice Thrown when a function receives a zero value where a non-zero value is required.
error ZeroValue();
/// @notice Thrown when a report is submitted before the required timeout period,
/// and the previous report was not marked as suspicious.
/// @param timestamp The submitted report timestamp.
/// @param minTimestamp The earliest acceptable timestamp based on timeout configuration.
error TooEarly(uint256 timestamp, uint256 minTimestamp);
/// @notice Thrown when the submitted price violates oracle security rules.
/// @param priceD18 The submitted price in 18-decimal fixed-point format.
error InvalidPrice(uint256 priceD18);
/// @notice Thrown when the caller lacks the necessary permission to perform the operation.
error Forbidden();
/// @notice Configuration parameters that govern oracle price validation logic and reporting cadence.
struct SecurityParams {
/// @notice Maximum absolute difference between the new and previous price, beyond which the report is rejected.
uint224 maxAbsoluteDeviation;
/// @notice Absolute deviation threshold beyond which the report is flagged as suspicious (but not rejected).
uint224 suspiciousAbsoluteDeviation;
/// @notice Maximum allowed relative price deviation (as a fixed-point value with 18 decimals), beyond which the report is rejected.
/// Example: 0.05 * 1e18 = 5% max relative deviation.
uint64 maxRelativeDeviationD18;
/// @notice Relative deviation threshold for flagging suspicious reports (in 18-decimal format),
/// beyond which the report is flagged as suspicious (but not rejected).
/// Example: 0.03 * 1e18 = 3% suspicious threshold.
uint64 suspiciousRelativeDeviationD18;
/// @notice Minimum time in seconds required between two valid non-suspicious reports.
uint32 timeout;
/// @notice Minimum age (in seconds) a deposit request must have to be eligible for processing by a report submitted at the current timestamp.
uint32 depositInterval;
/// @notice Minimum age (in seconds) a redemption request must have to be eligible for processing by a report submitted at the current timestamp.
uint32 redeemInterval;
}
/// @notice Struct representing a price report submitted to the oracle.
/// @dev Used in vault accounting where `shares = (assets * priceD18) / 1e18`.
struct Report {
address asset; // Address of the asset the price refers to
uint224 priceD18; // Asset price in 18-decimal fixed-point format
}
/// @notice Detailed price report used for validation and tracking
struct DetailedReport {
uint224 priceD18; // Reported asset price in 18-decimal fixed-point format
uint32 timestamp; // Timestamp when the report was submitted
bool isSuspicious; // Whether the report is flagged as suspicious according to deviation thresholds
}
/// @notice Storage layout of the oracle
struct OracleStorage {
IShareModule vault; // The vault module that integrates with oracle reports
SecurityParams securityParams; // Oracle security configuration
EnumerableSet.AddressSet supportedAssets; // List of supported assets
mapping(address asset => DetailedReport) reports; // Latest report per asset
}
/// @notice Role required to submit reports
function SUBMIT_REPORTS_ROLE() external view returns (bytes32);
/// @notice Role required to accept suspicious reports
function ACCEPT_REPORT_ROLE() external view returns (bytes32);
/// @notice Role required to update security parameters
function SET_SECURITY_PARAMS_ROLE() external view returns (bytes32);
/// @notice Role required to add new supported assets
function ADD_SUPPORTED_ASSETS_ROLE() external view returns (bytes32);
/// @notice Role required to remove supported assets
function REMOVE_SUPPORTED_ASSETS_ROLE() external view returns (bytes32);
/// @notice Returns the connected vault module
function vault() external view returns (IShareModule);
/// @notice Returns current security parameters
function securityParams() external view returns (SecurityParams memory);
/// @notice Returns total count of supported assets
function supportedAssets() external view returns (uint256);
/// @notice Returns the supported asset at a specific index
/// @param index Index in the supported asset set
function supportedAssetAt(uint256 index) external view returns (address);
/// @notice Checks whether an asset is supported
/// @param asset Address of the asset
function isSupportedAsset(address asset) external view returns (bool);
/// @notice Returns the most recent detailed report for an asset
/// @param asset Address of the asset
function getReport(address asset) external view returns (DetailedReport memory);
/// @notice Validates the given price for a specific asset based on oracle security parameters.
/// @dev Evaluates both absolute and relative deviation limits to determine whether the price is valid or suspicious.
/// @param priceD18 Price to validate, in 18-decimal fixed-point format.
/// @param asset Address of the asset being evaluated.
/// @return isValid True if the price is within maximum allowed deviation.
/// @return isSuspicious True if the price exceeds the suspicious deviation threshold.
function validatePrice(uint256 priceD18, address asset) external view returns (bool isValid, bool isSuspicious);
/// @notice Submits price reports for supported assets.
/// @dev Processes pending deposit and redemption requests across DepositQueue and RedeemQueue contracts.
/// The core processing logic is determined by the ShareModule and Queue contracts.
/// Only callable by accounts with the `SUBMIT_REPORTS_ROLE`.
/// @param reports An array of price reports, each specifying the target asset and its latest price (in 18 decimals).
///
/// @dev Note: Submitted prices MUST reflect protocol and performance fee deductions, ensuring accurate share issuance.
function submitReports(Report[] calldata reports) external;
/// @notice Accepts a previously suspicious report
/// @dev Callable only by account with `ACCEPT_REPORT_ROLE`
/// @param asset Address of the asset
/// @param priceD18 Timestamp that must match existing suspicious report
/// @param timestamp Timestamp that must match existing suspicious report
function acceptReport(address asset, uint256 priceD18, uint32 timestamp) external;
/// @notice Updates oracle security parameters
/// @param securityParams_ New security settings
function setSecurityParams(SecurityParams calldata securityParams_) external;
/// @notice Adds multiple new assets to the supported set
/// @param assets Array of asset addresses to add
function addSupportedAssets(address[] calldata assets) external;
/// @notice Removes assets from the supported set
/// @param assets Array of asset addresses to remove
function removeSupportedAssets(address[] calldata assets) external;
/// @notice Sets the associated vault
/// @param vault_ Address of the vault module
function setVault(address vault_) external;
/// @notice Emitted when price reports are submitted
event ReportsSubmitted(Report[] reports);
/// @notice Emitted when a suspicious report is accepted
event ReportAccepted(address indexed asset, uint224 indexed priceD18, uint32 indexed timestamp);
/// @notice Emitted when new security parameters are set
event SecurityParamsSet(SecurityParams securityParams);
/// @notice Emitted when new assets are added
event SupportedAssetsAdded(address[] assets);
/// @notice Emitted when supported assets are removed
event SupportedAssetsRemoved(address[] assets);
/// @notice Emitted when vault is set
event SetVault(address indexed vault);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/structs/Checkpoints.sol";
import "../../libraries/FenwickTreeLibrary.sol";
import "../managers/IRiskManager.sol";
import "../modules/IShareModule.sol";
import "../modules/IVaultModule.sol";
import "./IQueue.sol";
/// @title IDepositQueue
/// @notice Interface for deposit queues that manage time-delayed deposit requests with oracle-based pricing.
/// @dev Implements request creation, cancellation, and oracle-based price batch processing.
///
/// # Overview
/// A `DepositQueue` manages deposits for a specific asset with a time delay enforced by an oracle (`depositInterval`). It enforces the following invariants:
/// 1. Each user may have only one pending deposit request at a time.
/// 2. Each request is defined by `(amount, timestamp)`.
/// 3. Based on oracle reports queue determines when deposit requests are processed.
/// A report handles only those requests older than a configured `depositInterval`.
///
/// Once an oracle report is submitted at `reportTimestamp`, it processes all requests with `timestamp <= reportTimestamp - depositInterval`, converting asset deposits into vault shares at the reported price.
///
/// # User Cancellation
/// Users can cancel pending deposit requests before they are processed. This ensures a binary lifecycle:
/// - Either a user has a pending request they can cancel, or
/// - The request has been executed and the user owns shares.
///
/// # Scalability Challenge
/// Vaults can receive thousands of deposit requests per day. Processing each request individually is gas-inefficient.
/// To solve this, a **Fenwick Tree** is used to maintain prefix sums of deposits per timestamp.
///
/// # Fenwick Tree Usage
/// - When a user deposits `amount` at time `T`, the system records `fenwickTree[T] += amount`.
/// - If the user cancels, then `fenwickTree[T] -= amount`.
/// - On oracle report at time `reportTimestamp`, the system calculates:
/// `fenwickTree.getSum(latestHandledTimestamp + 1, reportTimestamp - depositInterval)`
/// to determine the total amount to convert into vault shares at the reported price.
///
/// The vault uses **lazy propagation** to calculate claimable shares per user without eagerly updating all balances in the `handleReport` processing.
/// Shares become fully claimed on the next interaction (e.g., claim, transfer or new deposit).
///
/// Additionally, **timestamp compression (coordinate compression)** is used to track in FenwickTree only timestamps where actual requests were made, reducing storage overhead.
interface IDepositQueue is IQueue {
/// @notice Thrown when a user is not allowed to deposit.
error DepositNotAllowed();
/// @notice Thrown if a new deposit is attempted while a pending request exists.
error PendingRequestExists();
/// @notice Thrown when attempting to cancel a deposit request that has become claimable.
error ClaimableRequestExists();
/// @notice Thrown when trying to cancel a non-existent deposit request.
error NoPendingRequest();
/// @notice Storage layout for managing the state of a deposit queue.
struct DepositQueueStorage {
/// @dev Iterator representing the number of fully processed `timestamps`.
/// Each timestamp may correspond to multiple user requests.
uint256 handledIndices;
/// @dev Mapping of user address to their latest deposit request.
/// Each request is stored as a checkpoint with timestamp (key) and asset amount (value).
mapping(address account => Checkpoints.Checkpoint224) requestOf;
/// @dev Fenwick tree tracking cumulative asset deposits by timestamp indices.
/// Enables efficient range sum queries and updates for oracle processing.
FenwickTreeLibrary.Tree requests;
/// @dev Price history reported by the oracle (indexed by timestamp).
/// Used to convert deposited assets into vault shares.
Checkpoints.Trace224 prices;
/// @dev Total number of unclaimed requests.
/// Used to check that the queue can be deleted.
uint256 unclaimedRequests;
}
/// @notice Returns the number of shares that can currently be claimed by the given account.
/// @param account Address of the user.
/// @return shares Amount of claimable shares.
function claimableOf(address account) external view returns (uint256 shares);
/// @notice Retrieves the timestamp and asset amount for a user's pending deposit request.
/// @param account Address of the user.
/// @return timestamp When the deposit was requested.
/// @return assets Amount of assets deposited.
function requestOf(address account) external view returns (uint256 timestamp, uint256 assets);
/// @notice Returns the number of unclaimed requests.
/// @return unclaimedRequests Number of unclaimed requests.
function unclaimedRequests() external view returns (uint256 unclaimedRequests);
/// @notice Submits a new deposit request into the queue.
/// @dev Reverts if a previous pending (not yet claimable) request exists.
/// @param assets Amount of assets to deposit.
/// @param referral Optional referral address.
/// @param merkleProof Merkle proof for whitelist validation, if required.
function deposit(uint224 assets, address referral, bytes32[] calldata merkleProof) external payable;
/// @notice Cancels the caller's current pending deposit request.
/// @dev Refunds the originally deposited assets. Reverts with `ClaimableRequestExists` if the
/// request has already become claimable.
function cancelDepositRequest() external;
/// @notice Claims shares from a fulfilled deposit request for a specific account.
/// @param account Address for which to claim shares.
/// @return success Boolean indicating whether a claim was successful.
function claim(address account) external returns (bool success);
/// @notice Emitted when a new deposit request is submitted.
/// @param account The depositor's address.
/// @param referral Optional referral address.
/// @param assets Amount of assets deposited.
/// @param timestamp Timestamp when the request was created.
event DepositRequested(address indexed account, address indexed referral, uint224 assets, uint32 timestamp);
/// @notice Emitted when a pending deposit request is canceled.
/// @param account Address of the user who canceled the request.
/// @param assets Amount of assets refunded.
/// @param timestamp Timestamp of the original request.
event DepositRequestCanceled(address indexed account, uint256 assets, uint32 timestamp);
/// @notice Emitted when a deposit request is successfully claimed into shares.
/// @param account Address receiving the shares.
/// @param shares Number of shares claimed.
/// @param timestamp Timestamp of the original deposit request.
event DepositRequestClaimed(address indexed account, uint256 shares, uint32 timestamp);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/StorageSlot.sol";
/// @notice Interface for base module functionality shared across all modules
/// @dev Provides basic utilities such as raw storage access, ERC721 receiver support and `receive()` callback
interface IBaseModule is IERC721Receiver {
/// @notice Returns a reference to a storage slot as a `StorageSlot.Bytes32Slot` struct
/// @param slot The keccak256-derived storage slot identifier
/// @return A struct exposing the `.value` field stored at the given slot
function getStorageAt(bytes32 slot) external pure returns (StorageSlot.Bytes32Slot memory);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.20;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/transparent/TransparentUpgradeableProxy.sol)
pragma solidity ^0.8.22;
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
import {ERC1967Proxy} from "../ERC1967/ERC1967Proxy.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {ProxyAdmin} from "./ProxyAdmin.sol";
/**
* @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
* does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch
* mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
* include them in the ABI so this interface must be used to interact with it.
*/
interface ITransparentUpgradeableProxy is IERC1967 {
/// @dev See {UUPSUpgradeable-upgradeToAndCall}
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable;
}
/**
* @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.
* 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to
* the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating
* the proxy admin cannot fallback to the target implementation.
*
* These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a
* dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to
* call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and
* allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative
* interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.
*
* NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
* inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch
* mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
* fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
* implementation.
*
* NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a
* meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.
*
* IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an
* immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be
* overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an
* undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot
* is generally fine if the implementation is trusted.
*
* WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the
* compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new
* function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This
* could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
// An immutable address for the admin to avoid unnecessary SLOADs before each call
// at the expense of removing the ability to change the admin once it's set.
// This is acceptable if the admin is always a ProxyAdmin instance or similar contract
// with its own ability to transfer the permissions to another account.
address private immutable _admin;
/**
* @dev The proxy caller is the current admin, and can't fallback to the proxy target.
*/
error ProxyDeniedAdminAccess();
/**
* @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,
* backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in
* {ERC1967Proxy-constructor}.
*/
constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) {
_admin = address(new ProxyAdmin(initialOwner));
// Set the storage value and emit an event for ERC-1967 compatibility
ERC1967Utils.changeAdmin(_proxyAdmin());
}
/**
* @dev Returns the admin of this proxy.
*/
function _proxyAdmin() internal view virtual returns (address) {
return _admin;
}
/**
* @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.
*/
function _fallback() internal virtual override {
if (msg.sender == _proxyAdmin()) {
if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
revert ProxyDeniedAdminAccess();
} else {
_dispatchUpgradeToAndCall();
}
} else {
super._fallback();
}
}
/**
* @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
function _dispatchUpgradeToAndCall() private {
(address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
ERC1967Utils.upgradeToAndCall(newImplementation, data);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlEnumerableUpgradeable.sol";
/// @notice Interface for the MellowACL contract, which extends OpenZeppelin's AccessControlEnumerable
/// @dev Adds tracking of which roles are actively in use (i.e., assigned to at least one address)
interface IMellowACL is IAccessControlEnumerable {
/// @notice Storage layout used to track actively assigned roles
struct MellowACLStorage {
EnumerableSet.Bytes32Set supportedRoles; // Set of roles that have at least one assigned member
}
/// @notice Returns the total number of unique roles that are currently assigned
function supportedRoles() external view returns (uint256);
/// @notice Returns the role at the specified index in the set of active roles
/// @param index Index within the supported role set
/// @return role The bytes32 identifier of the role
function supportedRoleAt(uint256 index) external view returns (bytes32);
/// @notice Checks whether a given role is currently active (i.e., has at least one member)
/// @param role The bytes32 identifier of the role to check
/// @return isActive True if the role has any members assigned
function hasSupportedRole(bytes32 role) external view returns (bool);
/// @notice Emitted when a new role is granted for the first time
event RoleAdded(bytes32 indexed role);
/// @notice Emitted when a role loses its last member
event RoleRemoved(bytes32 indexed role);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts/access/IAccessControl.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../factories/IFactoryEntity.sol";
import "./ICustomVerifier.sol";
/// @notice Interface for the Verifier contract, used to validate allowed calls via multiple verification mechanisms
interface IVerifier is IFactoryEntity {
/// @notice Thrown when a caller lacks necessary permissions
error Forbidden();
/// @notice Thrown when a call fails verification
error VerificationFailed();
/// @notice Thrown when a required value (e.g. address) is zero
error ZeroValue();
/// @notice Thrown when input array lengths mismatch
error InvalidLength();
/// @notice Thrown when attempting to allow an already allowed CompactCall
error CompactCallAlreadyAllowed(address who, address where, bytes4 selector);
/// @notice Thrown when attempting to disallow a non-existent CompactCall
error CompactCallNotFound(address who, address where, bytes4 selector);
/// @notice Represents a minimal function call format using only selector-level granularity.
/// @dev Used in compact verification where only caller, target, and function selector are validated.
struct CompactCall {
address who; // The address initiating the call (caller)
address where; // The target contract address
bytes4 selector; // 4-byte function selector (first 4 bytes of calldata)
}
/// @notice Represents a full function call with calldata and ETH value.
/// @dev Used in extended verification types where arguments and call value must be validated.
struct ExtendedCall {
address who; // The address initiating the call (caller)
address where; // The target contract address
uint256 value; // ETH value sent with the call
bytes data; // Full calldata (function selector + encoded arguments)
}
/// @notice Internal storage layout used by the Verifier contract.
/// @dev Tracks verification configuration and access control data for calls made by the vault.
struct VerifierStorage {
address vault; // The vault that owns this verifier.
bytes32 merkleRoot; // Root of the Merkle tree used in Merkle-based verification modes
EnumerableSet.Bytes32Set compactCallHashes; // Set of approved hashed CompactCall entries for ONCHAIN_COMPACT verification types
mapping(bytes32 => CompactCall) compactCalls; // Optional mapping to recover original CompactCall from hash
}
/// @notice Enum defining the method used to verify a function call authorization.
enum VerificationType {
/// @dev Compact on-chain verification.
/// Checks if `keccak256(abi.encode(who, where, selector))` exists in the verifier's `compactCallHashes` set.
ONCHAIN_COMPACT,
/// @dev Merkle-based verification of a compact call.
/// Validates a Merkle proof for `keccak256(abi.encode(who, where, selector))` against a stored Merkle root.
MERKLE_COMPACT,
/// @dev Merkle-based verification of an extended call.
/// Validates a Merkle proof for `keccak256(abi.encode(who, where, value, data))` against a stored Merkle root.
MERKLE_EXTENDED,
/// @dev Delegated verification via external contract.
/// Forwards call details `abi.encode(address customVerifier, customVerifierSpecificData)`
/// to a custom verifier contract implementing `ICustomVerifier`.
CUSTOM_VERIFIER
}
/// @notice Struct containing all inputs required to verify a delegated function call.
struct VerificationPayload {
/// @dev The method used to verify the delegated call.
VerificationType verificationType;
/// @dev Encoded payload to be verified, varies by verification type:
/// - ONCHAIN_COMPACT: empty, checking directly that `keccak256(abi.encode(who, where, selector))` is allowed
/// - MERKLE_COMPACT: `abi.encodePacked(keccak256(abi.encode(who, where, selector)))` to validates a Merkle proof
/// - MERKLE_EXTENDED: `abi.encodePacked(keccak256(abi.encode(who, where, value, data)))` to validates a Merkle proof
/// - CUSTOM_VERIFIER: `abi.encode(address customVerifier, customVerifierSpecificData)`
bytes verificationData;
/// @dev Merkle proof used to validate the `verificationType` and `verificationData` for MERKLE_COMPACT,
/// MERKLE_EXTENDED, and CUSTOM_VERIFIER types.
bytes32[] proof;
}
/// @notice Role identifier for setting Merkle root
function SET_MERKLE_ROOT_ROLE() external view returns (bytes32);
/// @notice Role identifier for permitted callers
function CALLER_ROLE() external view returns (bytes32);
/// @notice Role identifier for allowing new CompactCalls
function ALLOW_CALL_ROLE() external view returns (bytes32);
/// @notice Role identifier for removing CompactCalls
function DISALLOW_CALL_ROLE() external view returns (bytes32);
/// @notice Returns the vault associated to this Verifier contract
function vault() external view returns (IAccessControl);
/// @notice Returns the current Merkle root
function merkleRoot() external view returns (bytes32);
/// @notice Returns number of currently allowed compact calls
function allowedCalls() external view returns (uint256);
/// @notice Returns the compact call at a specific index
function allowedCallAt(uint256 index) external view returns (CompactCall memory);
/// @notice Checks if a CompactCall is explicitly allowed
function isAllowedCall(address who, address where, bytes calldata callData) external view returns (bool);
/// @notice Computes the hash of a CompactCall
function hashCall(CompactCall memory call) external pure returns (bytes32);
/// @notice Computes the hash of an ExtendedCall
function hashCall(ExtendedCall memory call) external pure returns (bytes32);
/// @notice Validates a function call using the provided verification payload, reverts on failure
function verifyCall(
address who,
address where,
uint256 value,
bytes calldata data,
VerificationPayload calldata verificationPayload
) external view;
/// @return bool Returns whether a given call passes verification
function getVerificationResult(
address who,
address where,
uint256 value,
bytes calldata callData,
VerificationPayload calldata verificationPayload
) external view returns (bool);
/// @notice Sets the Merkle root used for verification
function setMerkleRoot(bytes32 merkleRoot_) external;
/// @notice Adds a list of CompactCalls to the allowlist
function allowCalls(CompactCall[] calldata compactCalls) external;
/// @notice Removes a list of CompactCalls from the allowlist
function disallowCalls(CompactCall[] calldata compactCalls) external;
/// @notice Emitted when the Merkle root is set
event SetMerkleRoot(bytes32 merkleRoot);
/// @notice Emitted when a new CompactCall is allowed
event AllowCall(address who, address where, bytes4 selector);
/// @notice Emitted when a CompactCall is disallowed
event DisallowCall(address who, address where, bytes4 selector);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
/// @title IHook
/// @notice Interface for a generic hook contract used to process asset-related logic during queue execution upon oracle reports.
/// @dev This interface is intended for both deposit and redeem queues, where additional logic (e.g. wrapping, redistributions, auto-compounding,
/// liquidity checks) must be executed atomically during queue finalization. Typically called via `delegatecall`.
interface IHook {
/// @notice Executes custom logic for the given asset and amount during queue processing.
/// @dev This function is called via `delegatecall` by the ShareModule or Vault.
/// @param asset The address of the ERC20 asset being processed.
/// @param assets The amount of the asset involved in the operation.
function callHook(address asset, uint256 assets) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.
pragma solidity ^0.8.20;
import {Hashes} from "./Hashes.sol";
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*
* IMPORTANT: Consider memory side-effects when using custom hashing functions
* that access memory in an unsafe way.
*
* NOTE: This library supports proof verification for merkle trees built using
* custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
* leaf inclusion in trees built using non-commutative hashing functions requires
* additional logic that is not supported by this library.
*/
library MerkleProof {
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProof(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function processProof(
bytes32[] memory proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProofCalldata(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function processProofCalldata(
bytes32[] calldata proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProof(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 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 to signal 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. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
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;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
/// @title FenwickTreeLibrary
/// @notice Implements a 0-indexed Fenwick Tree (Binary Indexed Tree) for prefix sum operations.
/// @dev Enables efficient updates and prefix sum queries over a dynamic array.
///
/// # Overview
/// Fenwick Tree is a compact data structure optimized for cumulative frequency computations:
/// - `update(i, delta)` increments the element at index `i` by signed `delta`.
/// - `prefixSum(i)` returns the sum of elements in the range `[0, i]`.
///
/// This library provides:
/// - `O(log n)` time complexity for updates and prefix queries.
/// - `O(1)` fixed cost for extending the tree by doubling its capacity.
/// - Support only for arrays whose lengths are powers of two (2^k).
///
/// # References
/// - https://cp-algorithms.com/data_structures/fenwick.html
/// - https://en.wikipedia.org/wiki/Fenwick_tree
library FenwickTreeLibrary {
/// @notice Thrown when initializing with an invalid length (must be power of 2 and nonzero), or during overflow.
error InvalidLength();
/// @notice Thrown when an index is outside the bounds of the tree.
error IndexOutOfBounds();
/// @notice Internal Fenwick Tree structure using a mapping as a flat array.
struct Tree {
/// @notice Mapping of index to its cumulative value.
mapping(uint256 index => int256) _values;
/// @notice Length of the tree (must be a power of 2).
uint256 _length;
}
/// @notice Initializes the tree with a given length (must be > 0 and power of 2).
/// @param tree The Fenwick tree to initialize.
/// @param length_ The length of the tree.
function initialize(Tree storage tree, uint256 length_) internal {
if (tree._length != 0 || length_ == 0 || (length_ & (length_ - 1)) != 0) {
revert InvalidLength();
}
tree._length = length_;
}
/// @notice Returns the current size of the tree.
/// @param tree The Fenwick tree.
/// @return The length of the tree.
function length(Tree storage tree) internal view returns (uint256) {
return tree._length;
}
/// @notice Doubles the length of the Fenwick tree while preserving internal state.
/// @param tree The Fenwick tree to be extended.
function extend(Tree storage tree) internal {
uint256 length_ = tree._length;
if (length_ >= (1 << 255)) {
revert InvalidLength();
}
tree._length = length_ << 1;
tree._values[(length_ << 1) - 1] = tree._values[length_ - 1];
}
/// @notice Updates the tree at the specified index by a given delta.
/// @param tree The Fenwick tree.
/// @param index Index to modify.
/// @param value Value to add (can be negative).
function modify(Tree storage tree, uint256 index, int256 value) internal {
uint256 length_ = tree._length;
if (index >= length_) {
revert IndexOutOfBounds();
}
if (value == 0) {
return;
}
_modify(tree, index, length_, value);
}
/// @dev Internal function to apply Fenwick update logic.
/// @param tree The Fenwick tree.
/// @param index Index to start updating from.
/// @param length_ Length of the tree.
/// @param value Value to add.
function _modify(Tree storage tree, uint256 index, uint256 length_, int256 value) private {
while (index < length_) {
tree._values[index] += value;
index |= index + 1;
}
}
/// @notice Returns the prefix sum from index 0 to `index` (inclusive).
/// @param tree The Fenwick tree.
/// @param index Right bound index for sum (inclusive).
/// @return prefixSum The sum of values from index 0 to `index`.
function get(Tree storage tree, uint256 index) internal view returns (int256) {
uint256 length_ = tree._length;
if (index >= length_) {
index = length_ - 1;
}
return _get(tree, index);
}
/// @dev Internal function to compute prefix sum up to `index`.
/// @param tree The Fenwick tree.
/// @param index Right bound index for sum (inclusive).
/// @return prefixSum The cumulative sum up to and including `index`.
function _get(Tree storage tree, uint256 index) private view returns (int256 prefixSum) {
assembly ("memory-safe") {
mstore(0x20, tree.slot)
for {} 1 { index := sub(index, 1) } {
mstore(0x00, index)
prefixSum := add(prefixSum, sload(keccak256(0x00, 0x40)))
index := and(index, add(index, 1))
if iszero(index) { break }
}
}
}
/// @notice Returns the sum over the interval [from, to].
/// @param tree The Fenwick tree.
/// @param from Left bound index (inclusive).
/// @param to Right bound index (inclusive).
/// @return The sum over the specified interval.
function get(Tree storage tree, uint256 from, uint256 to) internal view returns (int256) {
if (from > to) {
return 0;
}
return _get(tree, to) - (from == 0 ? int256(0) : _get(tree, from - 1));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for bytes32;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.22;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @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 ERC-1967 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 IERC1967.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 ERC-1967) 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 ERC-1967 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 IERC1967.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 ERC-1967 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 IERC1967.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();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.22;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _implementation() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/transparent/ProxyAdmin.sol)
pragma solidity ^0.8.22;
import {ITransparentUpgradeableProxy} from "./TransparentUpgradeableProxy.sol";
import {Ownable} from "../../access/Ownable.sol";
/**
* @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
* explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
*/
contract ProxyAdmin is Ownable {
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address,address)`
* and `upgradeAndCall(address,address,bytes)` are present, and `upgrade` must be used if no function should be called,
* while `upgradeAndCall` will invoke the `receive` function if the third argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeAndCall(address,address,bytes)` is present, and the third 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 Sets the initial owner who can perform upgrades.
*/
constructor(address initialOwner) Ownable(initialOwner) {}
/**
* @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.
* See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.
*
* Requirements:
*
* - This contract must be the admin of `proxy`.
* - If `data` is empty, `msg.value` must be zero.
*/
function upgradeAndCall(
ITransparentUpgradeableProxy proxy,
address implementation,
bytes memory data
) public payable virtual onlyOwner {
proxy.upgradeToAndCall{value: msg.value}(implementation, data);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/extensions/AccessControlEnumerable.sol)
pragma solidity ^0.8.20;
import {IAccessControlEnumerable} from "@openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol";
import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerable, AccessControlUpgradeable {
using EnumerableSet for EnumerableSet.AddressSet;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControlEnumerable
struct AccessControlEnumerableStorage {
mapping(bytes32 role => EnumerableSet.AddressSet) _roleMembers;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlEnumerable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlEnumerableStorageLocation = 0xc1f6fe24621ce81ec5827caf0253cadb74709b061630e6b55e82371705932000;
function _getAccessControlEnumerableStorage() private pure returns (AccessControlEnumerableStorage storage $) {
assembly {
$.slot := AccessControlEnumerableStorageLocation
}
}
function __AccessControlEnumerable_init() internal onlyInitializing {
}
function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].length();
}
/**
* @dev Return all accounts that have `role`
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function getRoleMembers(bytes32 role) public view virtual returns (address[] memory) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
return $._roleMembers[role].values();
}
/**
* @dev Overload {AccessControl-_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
bool granted = super._grantRole(role, account);
if (granted) {
$._roleMembers[role].add(account);
}
return granted;
}
/**
* @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
bool revoked = super._revokeRole(role, account);
if (revoked) {
$._roleMembers[role].remove(account);
}
return revoked;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.25;
/// @notice Interface for external/custom verification logic
/// @dev Allows plug-in modules to define arbitrary logic for verifying function calls.
/// Used with `VerificationType.CUSTOM_VERIFIER` in the main Verifier contract.
interface ICustomVerifier {
/// @notice Verifies whether the given call is permitted using custom logic
/// @param who Address attempting the call
/// @param where Target contract the call is directed to
/// @param value ETH value sent with the call
/// @param callData Full calldata of the intended call
/// @param verificationData Extra data provided by the caller to support verification logic
/// @return isValid True if the call is considered valid, false otherwise
function verifyCall(
address who,
address where,
uint256 value,
bytes calldata callData,
bytes calldata verificationData
) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/Hashes.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of standard hash functions.
*
* _Available since v5.1._
*/
library Hashes {
/**
* @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
*
* NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
*/
function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return a < b ? efficientKeccak256(a, b) : efficientKeccak256(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function efficientKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}// 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/extensions/IAccessControlEnumerable.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "../IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC-165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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` from `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;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 ERC-165 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;
}
}{
"remappings": [
"forge-std/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@cowswap/contracts/=lib/contracts/src/contracts/",
"contracts/=lib/contracts/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
},
"evmVersion": "cancun",
"viaIR": false
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"string","name":"name_","type":"string"},{"internalType":"uint256","name":"version_","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CheckpointUnorderedInsertion","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[],"name":"Forbidden","type":"error"},{"inputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvalidReport","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"QueuePaused","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"ZeroValue","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"initParams","type":"bytes"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"},{"indexed":false,"internalType":"uint32","name":"timestamp","type":"uint32"}],"name":"RedeemRequestClaimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"RedeemRequested","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"counter","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"demand","type":"uint256"}],"name":"RedeemRequestsHandled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint224","name":"priceD18","type":"uint224"},{"indexed":false,"internalType":"uint32","name":"timestamp","type":"uint32"}],"name":"ReportHandled","type":"event"},{"inputs":[],"name":"asset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"batchAt","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"canBeRemoved","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint32[]","name":"timestamps","type":"uint32[]"}],"name":"claim","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getState","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"batches","type":"uint256"}],"name":"handleBatches","outputs":[{"internalType":"uint256","name":"counter","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint224","name":"priceD18","type":"uint224"},{"internalType":"uint32","name":"timestamp","type":"uint32"}],"name":"handleReport","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"redeem","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"requestsOf","outputs":[{"components":[{"internalType":"uint256","name":"timestamp","type":"uint256"},{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"bool","name":"isClaimable","type":"bool"},{"internalType":"uint256","name":"assets","type":"uint256"}],"internalType":"struct IRedeemQueue.Request[]","name":"requests","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"vault","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]Contract Creation Code
60c060405234801561000f575f80fd5b50604051612a0d380380612a0d83398101604081905261002e916101ef565b818161005e60405180604001604052806005815260200164517565756560d81b81525083836100a360201b60201c565b608052610069610114565b505060408051808201909152600b81526a52656465656d517565756560a81b60208201526100989083836100a3565b60a052506103219050565b5f60ff5f1b1960018585856040516020016100c0939291906102ba565b604051602081830303815290604052805190602001205f1c6100e29190610302565b6040516020016100f491815260200190565b604051602081830303815290604052805190602001201690509392505050565b5f61011d6101b1565b805490915068010000000000000000900460ff161561014f5760405163f92ee8a960e01b815260040160405180910390fd5b80546001600160401b03908116146101ae5780546001600160401b0319166001600160401b0390811782556040519081527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005b92915050565b634e487b7160e01b5f52604160045260245ffd5b5f8060408385031215610200575f80fd5b82516001600160401b0380821115610216575f80fd5b818501915085601f830112610229575f80fd5b81518181111561023b5761023b6101db565b604051601f8201601f19908116603f01168101908382118183101715610263576102636101db565b8160405282815288602084870101111561027b575f80fd5b8260208601602083015e5f602084830101528096505050505050602083015190509250929050565b5f81518060208401855e5f93019283525090919050565b7f6d656c6c6f772e666c657869626c652d7661756c74732e73746f726167652e0081525f6102f46102ee601f8401876102a3565b856102a3565b928352505060200192915050565b818103818111156101d557634e487b7160e01b5f52601160045260245ffd5b60805160a0516126786103955f395f818160b6015281816104c30152818161054401528181610772015281816107eb01528181610df301528181610f9401526113eb01525f81816102840152818161079b01528181610dcf015281816112e501528181611389015261140e01526126785ff3fe60806040526004361061009d575f3560e01c8063c12e43e611610062578063c12e43e6146101b3578063c2f21896146101e0578063d493597214610204578063db006a7514610230578063ed1bccd91461024f578063fbfa77cf1461026e575f80fd5b80631865c57d146100a857806338d52e0f14610113578063439fab911461013f578063b8c5ea8a14610160578063bdec525a1461017f575f80fd5b366100a457005b5f80fd5b3480156100b3575f80fd5b507f0000000000000000000000000000000000000000000000000000000000000000600181015460068201546002830154600390930154919290916040805194855260208501939093529183015260608201526080015b60405180910390f35b34801561011e575f80fd5b50610127610282565b6040516001600160a01b03909116815260200161010a565b34801561014a575f80fd5b5061015e6101593660046121cb565b6102b0565b005b34801561016b575f80fd5b5061015e61017a36600461224a565b6103f9565b34801561018a575f80fd5b5061019e610199366004612288565b6104c1565b6040805192835260208301919091520161010a565b3480156101be575f80fd5b506101d26101cd3660046122b3565b610534565b60405190815260200161010a565b3480156101eb575f80fd5b506101f4610770565b604051901515815260200161010a565b34801561020f575f80fd5b5061022361021e366004612334565b6107db565b60405161010a9190612366565b34801561023b575f80fd5b5061015e61024a366004612288565b610a92565b34801561025a575f80fd5b506101d2610269366004612288565b610f89565b348015610279575f80fd5b506101276112e1565b7f0000000000000000000000000000000000000000000000000000000000000000546001600160a01b031690565b5f6102b9611312565b805490915060ff600160401b820416159067ffffffffffffffff165f811580156102e05750825b90505f8267ffffffffffffffff1660011480156102fc5750303b155b90508115801561030a575080155b156103285760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561035257845460ff60401b1916600160401b1785555b5f80610360888a018a6123df565b509150915061036f828261133c565b7f5e399709a9ff1709f6f6be7268c8e5c3eeaa9da9cd9797e78f07ef287c3717fe89896040516103a09291906124ae565b60405180910390a1505083156103f057845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b6104016112e1565b6001600160a01b0316336001600160a01b03161461043257604051631dd2188d60e31b815260040160405180910390fd5b6001600160e01b038216158061044e5750428163ffffffff1610155b1561046c57604051632d56b1d560e21b815260040160405180910390fd5b61047682826113e9565b604080516001600160e01b038416815263ffffffff831660208201527fe77959fec4c88854df13b1bb591bdba32c0915ce12f89d2fae561946b20dfa4f910160405180910390a15050565b7f000000000000000000000000000000000000000000000000000000000000000060068101545f91829184106104fc57505f93849350915050565b5f816006018581548110610512576105126124dc565b905f5260205f2090600202019050805f01548160010154935093505050915091565b5f61053d6116ac565b335f8181527f0000000000000000000000000000000000000000000000000000000000000000600481016020526040822090929161057d600785016116e3565b509150508063ffffffff165f0361059a575f945050505050610753565b60018401545f5b8781101561073a575f8989838181106105bc576105bc6124dc565b90506020020160208101906105d191906124f0565b90508363ffffffff168163ffffffff1611156105ed5750610732565b5f806106028763ffffffff8086169061174d16565b915091508161061357505050610732565b801561071a575f61062760078b018561176a565b6001600160e01b031690508581106106425750505050610732565b5f8a6006018281548110610658576106586124dc565b905f5260205f20906002020190505f61067984835f015484600101546117af565b9050610685818e61251d565b9c5080825f015f8282546106999190612530565b9250508190555083826001015f8282546106b39190612530565b925050819055508f6001600160a01b03168b6001600160a01b03167fb9ffaf4ddb49764cada66e304da6ebff5a1beee1375b83c26d6e340f2bffd2b7838960405161070e92919091825263ffffffff16602082015260400190565b60405180910390a35050505b61072d8763ffffffff8086169061185f16565b505050505b6001016105a1565b5061074d610746610282565b8a8861186a565b50505050505b61076960015f8051602061262383398151915255565b9392505050565b7f000000000000000000000000000000000000000000000000000000000000000080545f91906107c17f00000000000000000000000000000000000000000000000000000000000000006002015490565b1480156107d5575060068101546001820154145b91505090565b6001600160a01b0383165f9081527f00000000000000000000000000000000000000000000000000000000000000006004810160205260408220606092610821826118c5565b905085811161088657604080515f808252602082019092529061087b565b61086860405180608001604052805f81526020015f81526020015f151581526020015f81525090565b81526020019060019003908161083f5790505b509350505050610769565b6108996108938783612530565b866118cf565b94508467ffffffffffffffff8111156108b4576108b46123cb565b60405190808252806020026020018201604052801561090e57816020015b6108fb60405180608001604052805f81526020015f81526020015f151581526020015f81525090565b8152602001906001900390816108d25790505b5060018401549094505f610924600786016116e3565b5091505061094360405180604001604052805f81526020015f81525090565b5f5b88811015610a84575f8061096361095c8d8561251d565b89906118de565b91509150818a848151811061097a5761097a6124dc565b60200260200101515f018181525050808a848151811061099c5761099c6124dc565b602002602001015160200181815250508463ffffffff168211156109c1575050610a7c565b5f6109cf60078b018461176a565b6001600160e01b031690508960060181815481106109ef576109ef6124dc565b905f5260205f2090600202016040518060400160405290815f82015481526020016001820154815250509450610a2d82865f015187602001516117af565b8b8581518110610a3f57610a3f6124dc565b602002602001015160600181815250508681108b8581518110610a6457610a646124dc565b60209081029190910101519015156040909101525050505b600101610945565b505050505050509392505050565b610a9a6116ac565b805f03610aba57604051637c946ed760e01b815260040160405180910390fd5b335f610ac46112e1565b60405163219e7b5f60e21b81523060048201529091506001600160a01b03821690638679ed7c90602401602060405180830381865afa158015610b09573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b2d9190612543565b15610b4b5760405163191a2e9560e31b815260040160405180910390fd5b5f816001600160a01b0316635c60173d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b88573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bac9190612562565b60405163282d3fdf60e01b81526001600160a01b038581166004830152602482018790529192509082169063282d3fdf906044015f604051808303815f87803b158015610bf7575f80fd5b505af1158015610c09573d5f803e3d5ffd5b505050505f826001600160a01b031663d0fb02036040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c4a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c6e9190612562565b90505f816001600160a01b031663469048406040518163ffffffff1660e01b8152600401602060405180830381865afa158015610cad573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cd19190612562565b9050806001600160a01b0316856001600160a01b031614610dcb576040516307f0c60160e41b8152600481018790525f906001600160a01b03841690637f0c601090602401602060405180830381865afa158015610d31573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d55919061257d565b90508015610dc9576040516340c10f1960e01b81526001600160a01b038381166004830152602482018390528516906340c10f19906044015f604051808303815f87803b158015610da4575f80fd5b505af1158015610db6573d5f803e3d5ffd5b505050508087610dc69190612530565b96505b505b60027f00000000000000000000000000000000000000000000000000000000000000000180547f00000000000000000000000000000000000000000000000000000000000000009142915f610e1f836116e3565b509150508363ffffffff168163ffffffff161015610e8257610e428385846118ec565b5050600585015f610e54600185612530565b81526020019081526020015f20548b610e6d919061251d565b5f838152600587016020526040902055610eb5565b8a600586015f610e9185612594565b94508481526020019081526020015f205f828254610eaf919061251d565b90915550505b6001600160a01b038a165f908152600486016020526040812090610ee28263ffffffff8089169061174d16565b9150610f02905063ffffffff8716610efa8f8461251d565b849190611906565b508c876003015f828254610f16919061251d565b9091555050604080518e815263ffffffff881660208201526001600160a01b038e16917f58fe322fc5911ed072ec92f570e517b9793e350eb1ff7be0019fd9f3fade87bc910160405180910390a2505050505050505050505050610f8660015f8051602061262383398151915255565b50565b5f610f926116ac565b7f0000000000000000000000000000000000000000000000000000000000000000600181015460068201548082101580610fca575084155b15610fda575f93505050506112c6565b610fed85610fe88484612530565b6118cf565b94505f610ff86112e1565b90505f816001600160a01b0316635d66b00a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611037573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061105b919061257d565b90505f8061107a60405180604001604052805f81526020015f81525090565b5f5b8a8110156111185760068901611092828a61251d565b815481106110a2576110a26124dc565b905f5260205f2090600202016040518060400160405290815f8201548152602001600182015481525050915084825f0151856110de919061251d565b116111185781516110ef908561251d565b9350816020015183611101919061251d565b92508961110d816125a9565b9a505060010161107c565b5088156112bd57821561126b5760405163d27d250360e01b8152600481018490526001600160a01b0386169063d27d2503906024015f604051808303815f87803b158015611164575f80fd5b505af1158015611176573d5f803e3d5ffd5b50505050846001600160a01b031663478426636040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111b6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111da9190612562565b6001600160a01b03166382dcf0746111f0610282565b6111f9866125c1565b6040516001600160e01b031960e085901b1681526001600160a01b03909216600483015260248201526044015f604051808303815f87803b15801561123c575f80fd5b505af115801561124e573d5f803e3d5ffd5b5050505082886002015f8282546112659190612530565b90915550505b88886001015f82825461127e919061251d565b9091555050604080518a8152602081018590527f0e6455e20f0311b7e812c0a7d83f32566f1004a28f3a5611247da5b55ee827b2910160405180910390a15b50505050505050505b6112dc60015f8051602061262383398151915255565b919050565b60017f000000000000000000000000000000000000000000000000000000000000000001546001600160a01b031690565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005b92915050565b61134461191a565b61134c611941565b6001600160a01b038216158061136957506001600160a01b038116155b1561138757604051637c946ed760e01b815260040160405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000080546001600160a01b038481166001600160a01b0319928316178355600183018054918516919092161790556113e260028201425f6118ec565b5050505050565b7f000000000000000000000000000000000000000000000000000000000000000060027f0000000000000000000000000000000000000000000000000000000000000000015f80611439836116e3565b92509250505f8563ffffffff168363ffffffff161161146257506001600160e01b0381166114aa565b61146c8487611951565b6001600160e01b031690508015801561149c575061148a845f6119f2565b5f015163ffffffff168663ffffffff16105b156114aa5750505050505050565b8454808210156114be575050505050505050565b5f81156114e857600587015f6114d5600185612530565b81526020019081526020015f20546114ea565b5f5b5f8481526005890160205260409020546115049190612530565b905061151183600161251d565b87555f81900361152657505050505050505050565b5f611532886007015490565b905081886003015f8282546115479190612530565b909155505f90506115566112e1565b6001600160a01b0316635c60173d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611591573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115b59190612562565b604051632770a7eb60e21b81526001600160a01b0382166004820181905260248201869052919250639dc29fac906044015f604051808303815f87803b1580156115fd575f80fd5b505af115801561160f573d5f803e3d5ffd5b506116229250505060078a018b846118ec565b50505f61164184670de0b6b3a76400008e6001600160e01b03166117af565b60408051808201909152818152602080820187815260068e018054600181810183555f9283529382209451600291820290950194855591519390920192909255908c018054929350839290919061169990849061251d565b9091555050505050505050505050505050565b5f805160206126238339815191528054600119016116dd57604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b80545f9081908190808203611701575f805f93509350935050611746565b5f61171e86611711600185612530565b5f91825260209091200190565b546001955063ffffffff81169450600160201b90046001600160e01b03169250611746915050565b9193909250565b5f80808061175b8686611a5d565b909450925050505b9250929050565b81545f908161177b85858385611a95565b90508181146117a4575f85815260209020810154600160201b90046001600160e01b03166117a6565b5f5b95945050505050565b5f805f6117bc8686611af0565b91509150815f036117e0578381816117d6576117d66125db565b0492505050610769565b8184116117f7576117f76003851502601118611b0c565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010185841190960395909502919093039390930492909217029150509392505050565b5f6107698383611b1d565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeed196001600160a01b0384160161189e576118998282611b39565b505050565b6118996001600160a01b0384168383611bd0565b60015f8051602061262383398151915255565b5f61133682611c22565b5f828218828410028218610769565b5f80808061175b8686611c2c565b5f806118f9858585611c55565b915091505b935093915050565b5f611912848484611d99565b949350505050565b611922611db5565b61193f57604051631afcd79f60e31b815260040160405180910390fd5b565b61194961191a565b61193f611dce565b81545f90818160058111156119ab575f61196a84611dd6565b6119749085612530565b5f8881526020902090915081015463ffffffff908116908716101561199b578091506119a9565b6119a681600161251d565b92505b505b5f6119b887878585611f28565b905080156119e5576119cf87611711600184612530565b54600160201b90046001600160e01b03166119e7565b5f5b979650505050505050565b604080518082019091525f8082526020820152825f018263ffffffff1681548110611a1f57611a1f6124dc565b5f9182526020918290206040805180820190915291015463ffffffff81168252600160201b90046001600160e01b0316918101919091529392505050565b5f818152600283016020526040812054819080611a8a57611a7e8585611f7b565b92505f91506117639050565b600192509050611763565b5f5b81831015611ae8575f611aaa8484611f86565b5f8781526020902090915063ffffffff86169082015463ffffffff161015611ade57611ad781600161251d565b9350611ae2565b8092505b50611a97565b509392505050565b5f805f1983850993909202808410938190039390930393915050565b634e487b715f52806020526024601cfd5b5f81815260028301602052604081208190556107698383611fa0565b80471015611b685760405163cf47918160e01b8152476004820152602481018290526044015b60405180910390fd5b5f80836001600160a01b0316836040515f6040518083038185875af1925050503d805f8114611bb2576040519150601f19603f3d011682016040523d82523d5f602084013e611bb7565b606091505b509150915081611bca57611bca81611fab565b50505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052611899908490611fd4565b5f61133682612040565b5f8080611c398585612049565b5f81815260029690960160205260409095205494959350505050565b82545f9081908015611d41575f611c7187611711600185612530565b805490915063ffffffff80821691600160201b90046001600160e01b0316908816821115611cb257604051632520601d60e01b815260040160405180910390fd5b8763ffffffff168263ffffffff1603611ce557825463ffffffff16600160201b6001600160e01b03891602178355611d33565b6040805180820190915263ffffffff808a1682526001600160e01b03808a1660208085019182528d54600181018f555f8f81529190912094519151909216600160201b029216919091179101555b94508593506118fe92505050565b50506040805180820190915263ffffffff80851682526001600160e01b0380851660208085019182528854600181018a555f8a815291822095519251909316600160201b0291909316179201919091559050816118fe565b5f82815260028401602052604081208290556119128484612054565b5f611dbe611312565b54600160401b900460ff16919050565b6118b261191a565b5f60018211611de3575090565b816001600160801b8210611dfc5760809190911c9060401b5b600160401b8210611e125760409190911c9060201b5b600160201b8210611e285760209190911c9060101b5b620100008210611e3d5760109190911c9060081b5b6101008210611e515760089190911c9060041b5b60108210611e645760049190911c9060021b5b60048210611e705760011b5b600302600190811c90818581611e8857611e886125db565b048201901c90506001818581611ea057611ea06125db565b048201901c90506001818581611eb857611eb86125db565b048201901c90506001818581611ed057611ed06125db565b048201901c90506001818581611ee857611ee86125db565b048201901c90506001818581611f0057611f006125db565b048201901c9050611f1f818581611f1957611f196125db565b04821190565b90039392505050565b5f5b81831015611ae8575f611f3d8484611f86565b5f8781526020902090915063ffffffff86169082015463ffffffff161115611f6757809250611f75565b611f7281600161251d565b93505b50611f2a565b5f610769838361205f565b5f611f9460028484186125ef565b6107699084841661251d565b5f6107698383612076565b805115611fbb5780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b5f8060205f8451602086015f885af180611ff3576040513d5f823e3d81fd5b50505f513d9150811561200a578060011415612017565b6001600160a01b0384163b155b15611bca57604051635274afe760e01b81526001600160a01b0385166004820152602401611b5f565b5f611336825490565b5f6107698383612159565b5f610769838361217f565b5f8181526001830160205260408120541515610769565b5f8181526001830160205260408120548015612150575f612098600183612530565b85549091505f906120ab90600190612530565b905080821461210a575f865f0182815481106120c9576120c96124dc565b905f5260205f200154905080875f0184815481106120e9576120e96124dc565b5f918252602080832090910192909255918252600188019052604090208390555b855486908061211b5761211b61260e565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050611336565b5f915050611336565b5f825f01828154811061216e5761216e6124dc565b905f5260205f200154905092915050565b5f8181526001830160205260408120546121c457508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155611336565b505f611336565b5f80602083850312156121dc575f80fd5b823567ffffffffffffffff808211156121f3575f80fd5b818501915085601f830112612206575f80fd5b813581811115612214575f80fd5b866020828501011115612225575f80fd5b60209290920196919550909350505050565b803563ffffffff811681146112dc575f80fd5b5f806040838503121561225b575f80fd5b82356001600160e01b0381168114612271575f80fd5b915061227f60208401612237565b90509250929050565b5f60208284031215612298575f80fd5b5035919050565b6001600160a01b0381168114610f86575f80fd5b5f805f604084860312156122c5575f80fd5b83356122d08161229f565b9250602084013567ffffffffffffffff808211156122ec575f80fd5b818601915086601f8301126122ff575f80fd5b81358181111561230d575f80fd5b8760208260051b8501011115612321575f80fd5b6020830194508093505050509250925092565b5f805f60608486031215612346575f80fd5b83356123518161229f565b95602085013595506040909401359392505050565b602080825282518282018190525f919060409081850190868401855b828110156123be578151805185528681015187860152858101511515868601526060908101519085015260809093019290850190600101612382565b5091979650505050505050565b634e487b7160e01b5f52604160045260245ffd5b5f805f606084860312156123f1575f80fd5b83356123fc8161229f565b9250602084013561240c8161229f565b9150604084013567ffffffffffffffff80821115612428575f80fd5b818601915086601f83011261243b575f80fd5b81358181111561244d5761244d6123cb565b604051601f8201601f19908116603f01168101908382118183101715612475576124756123cb565b8160405282815289602084870101111561248d575f80fd5b826020860160208301375f6020848301015280955050505050509250925092565b60208152816020820152818360408301375f818301604090810191909152601f909201601f19160101919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215612500575f80fd5b61076982612237565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561133657611336612509565b8181038181111561133657611336612509565b5f60208284031215612553575f80fd5b81518015158114610769575f80fd5b5f60208284031215612572575f80fd5b81516107698161229f565b5f6020828403121561258d575f80fd5b5051919050565b5f816125a2576125a2612509565b505f190190565b5f600182016125ba576125ba612509565b5060010190565b5f600160ff1b82016125d5576125d5612509565b505f0390565b634e487b7160e01b5f52601260045260245ffd5b5f8261260957634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52603160045260245ffdfe9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00a26469706673582212203bcf767418f9bf5f46216d11963df1641c0fc8ab7a0a049324415ba392f6a9f964736f6c634300081900330000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000064d656c6c6f770000000000000000000000000000000000000000000000000000
Deployed Bytecode
0x60806040526004361061009d575f3560e01c8063c12e43e611610062578063c12e43e6146101b3578063c2f21896146101e0578063d493597214610204578063db006a7514610230578063ed1bccd91461024f578063fbfa77cf1461026e575f80fd5b80631865c57d146100a857806338d52e0f14610113578063439fab911461013f578063b8c5ea8a14610160578063bdec525a1461017f575f80fd5b366100a457005b5f80fd5b3480156100b3575f80fd5b507f7a6b8449721bbce19f1eca0ca371853fa0ae5717c37641a4ed688bd87f4ab000600181015460068201546002830154600390930154919290916040805194855260208501939093529183015260608201526080015b60405180910390f35b34801561011e575f80fd5b50610127610282565b6040516001600160a01b03909116815260200161010a565b34801561014a575f80fd5b5061015e6101593660046121cb565b6102b0565b005b34801561016b575f80fd5b5061015e61017a36600461224a565b6103f9565b34801561018a575f80fd5b5061019e610199366004612288565b6104c1565b6040805192835260208301919091520161010a565b3480156101be575f80fd5b506101d26101cd3660046122b3565b610534565b60405190815260200161010a565b3480156101eb575f80fd5b506101f4610770565b604051901515815260200161010a565b34801561020f575f80fd5b5061022361021e366004612334565b6107db565b60405161010a9190612366565b34801561023b575f80fd5b5061015e61024a366004612288565b610a92565b34801561025a575f80fd5b506101d2610269366004612288565b610f89565b348015610279575f80fd5b506101276112e1565b7f52a7b6d93a2c9ad395cecfe3e26abf6804c5267e2e8178f357f8cea67a0be800546001600160a01b031690565b5f6102b9611312565b805490915060ff600160401b820416159067ffffffffffffffff165f811580156102e05750825b90505f8267ffffffffffffffff1660011480156102fc5750303b155b90508115801561030a575080155b156103285760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561035257845460ff60401b1916600160401b1785555b5f80610360888a018a6123df565b509150915061036f828261133c565b7f5e399709a9ff1709f6f6be7268c8e5c3eeaa9da9cd9797e78f07ef287c3717fe89896040516103a09291906124ae565b60405180910390a1505083156103f057845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b6104016112e1565b6001600160a01b0316336001600160a01b03161461043257604051631dd2188d60e31b815260040160405180910390fd5b6001600160e01b038216158061044e5750428163ffffffff1610155b1561046c57604051632d56b1d560e21b815260040160405180910390fd5b61047682826113e9565b604080516001600160e01b038416815263ffffffff831660208201527fe77959fec4c88854df13b1bb591bdba32c0915ce12f89d2fae561946b20dfa4f910160405180910390a15050565b7f7a6b8449721bbce19f1eca0ca371853fa0ae5717c37641a4ed688bd87f4ab00060068101545f91829184106104fc57505f93849350915050565b5f816006018581548110610512576105126124dc565b905f5260205f2090600202019050805f01548160010154935093505050915091565b5f61053d6116ac565b335f8181527f7a6b8449721bbce19f1eca0ca371853fa0ae5717c37641a4ed688bd87f4ab000600481016020526040822090929161057d600785016116e3565b509150508063ffffffff165f0361059a575f945050505050610753565b60018401545f5b8781101561073a575f8989838181106105bc576105bc6124dc565b90506020020160208101906105d191906124f0565b90508363ffffffff168163ffffffff1611156105ed5750610732565b5f806106028763ffffffff8086169061174d16565b915091508161061357505050610732565b801561071a575f61062760078b018561176a565b6001600160e01b031690508581106106425750505050610732565b5f8a6006018281548110610658576106586124dc565b905f5260205f20906002020190505f61067984835f015484600101546117af565b9050610685818e61251d565b9c5080825f015f8282546106999190612530565b9250508190555083826001015f8282546106b39190612530565b925050819055508f6001600160a01b03168b6001600160a01b03167fb9ffaf4ddb49764cada66e304da6ebff5a1beee1375b83c26d6e340f2bffd2b7838960405161070e92919091825263ffffffff16602082015260400190565b60405180910390a35050505b61072d8763ffffffff8086169061185f16565b505050505b6001016105a1565b5061074d610746610282565b8a8861186a565b50505050505b61076960015f8051602061262383398151915255565b9392505050565b7f7a6b8449721bbce19f1eca0ca371853fa0ae5717c37641a4ed688bd87f4ab00080545f91906107c17f52a7b6d93a2c9ad395cecfe3e26abf6804c5267e2e8178f357f8cea67a0be8006002015490565b1480156107d5575060068101546001820154145b91505090565b6001600160a01b0383165f9081527f7a6b8449721bbce19f1eca0ca371853fa0ae5717c37641a4ed688bd87f4ab0006004810160205260408220606092610821826118c5565b905085811161088657604080515f808252602082019092529061087b565b61086860405180608001604052805f81526020015f81526020015f151581526020015f81525090565b81526020019060019003908161083f5790505b509350505050610769565b6108996108938783612530565b866118cf565b94508467ffffffffffffffff8111156108b4576108b46123cb565b60405190808252806020026020018201604052801561090e57816020015b6108fb60405180608001604052805f81526020015f81526020015f151581526020015f81525090565b8152602001906001900390816108d25790505b5060018401549094505f610924600786016116e3565b5091505061094360405180604001604052805f81526020015f81525090565b5f5b88811015610a84575f8061096361095c8d8561251d565b89906118de565b91509150818a848151811061097a5761097a6124dc565b60200260200101515f018181525050808a848151811061099c5761099c6124dc565b602002602001015160200181815250508463ffffffff168211156109c1575050610a7c565b5f6109cf60078b018461176a565b6001600160e01b031690508960060181815481106109ef576109ef6124dc565b905f5260205f2090600202016040518060400160405290815f82015481526020016001820154815250509450610a2d82865f015187602001516117af565b8b8581518110610a3f57610a3f6124dc565b602002602001015160600181815250508681108b8581518110610a6457610a646124dc565b60209081029190910101519015156040909101525050505b600101610945565b505050505050509392505050565b610a9a6116ac565b805f03610aba57604051637c946ed760e01b815260040160405180910390fd5b335f610ac46112e1565b60405163219e7b5f60e21b81523060048201529091506001600160a01b03821690638679ed7c90602401602060405180830381865afa158015610b09573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610b2d9190612543565b15610b4b5760405163191a2e9560e31b815260040160405180910390fd5b5f816001600160a01b0316635c60173d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b88573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bac9190612562565b60405163282d3fdf60e01b81526001600160a01b038581166004830152602482018790529192509082169063282d3fdf906044015f604051808303815f87803b158015610bf7575f80fd5b505af1158015610c09573d5f803e3d5ffd5b505050505f826001600160a01b031663d0fb02036040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c4a573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c6e9190612562565b90505f816001600160a01b031663469048406040518163ffffffff1660e01b8152600401602060405180830381865afa158015610cad573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cd19190612562565b9050806001600160a01b0316856001600160a01b031614610dcb576040516307f0c60160e41b8152600481018790525f906001600160a01b03841690637f0c601090602401602060405180830381865afa158015610d31573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d55919061257d565b90508015610dc9576040516340c10f1960e01b81526001600160a01b038381166004830152602482018390528516906340c10f19906044015f604051808303815f87803b158015610da4575f80fd5b505af1158015610db6573d5f803e3d5ffd5b505050508087610dc69190612530565b96505b505b60027f52a7b6d93a2c9ad395cecfe3e26abf6804c5267e2e8178f357f8cea67a0be8000180547f7a6b8449721bbce19f1eca0ca371853fa0ae5717c37641a4ed688bd87f4ab0009142915f610e1f836116e3565b509150508363ffffffff168163ffffffff161015610e8257610e428385846118ec565b5050600585015f610e54600185612530565b81526020019081526020015f20548b610e6d919061251d565b5f838152600587016020526040902055610eb5565b8a600586015f610e9185612594565b94508481526020019081526020015f205f828254610eaf919061251d565b90915550505b6001600160a01b038a165f908152600486016020526040812090610ee28263ffffffff8089169061174d16565b9150610f02905063ffffffff8716610efa8f8461251d565b849190611906565b508c876003015f828254610f16919061251d565b9091555050604080518e815263ffffffff881660208201526001600160a01b038e16917f58fe322fc5911ed072ec92f570e517b9793e350eb1ff7be0019fd9f3fade87bc910160405180910390a2505050505050505050505050610f8660015f8051602061262383398151915255565b50565b5f610f926116ac565b7f7a6b8449721bbce19f1eca0ca371853fa0ae5717c37641a4ed688bd87f4ab000600181015460068201548082101580610fca575084155b15610fda575f93505050506112c6565b610fed85610fe88484612530565b6118cf565b94505f610ff86112e1565b90505f816001600160a01b0316635d66b00a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611037573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061105b919061257d565b90505f8061107a60405180604001604052805f81526020015f81525090565b5f5b8a8110156111185760068901611092828a61251d565b815481106110a2576110a26124dc565b905f5260205f2090600202016040518060400160405290815f8201548152602001600182015481525050915084825f0151856110de919061251d565b116111185781516110ef908561251d565b9350816020015183611101919061251d565b92508961110d816125a9565b9a505060010161107c565b5088156112bd57821561126b5760405163d27d250360e01b8152600481018490526001600160a01b0386169063d27d2503906024015f604051808303815f87803b158015611164575f80fd5b505af1158015611176573d5f803e3d5ffd5b50505050846001600160a01b031663478426636040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111b6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111da9190612562565b6001600160a01b03166382dcf0746111f0610282565b6111f9866125c1565b6040516001600160e01b031960e085901b1681526001600160a01b03909216600483015260248201526044015f604051808303815f87803b15801561123c575f80fd5b505af115801561124e573d5f803e3d5ffd5b5050505082886002015f8282546112659190612530565b90915550505b88886001015f82825461127e919061251d565b9091555050604080518a8152602081018590527f0e6455e20f0311b7e812c0a7d83f32566f1004a28f3a5611247da5b55ee827b2910160405180910390a15b50505050505050505b6112dc60015f8051602061262383398151915255565b919050565b60017f52a7b6d93a2c9ad395cecfe3e26abf6804c5267e2e8178f357f8cea67a0be80001546001600160a01b031690565b5f807ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a005b92915050565b61134461191a565b61134c611941565b6001600160a01b038216158061136957506001600160a01b038116155b1561138757604051637c946ed760e01b815260040160405180910390fd5b7f52a7b6d93a2c9ad395cecfe3e26abf6804c5267e2e8178f357f8cea67a0be80080546001600160a01b038481166001600160a01b0319928316178355600183018054918516919092161790556113e260028201425f6118ec565b5050505050565b7f7a6b8449721bbce19f1eca0ca371853fa0ae5717c37641a4ed688bd87f4ab00060027f52a7b6d93a2c9ad395cecfe3e26abf6804c5267e2e8178f357f8cea67a0be800015f80611439836116e3565b92509250505f8563ffffffff168363ffffffff161161146257506001600160e01b0381166114aa565b61146c8487611951565b6001600160e01b031690508015801561149c575061148a845f6119f2565b5f015163ffffffff168663ffffffff16105b156114aa5750505050505050565b8454808210156114be575050505050505050565b5f81156114e857600587015f6114d5600185612530565b81526020019081526020015f20546114ea565b5f5b5f8481526005890160205260409020546115049190612530565b905061151183600161251d565b87555f81900361152657505050505050505050565b5f611532886007015490565b905081886003015f8282546115479190612530565b909155505f90506115566112e1565b6001600160a01b0316635c60173d6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611591573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115b59190612562565b604051632770a7eb60e21b81526001600160a01b0382166004820181905260248201869052919250639dc29fac906044015f604051808303815f87803b1580156115fd575f80fd5b505af115801561160f573d5f803e3d5ffd5b506116229250505060078a018b846118ec565b50505f61164184670de0b6b3a76400008e6001600160e01b03166117af565b60408051808201909152818152602080820187815260068e018054600181810183555f9283529382209451600291820290950194855591519390920192909255908c018054929350839290919061169990849061251d565b9091555050505050505050505050505050565b5f805160206126238339815191528054600119016116dd57604051633ee5aeb560e01b815260040160405180910390fd5b60029055565b80545f9081908190808203611701575f805f93509350935050611746565b5f61171e86611711600185612530565b5f91825260209091200190565b546001955063ffffffff81169450600160201b90046001600160e01b03169250611746915050565b9193909250565b5f80808061175b8686611a5d565b909450925050505b9250929050565b81545f908161177b85858385611a95565b90508181146117a4575f85815260209020810154600160201b90046001600160e01b03166117a6565b5f5b95945050505050565b5f805f6117bc8686611af0565b91509150815f036117e0578381816117d6576117d66125db565b0492505050610769565b8184116117f7576117f76003851502601118611b0c565b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010185841190960395909502919093039390930492909217029150509392505050565b5f6107698383611b1d565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeed196001600160a01b0384160161189e576118998282611b39565b505050565b6118996001600160a01b0384168383611bd0565b60015f8051602061262383398151915255565b5f61133682611c22565b5f828218828410028218610769565b5f80808061175b8686611c2c565b5f806118f9858585611c55565b915091505b935093915050565b5f611912848484611d99565b949350505050565b611922611db5565b61193f57604051631afcd79f60e31b815260040160405180910390fd5b565b61194961191a565b61193f611dce565b81545f90818160058111156119ab575f61196a84611dd6565b6119749085612530565b5f8881526020902090915081015463ffffffff908116908716101561199b578091506119a9565b6119a681600161251d565b92505b505b5f6119b887878585611f28565b905080156119e5576119cf87611711600184612530565b54600160201b90046001600160e01b03166119e7565b5f5b979650505050505050565b604080518082019091525f8082526020820152825f018263ffffffff1681548110611a1f57611a1f6124dc565b5f9182526020918290206040805180820190915291015463ffffffff81168252600160201b90046001600160e01b0316918101919091529392505050565b5f818152600283016020526040812054819080611a8a57611a7e8585611f7b565b92505f91506117639050565b600192509050611763565b5f5b81831015611ae8575f611aaa8484611f86565b5f8781526020902090915063ffffffff86169082015463ffffffff161015611ade57611ad781600161251d565b9350611ae2565b8092505b50611a97565b509392505050565b5f805f1983850993909202808410938190039390930393915050565b634e487b715f52806020526024601cfd5b5f81815260028301602052604081208190556107698383611fa0565b80471015611b685760405163cf47918160e01b8152476004820152602481018290526044015b60405180910390fd5b5f80836001600160a01b0316836040515f6040518083038185875af1925050503d805f8114611bb2576040519150601f19603f3d011682016040523d82523d5f602084013e611bb7565b606091505b509150915081611bca57611bca81611fab565b50505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052611899908490611fd4565b5f61133682612040565b5f8080611c398585612049565b5f81815260029690960160205260409095205494959350505050565b82545f9081908015611d41575f611c7187611711600185612530565b805490915063ffffffff80821691600160201b90046001600160e01b0316908816821115611cb257604051632520601d60e01b815260040160405180910390fd5b8763ffffffff168263ffffffff1603611ce557825463ffffffff16600160201b6001600160e01b03891602178355611d33565b6040805180820190915263ffffffff808a1682526001600160e01b03808a1660208085019182528d54600181018f555f8f81529190912094519151909216600160201b029216919091179101555b94508593506118fe92505050565b50506040805180820190915263ffffffff80851682526001600160e01b0380851660208085019182528854600181018a555f8a815291822095519251909316600160201b0291909316179201919091559050816118fe565b5f82815260028401602052604081208290556119128484612054565b5f611dbe611312565b54600160401b900460ff16919050565b6118b261191a565b5f60018211611de3575090565b816001600160801b8210611dfc5760809190911c9060401b5b600160401b8210611e125760409190911c9060201b5b600160201b8210611e285760209190911c9060101b5b620100008210611e3d5760109190911c9060081b5b6101008210611e515760089190911c9060041b5b60108210611e645760049190911c9060021b5b60048210611e705760011b5b600302600190811c90818581611e8857611e886125db565b048201901c90506001818581611ea057611ea06125db565b048201901c90506001818581611eb857611eb86125db565b048201901c90506001818581611ed057611ed06125db565b048201901c90506001818581611ee857611ee86125db565b048201901c90506001818581611f0057611f006125db565b048201901c9050611f1f818581611f1957611f196125db565b04821190565b90039392505050565b5f5b81831015611ae8575f611f3d8484611f86565b5f8781526020902090915063ffffffff86169082015463ffffffff161115611f6757809250611f75565b611f7281600161251d565b93505b50611f2a565b5f610769838361205f565b5f611f9460028484186125ef565b6107699084841661251d565b5f6107698383612076565b805115611fbb5780518082602001fd5b60405163d6bda27560e01b815260040160405180910390fd5b5f8060205f8451602086015f885af180611ff3576040513d5f823e3d81fd5b50505f513d9150811561200a578060011415612017565b6001600160a01b0384163b155b15611bca57604051635274afe760e01b81526001600160a01b0385166004820152602401611b5f565b5f611336825490565b5f6107698383612159565b5f610769838361217f565b5f8181526001830160205260408120541515610769565b5f8181526001830160205260408120548015612150575f612098600183612530565b85549091505f906120ab90600190612530565b905080821461210a575f865f0182815481106120c9576120c96124dc565b905f5260205f200154905080875f0184815481106120e9576120e96124dc565b5f918252602080832090910192909255918252600188019052604090208390555b855486908061211b5761211b61260e565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050611336565b5f915050611336565b5f825f01828154811061216e5761216e6124dc565b905f5260205f200154905092915050565b5f8181526001830160205260408120546121c457508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155611336565b505f611336565b5f80602083850312156121dc575f80fd5b823567ffffffffffffffff808211156121f3575f80fd5b818501915085601f830112612206575f80fd5b813581811115612214575f80fd5b866020828501011115612225575f80fd5b60209290920196919550909350505050565b803563ffffffff811681146112dc575f80fd5b5f806040838503121561225b575f80fd5b82356001600160e01b0381168114612271575f80fd5b915061227f60208401612237565b90509250929050565b5f60208284031215612298575f80fd5b5035919050565b6001600160a01b0381168114610f86575f80fd5b5f805f604084860312156122c5575f80fd5b83356122d08161229f565b9250602084013567ffffffffffffffff808211156122ec575f80fd5b818601915086601f8301126122ff575f80fd5b81358181111561230d575f80fd5b8760208260051b8501011115612321575f80fd5b6020830194508093505050509250925092565b5f805f60608486031215612346575f80fd5b83356123518161229f565b95602085013595506040909401359392505050565b602080825282518282018190525f919060409081850190868401855b828110156123be578151805185528681015187860152858101511515868601526060908101519085015260809093019290850190600101612382565b5091979650505050505050565b634e487b7160e01b5f52604160045260245ffd5b5f805f606084860312156123f1575f80fd5b83356123fc8161229f565b9250602084013561240c8161229f565b9150604084013567ffffffffffffffff80821115612428575f80fd5b818601915086601f83011261243b575f80fd5b81358181111561244d5761244d6123cb565b604051601f8201601f19908116603f01168101908382118183101715612475576124756123cb565b8160405282815289602084870101111561248d575f80fd5b826020860160208301375f6020848301015280955050505050509250925092565b60208152816020820152818360408301375f818301604090810191909152601f909201601f19160101919050565b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215612500575f80fd5b61076982612237565b634e487b7160e01b5f52601160045260245ffd5b8082018082111561133657611336612509565b8181038181111561133657611336612509565b5f60208284031215612553575f80fd5b81518015158114610769575f80fd5b5f60208284031215612572575f80fd5b81516107698161229f565b5f6020828403121561258d575f80fd5b5051919050565b5f816125a2576125a2612509565b505f190190565b5f600182016125ba576125ba612509565b5060010190565b5f600160ff1b82016125d5576125d5612509565b505f0390565b634e487b7160e01b5f52601260045260245ffd5b5f8261260957634e487b7160e01b5f52601260045260245ffd5b500490565b634e487b7160e01b5f52603160045260245ffdfe9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00a26469706673582212203bcf767418f9bf5f46216d11963df1641c0fc8ab7a0a049324415ba392f6a9f964736f6c63430008190033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000064d656c6c6f770000000000000000000000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : name_ (string): Mellow
Arg [1] : version_ (uint256): 1
-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 0000000000000000000000000000000000000000000000000000000000000040
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000006
Arg [3] : 4d656c6c6f770000000000000000000000000000000000000000000000000000
Deployed Bytecode Sourcemap
178:9173:63:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;620:241;;;;;;;;;;-1:-1:-1;9263:23:63;777:15;;;;794:9;;;:16;812:19;;;;833:20;;;;;777:15;;794:16;;620:241;;;245:25:64;;;301:2;286:18;;279:34;;;;329:18;;;322:34;387:2;372:18;;365:34;232:3;217:19;620:241:63;;;;;;;;727:92:62;;;;;;;;;;;;;:::i;:::-;;;-1:-1:-1;;;;;574:32:64;;;556:51;;544:2;529:18;727:92:62;410:203:64;2858:240:63;;;;;;;;;;-1:-1:-1;2858:240:63;;;;;:::i;:::-;;:::i;:::-;;878:355:62;;;;;;;;;;-1:-1:-1;878:355:62;;;;;:::i;:::-;;:::i;900:325:63:-;;;;;;;;;;-1:-1:-1;900:325:63;;;;;:::i;:::-;;:::i;:::-;;;;2104:25:64;;;2160:2;2145:18;;2138:34;;;;2077:18;900:325:63;1930:248:64;4844:1513:63;;;;;;;;;;-1:-1:-1;4844:1513:63;;;;;:::i;:::-;;:::i;:::-;;;3219:25:64;;;3207:2;3192:18;4844:1513:63;3073:177:64;2536:220:63;;;;;;;;;;;;;:::i;:::-;;;3420:14:64;;3413:22;3395:41;;3383:2;3368:18;2536:220:63;3255:187:64;1264:1239:63;;;;;;;;;;-1:-1:-1;1264:1239:63;;;;;:::i;:::-;;:::i;:::-;;;;;;;:::i;3137:1668::-;;;;;;;;;;-1:-1:-1;3137:1668:63;;;;;:::i;:::-;;:::i;6396:1254::-;;;;;;;;;;-1:-1:-1;6396:1254:63;;;;;:::i;:::-;;:::i;602:92:62:-;;;;;;;;;;;;;:::i;727:::-;1890:17;791:21;-1:-1:-1;;;;;791:21:62;;727:92::o;2858:240:63:-;4158:30:3;4191:26;:24;:26::i;:::-;4302:15;;4158:59;;-1:-1:-1;4302:15:3;-1:-1:-1;;;4302:15:3;;;4301:16;;4348:14;;4279:19;4724:16;;:34;;;;;4744:14;4724:34;4704:54;;4768:17;4788:11;:16;;4803:1;4788:16;:50;;;;-1:-1:-1;4816:4:3;4808:25;:30;4788:50;4768:70;;4854:12;4853:13;:30;;;;;4871:12;4870:13;4853:30;4849:91;;;4906:23;;-1:-1:-1;;;4906:23:3;;;;;;;;;;;4849:91;4949:18;;-1:-1:-1;;4949:18:3;4966:1;4949:18;;;4977:67;;;;5011:22;;-1:-1:-1;;;;5011:22:3;-1:-1:-1;;;5011:22:3;;;4977:67;2931:14:63::1;::::0;2972:43:::1;::::0;;::::1;2983:4:::0;2972:43:::1;:::i;:::-;2930:85;;;;;3025:34;3038:6;3046:12;3025;:34::i;:::-;3074:17;3086:4;;3074:17;;;;;;;:::i;:::-;;;;;;;;2920:178;;5068:14:3::0;5064:101;;;5098:23;;-1:-1:-1;;;;5098:23:3;;;5140:14;;-1:-1:-1;6677:50:64;;5140:14:3;;6665:2:64;6650:18;5140:14:3;;;;;;;5064:101;4092:1079;;;;;2858:240:63;;:::o;878:355:62:-;975:7;:5;:7::i;:::-;-1:-1:-1;;;;;959:23:62;966:10:4;-1:-1:-1;;;;;959:23:62;;955:72;;1005:11;;-1:-1:-1;;;1005:11:62;;;;;;;;;;;955:72;-1:-1:-1;;;;;1040:13:62;;;;:45;;;1070:15;1057:9;:28;;;;1040:45;1036:98;;;1108:15;;-1:-1:-1;;;1108:15:62;;;;;;;;;;;1036:98;1143:34;1157:8;1167:9;1143:13;:34::i;:::-;1192;;;-1:-1:-1;;;;;6928:32:64;;6910:51;;7009:10;6997:23;;6992:2;6977:18;;6970:51;1192:34:62;;6883:18:64;1192:34:62;;;;;;;878:355;;:::o;900:325:63:-;9263:23;1070:9;;;:16;953:14;;;;1061:25;;1057:69;;-1:-1:-1;1110:1:63;;;;-1:-1:-1;900:325:63;-1:-1:-1;;900:325:63:o;1057:69::-;1135:19;1157:1;:9;;1167:5;1157:16;;;;;;;;:::i;:::-;;;;;;;;;;;1135:38;;1191:5;:12;;;1205:5;:12;;;1183:35;;;;;;900:325;;;:::o;4844:1513::-;4938:14;3395:21:5;:19;:21::i;:::-;966:10:4;4964:28:63::1;5119:21:::0;;;9263:23;5119:12:::1;::::0;::::1;:21;::::0;;;;9263:23;;966:10:4;5186:27:63::1;:8;::::0;::::1;:25;:27::i;:::-;5150:63;;;;5227:21;:26;;5252:1;5227:26:::0;5223:65:::1;;5276:1;5269:8;;;;;;;;5223:65;5322:15;::::0;::::1;::::0;5298:21:::1;5347:940;5367:21:::0;;::::1;5347:940;;;5409:16;5428:10;;5439:1;5428:13;;;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;5409:32;;5471:21;5459:33;;:9;:33;;;5455:80;;;5512:8;;;5455:80;5549:15;::::0;5584:32:::1;:14:::0;:32:::1;::::0;;::::1;::::0;:21:::1;:32;:::i;:::-;5548:68;;;;5635:10;5630:58;;5665:8;;;;;5630:58;5705:11:::0;;5701:530:::1;;5736:13;5752:31;:8;::::0;::::1;5773:9:::0;5752:20:::1;:31::i;:::-;-1:-1:-1::0;;;;;5736:47:63::1;;;5814:13;5805:5;:22;5801:77;;5851:8;;;;;;5801:77;5895:19;5917:1;:9;;5927:5;5917:16;;;;;;;;:::i;:::-;;;;;;;;;;;5895:38;;5952:15;5970:47;5982:6;5990:5;:12;;;6004:5;:12;;;5970:11;:47::i;:::-;5952:65:::0;-1:-1:-1;6035:17:63::1;5952:65:::0;6035:17;::::1;:::i;:::-;;;6086:7;6070:5;:12;;;:23;;;;;;;:::i;:::-;;;;;;;;6127:6;6111:5;:12;;;:22;;;;;;;:::i;:::-;;;;;;;;6187:8;-1:-1:-1::0;;;;;6157:59:63::1;6178:7;-1:-1:-1::0;;;;;6157:59:63::1;;6197:7;6206:9;6157:59;;;;;;7920:25:64::0;;;7993:10;7981:23;7976:2;7961:18;;7954:51;7908:2;7893:18;;7748:263;6157:59:63::1;;;;;;;;5718:513;;;5701:530;6244:32;:14:::0;:32:::1;::::0;;::::1;::::0;:21:::1;:32;:::i;:::-;;5395:892;;;5347:940;5390:3;;5347:940;;;;6297:53;6324:7;:5;:7::i;:::-;6333:8;6343:6;6297:26;:53::i;:::-;4954:1403;;;;;3426:1:5;3437:20:::0;1949:1;-1:-1:-1;;;;;;;;;;;4113:23:5;3860:283;3437:20;4844:1513:63;;;;;:::o;2536:220::-;9263:23;2694:16;;2583:4;;9263:23;2668:22;1890:17:62;1754:26;;4373:24:36;;4285:119;2668:22:63;:42;:81;;;;-1:-1:-1;2733:9:63;;;:16;2714:15;;;;:35;2668:81;2661:88;;;2536:220;:::o;1264:1239::-;-1:-1:-1;;;;;1533:21:63;;1418:28;1533:21;;;9263:23;1533:12;;;:21;;;;;1377:25;;1581:23;1533:21;1581;:23::i;:::-;1564:40;;1628:6;1618;:16;1614:70;;1657:16;;;1671:1;1657:16;;;;;;;;;;;;;;-1:-1:-1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1657:16:63;;;;;;;;;;;;;;;;;1650:23;;;;;;;1614:70;1701:32;1710:15;1719:6;1710;:15;:::i;:::-;1727:5;1701:8;:32::i;:::-;1693:40;;1768:5;1754:20;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1754:20:63;;;;;;;;;;;;;;;;-1:-1:-1;1808:15:63;;;;1743:31;;-1:-1:-1;1784:21:63;1871:27;:8;;;:25;:27::i;:::-;1833:65;;;;1908:18;-1:-1:-1;;;;;;;;;;;;;;;;;;;1908:18:63;1941:9;1936:561;1960:5;1956:1;:9;1936:561;;;1987:17;;2024:29;2042:10;2046:6;2042:1;:10;:::i;:::-;2024:14;;:17;:29::i;:::-;1986:67;;;;2091:9;2067:8;2076:1;2067:11;;;;;;;;:::i;:::-;;;;;;;:21;;:33;;;;;2135:6;2114:8;2123:1;2114:11;;;;;;;;:::i;:::-;;;;;;;:18;;:27;;;;;2171:23;2159:35;;:9;:35;2155:82;;;2214:8;;;;2155:82;2250:13;2266:39;:8;;;2294:9;2266:20;:39::i;:::-;-1:-1:-1;;;;;2250:55:63;;;2327:1;:9;;2337:5;2327:16;;;;;;;;:::i;:::-;;;;;;;;;;;2319:24;;;;;;;;;;;;;;;;;;;;;;;;;;;2378:47;2390:6;2398:5;:12;;;2412:5;:12;;;2378:11;:47::i;:::-;2357:8;2366:1;2357:11;;;;;;;;:::i;:::-;;;;;;;:18;;:68;;;;;2473:13;2465:5;:21;2439:8;2448:1;2439:11;;;;;;;;:::i;:::-;;;;;;;;;;;:47;;;:23;;;;:47;-1:-1:-1;;;1936:561:63;1967:3;;1936:561;;;;1408:1095;;;;;;1264:1239;;;;;:::o;3137:1668::-;3395:21:5;:19;:21::i;:::-;3205:6:63::1;3215:1;3205:11:::0;3201:60:::1;;3239:11;;-1:-1:-1::0;;;3239:11:63::1;;;;;;;;;;;3201:60;966:10:4::0;3270:14:63::1;3327:7;:5;:7::i;:::-;3348:49;::::0;-1:-1:-1;;;3348:49:63;;3391:4:::1;3348:49;::::0;::::1;556:51:64::0;3310:24:63;;-1:-1:-1;;;;;;3348:34:63;::::1;::::0;::::1;::::0;529:18:64;;3348:49:63::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;3344:100;;;3420:13;;-1:-1:-1::0;;;3420:13:63::1;;;;;;;;;;;3344:100;3453:27;3510:6;-1:-1:-1::0;;;;;3497:33:63::1;;:35;;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;3543:34;::::0;-1:-1:-1;;;3543:34:63;;-1:-1:-1;;;;;8769:32:64;;;3543:34:63::1;::::0;::::1;8751:51:64::0;8818:18;;;8811:34;;;3453:80:63;;-1:-1:-1;3543:18:63;;::::1;::::0;::::1;::::0;8724::64;;3543:34:63::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;3587:23;3626:6;-1:-1:-1::0;;;;;3613:31:63::1;;:33;;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;3587:59;;3656:21;3680:11;-1:-1:-1::0;;;;;3680:24:63::1;;:26;;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;3656:50;;3731:13;-1:-1:-1::0;;;;;3721:23:63::1;:6;-1:-1:-1::0;;;;;3721:23:63::1;;3717:238;;3775:38;::::0;-1:-1:-1;;;3775:38:63;;::::1;::::0;::::1;3219:25:64::0;;;3760:12:63::1;::::0;-1:-1:-1;;;;;3775:30:63;::::1;::::0;::::1;::::0;3192:18:64;;3775:38:63::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;3760:53:::0;-1:-1:-1;3831:8:63;;3827:118:::1;;3859:39;::::0;-1:-1:-1;;;3859:39:63;;-1:-1:-1;;;;;8769:32:64;;;3859:39:63::1;::::0;::::1;8751:51:64::0;8818:18;;;8811:34;;;3859:18:63;::::1;::::0;::::1;::::0;8724::64;;3859:39:63::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;3926:4;3916:14;;;;;:::i;:::-;;;3827:118;3746:209;3717:238;1754:26:62::0;1890:17;1754:26;4373:24:36;;9263:23:63;;4053:15:::1;::::0;4192:22:::1;4219:29;:10;:27;:29::i;:::-;4189:59;;;;4280:9;4262:27;;:15;:27;;;4258:227;;;4305:42;:10:::0;4321:9;4340:5;4305:15:::1;:42::i;:::-;-1:-1:-1::0;;4391:11:63::1;::::0;::::1;:22;4403:9;4411:1;4403:5:::0;:9:::1;:::i;:::-;4391:22;;;;;;;;;;;;4382:6;:31;;;;:::i;:::-;4361:18;::::0;;;:11:::1;::::0;::::1;:18;::::0;;;;:52;4258:227:::1;;;4468:6:::0;4444:11:::1;::::0;::::1;:20;4456:7;::::0;::::1;:::i;:::-;;;;4444:20;;;;;;;;;;;;:30;;;;;;;:::i;:::-;::::0;;;-1:-1:-1;;4258:227:63::1;-1:-1:-1::0;;;;;4548:20:63;::::1;4495:50;4548:20:::0;;;:12:::1;::::0;::::1;:20;::::0;;;;;4606:32:::1;4548:20:::0;4606:32:::1;::::0;;::::1;::::0;:21:::1;:32;:::i;:::-;4578:60:::0;-1:-1:-1;4648:53:63::1;::::0;-1:-1:-1;4648:53:63::1;::::0;::::1;4678:22;4694:6:::0;4578:60;4678:22:::1;:::i;:::-;4648:14:::0;;:53;:18:::1;:53::i;:::-;;4735:6;4711:1;:20;;;:30;;;;;;;:::i;:::-;::::0;;;-1:-1:-1;;4756:42:63::1;::::0;;7920:25:64;;;7993:10;7981:23;;7976:2;7961:18;;7954:51;-1:-1:-1;;;;;4756:42:63;::::1;::::0;::::1;::::0;7893:18:64;4756:42:63::1;;;;;;;3191:1614;;;;;;;;;;;;3437:20:5::0;1949:1;-1:-1:-1;;;;;;;;;;;4113:23:5;3860:283;3437:20;3137:1668:63;:::o;6396:1254::-;6467:15;3395:21:5;:19;:21::i;:::-;9263:23:63;6576:15:::1;::::0;::::1;::::0;6618:9:::1;::::0;::::1;:16:::0;6648:19;;::::1;;::::0;:35:::1;;-1:-1:-1::0;6671:12:63;;6648:35:::1;6644:74;;;6706:1;6699:8;;;;;;;6644:74;6737:37;6746:7:::0;6755:18:::1;6764:9:::0;6755:6;:18:::1;:::i;:::-;6737:8;:37::i;:::-;6727:47;;6785:19;6820:7;:5;:7::i;:::-;6785:43;;6838:20;6861:6;-1:-1:-1::0;;;;;6861:22:63::1;;:24;;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;6838:47;;6895:14;6923::::0;6951:18:::1;-1:-1:-1::0;;;;;;;;;;;;;;;;;;;6951:18:63::1;6984:9;6979:283;7003:7;6999:1;:11;6979:283;;;7039:9;::::0;::::1;7049:13;7061:1:::0;7049:9;:13:::1;:::i;:::-;7039:24;;;;;;;;:::i;:::-;;;;;;;;;;;7031:32;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;;;7105:12;7090:5;:12;;;7081:6;:21;;;;:::i;:::-;:36;7137:5;7077:80;7180:12:::0;;7170:22:::1;::::0;;::::1;:::i;:::-;;;7216:5;:12;;;7206:22;;;;;:::i;:::-;::::0;-1:-1:-1;7242:9:63;::::1;::::0;::::1;:::i;:::-;::::0;-1:-1:-1;;7012:3:63::1;;6979:283;;;-1:-1:-1::0;7276:11:63;;7272:372:::1;;7307:10:::0;;7303:234:::1;;7337:23;::::0;-1:-1:-1;;;7337:23:63;;::::1;::::0;::::1;3219:25:64::0;;;-1:-1:-1;;;;;7337:15:63;::::1;::::0;::::1;::::0;3192:18:64;;7337:23:63::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;7399:6;-1:-1:-1::0;;;;;7378:41:63::1;;:43;;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1::0;;;;;7378:62:63::1;;7441:7;:5;:7::i;:::-;7450:24;7466:6:::0;7450:24:::1;:::i;:::-;7378:97;::::0;-1:-1:-1;;;;;;7378:97:63::1;::::0;;;;;;-1:-1:-1;;;;;8769:32:64;;;7378:97:63::1;::::0;::::1;8751:51:64::0;8818:18;;;8811:34;8724:18;;7378:97:63::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;7516:6;7493:1;:19;;;:29;;;;;;;:::i;:::-;::::0;;;-1:-1:-1;;7303:234:63::1;7569:7;7550:1;:15;;;:26;;;;;;;:::i;:::-;::::0;;;-1:-1:-1;;7595:38:63::1;::::0;;2104:25:64;;;2160:2;2145:18;;2138:34;;;7595:38:63::1;::::0;2077:18:64;7595:38:63::1;;;;;;;7272:372;6484:1166;;;;;;;;3426:1:5;3437:20:::0;1949:1;-1:-1:-1;;;;;;;;;;;4113:23:5;3860:283;3437:20;6396:1254:63;;;:::o;602:92:62:-;666:21;1890:17;666:21;;-1:-1:-1;;;;;666:21:62;;602:92::o;9071:205:3:-;9129:30;;3147:66;9186:27;9171:42;9071:205;-1:-1:-1;;9071:205:3:o;1266:389:62:-;6929:20:3;:18;:20::i;:::-;1356:24:62::1;:22;:24::i;:::-;-1:-1:-1::0;;;;;1394:20:62;::::1;::::0;;:44:::1;;-1:-1:-1::0;;;;;;1418:20:62;::::1;::::0;1394:44:::1;1390:93;;;1461:11;;-1:-1:-1::0;;;1461:11:62::1;;;;;;;;;;;1390:93;1890:17:::0;1542:16;;-1:-1:-1;;;;;1542:16:62;;::::1;-1:-1:-1::0;;;;;;1542:16:62;;::::1;;::::0;;-1:-1:-1;1568:7:62;::::1;:16:::0;;;;::::1;::::0;;;::::1;;::::0;;1594:54:::1;:12;::::0;::::1;1619:15;-1:-1:-1::0;1594:17:62::1;:54::i;:::-;;;1346:309;1266:389:::0;;:::o;7683:1465:63:-;9263:23;1754:26:62;1890:17;1754:26;7770:28:63;;7948:29;1754:26:62;7948:27:63;:29::i;:::-;7898:79;;;;;7987:27;8047:9;8028:28;;:15;:28;;;8024:312;;-1:-1:-1;;;;;;8072:33:63;;8024:312;;;8166:39;:10;8195:9;8166:28;:39::i;:::-;-1:-1:-1;;;;;8158:48:63;;-1:-1:-1;8224:24:63;;:61;;;;-1:-1:-1;8264:16:63;:10;8278:1;8264:13;:16::i;:::-;:21;;;8252:33;;:9;:33;;;8224:61;8220:106;;;8305:7;;;;;7683:1465;;:::o;8220:106::-;8372:16;;8402:37;;;8398:74;;;8455:7;;;;;;7683:1465;;:::o;8398:74::-;8482:14;8547:20;;:59;;8574:11;;;:32;8586:19;8604:1;8586:15;:19;:::i;:::-;8574:32;;;;;;;;;;;;8547:59;;;8570:1;8547:59;8511:32;;;;:11;;;:32;;;;;;:96;;;;:::i;:::-;8482:125;-1:-1:-1;8636:23:63;:19;8658:1;8636:23;:::i;:::-;8617:42;;:16;8674:11;;;8670:48;;8701:7;;;;;;;7683:1465;;:::o;8670:48::-;8728:13;8744:17;:1;:8;;4373:24:36;;4285:119;8744:17:63;8728:33;;8795:6;8771:1;:20;;;:30;;;;;;;:::i;:::-;;;;-1:-1:-1;8811:27:63;;-1:-1:-1;8854:7:63;:5;:7::i;:::-;-1:-1:-1;;;;;8841:34:63;;:36;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;8887:50;;-1:-1:-1;;;8887:50:63;;-1:-1:-1;;;;;8887:18:63;;:50;;;8751:51:64;;;8818:18;;;8811:34;;;:66:63;;-1:-1:-1;8887:18:63;;8724::64;;8887:50:63;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;8947:40:63;;-1:-1:-1;;;8947:8:63;;;8961:9;8980:5;8947:13;:40::i;:::-;;;8997:15;9015:38;9027:6;9035:7;9044:8;-1:-1:-1;;;;;9015:38:63;:11;:38::i;:::-;9078:22;;;;;;;;;;;;;;;;;;;9063:9;;;:38;;;;;;;;-1:-1:-1;9063:38:63;;;;;;;;;;;;;;;;;;;;;;;;;;;;9111:19;;;:30;;8997:56;;-1:-1:-1;8997:56:63;;9111:19;;-1:-1:-1;9111:30:63;;8997:56;;9111:30;:::i;:::-;;;;-1:-1:-1;;;;;;;;;;;;;;7683:1465:63:o;3470:384:5:-;-1:-1:-1;;;;;;;;;;;3670:9:5;;-1:-1:-1;;3670:20:5;3666:88;;3713:30;;-1:-1:-1;;;3713:30:5;;;;;;;;;;;3666:88;1991:1;3828:19;;3470:384::o;3827:389:36:-;3965:24;;3899:11;;;;;;4003:8;;;3999:211;;4035:5;4042:1;4045;4027:20;;;;;;;;;3999:211;4078:26;4107:41;4121:4;4140:7;4146:1;4140:3;:7;:::i;:::-;7532:28;7595:20;;;7660:4;7647:18;;;7643:28;;7422:265;4107:41;4176:9;4170:4;;-1:-1:-1;4176:9:36;;;;-1:-1:-1;;;;4187:11:36;;-1:-1:-1;;;;;4187:11:36;;-1:-1:-1;4162:37:36;;-1:-1:-1;;4162:37:36;3827:389;;;;;;:::o;8847:226:37:-;8926:11;;;;8994:32;9001:3;9021;8994:6;:32::i;:::-;8964:62;;-1:-1:-1;8964:62:37;-1:-1:-1;;;8847:226:37;;;;;;:::o;1652:295:36:-;1764:24;;1731:7;;;1812:50;1764:4;1850:3;1731:7;1764:24;1812:18;:50::i;:::-;1798:64;;1886:3;1879;:10;:61;;7532:28;7595:20;;;7660:4;7647:18;;7643:28;;1896:44;-1:-1:-1;;;1896:44:36;;-1:-1:-1;;;;;1896:44:36;1879:61;;;1892:1;1879:61;1872:68;1652:295;-1:-1:-1;;;;;1652:295:36:o;7242:3683:34:-;7324:14;7375:12;7389:11;7404:12;7411:1;7414;7404:6;:12::i;:::-;7374:42;;;;7498:4;7506:1;7498:9;7494:365;;7833:11;7827:3;:17;;;;;:::i;:::-;;7820:24;;;;;;7494:365;7984:4;7969:11;:19;7965:142;;8008:84;5312:5;8028:16;;5311:36;940:4:28;5306:42:34;8008:11;:84::i;:::-;8359:17;8510:11;8507:1;8504;8497:25;8902:12;8932:15;;;8917:31;;9067:22;;;;;9800:1;9781;:15;;9780:21;;10033;;;10029:25;;10018:36;10103:21;;;10099:25;;10088:36;10175:21;;;10171:25;;10160:36;10246:21;;;10242:25;;10231:36;10319:21;;;10315:25;;10304:36;10393:21;;;10389:25;;;10378:36;9309:12;;;;9305:23;;;9330:1;9301:31;8622:18;;;8612:29;;;9416:11;;;;8665:19;;;;9160:14;;;;9409:18;;;;10868:13;;-1:-1:-1;;7242:3683:34;;;;;:::o;7188:136:37:-;7262:4;7285:32;7292:3;7312;7285:6;:32::i;1134:238:61:-;-1:-1:-1;;;;;;;1220:12:61;;;1216:150;;1248:38;1274:2;1279:6;1248:17;:38::i;:::-;1134:238;;;:::o;1216:150::-;1317:38;-1:-1:-1;;;;;1317:26:61;;1344:2;1348:6;1317:26;:38::i;3860:283:5:-;1949:1;-1:-1:-1;;;;;;;;;;;4113:23:5;3860:283::o;8031:117:37:-;8097:7;8123:18;8130:3;8123:6;:18::i;5617:111:34:-;5675:7;5312:5;;;5709;;;5311:36;5306:42;;5701:20;5071:294;8485:221:37;8562:11;;;;8631:21;8634:3;8646:5;8631:2;:21::i;1277:210:36:-;1389:16;;1442:38;1450:4;1469:3;1474:5;1442:7;:38::i;:::-;1435:45;;;;1277:210;;;;;;;:::o;6868:161:37:-;6954:4;6977:45;6981:3;7001;7015:5;6977:3;:45::i;:::-;6970:52;6868:161;-1:-1:-1;;;;6868:161:37:o;7082:141:3:-;7149:17;:15;:17::i;:::-;7144:73;;7189:17;;-1:-1:-1;;;7189:17:3;;;;;;;;;;;7144:73;7082:141::o;2684:111:5:-;6929:20:3;:18;:20::i;:::-;2754:34:5::1;:32;:34::i;2716:606:36:-:0;2834:24;;2801:7;;;2834:24;2933:1;2927:7;;2923:234;;;2950:11;2970:14;2980:3;2970:9;:14::i;:::-;2964:20;;:3;:20;:::i;:::-;7532:28;7595:20;;;7660:4;7647:18;;2950:34;;-1:-1:-1;7643:28:36;;3008:42;;;;;3002:48;;;;2998:149;;;3077:3;3070:10;;2998:149;;;3125:7;:3;3131:1;3125:7;:::i;:::-;3119:13;;2998:149;2936:221;2923:234;3167:11;3181:53;3200:4;3219:3;3224;3229:4;3181:18;:53::i;:::-;3167:67;-1:-1:-1;3252:8:36;;:63;;3267:41;3281:4;3300:7;3306:1;3300:3;:7;:::i;3267:41::-;:48;-1:-1:-1;;;3267:48:36;;-1:-1:-1;;;;;3267:48:36;3252:63;;;3263:1;3252:63;3245:70;2716:606;-1:-1:-1;;;;;;;2716:606:36:o;4476:138::-;-1:-1:-1;;;;;;;;;;;;;;;;;4585:4:36;:17;;4603:3;4585:22;;;;;;;;;;:::i;:::-;;;;;;;;;;4578:29;;;;;;;;;4585:22;;4578:29;;;;;;-1:-1:-1;;;4578:29:36;;-1:-1:-1;;;;;4578:29:36;;;;;;;;;4476:138;-1:-1:-1;;;4476:138:36:o;5139:305:37:-;5224:11;5276:16;;;:11;;;:16;;;;;;5224:11;;5276:16;5302:136;;5347:18;5356:3;5361;5347:8;:18::i;:::-;5339:39;-1:-1:-1;5375:1:37;;-1:-1:-1;5339:39:37;;-1:-1:-1;5339:39:37;5302:136;5417:4;;-1:-1:-1;5423:3:37;-1:-1:-1;5409:18:37;;6846:433:36;7003:7;7022:230;7035:4;7029:3;:10;7022:230;;;7055:11;7069:23;7082:3;7087:4;7069:12;:23::i;:::-;7532:28;7595:20;;;7660:4;7647:18;;7055:37;;-1:-1:-1;7110:35:36;;;;7643:28;;7110:29;;;:35;7106:136;;;7171:7;:3;7177:1;7171:7;:::i;:::-;7165:13;;7106:136;;;7224:3;7217:10;;7106:136;7041:211;7022:230;;;-1:-1:-1;7268:4:36;6846:433;-1:-1:-1;;;6846:433:36:o;1027:550:34:-;1088:12;;-1:-1:-1;;1471:1:34;1468;1461:20;1501:9;;;;1549:11;;;1535:12;;;;1531:30;;;;;1027:550;-1:-1:-1;;1027:550:34:o;1776:194:28:-;1881:10;1875:4;1868:24;1918:4;1912;1905:18;1949:4;1943;1936:18;3298:164:37;3378:4;3401:16;;;:11;;;:16;;;;;3394:23;;;3434:21;3401:3;3413;3434:16;:21::i;1290:365:23:-;1399:6;1375:21;:30;1371:125;;;1428:57;;-1:-1:-1;;;1428:57:23;;1455:21;1428:57;;;2104:25:64;2145:18;;;2138:34;;;2077:18;;1428:57:23;;;;;;;;1371:125;1507:12;1521:23;1548:9;-1:-1:-1;;;;;1548:14:23;1570:6;1548:33;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1506:75;;;;1596:7;1591:58;;1619:19;1627:10;1619:7;:19::i;:::-;1361:294;;1290:365;;:::o;1219:160:21:-;1328:43;;;-1:-1:-1;;;;;8769:32:64;;1328:43:21;;;8751:51:64;8818:18;;;;8811:34;;;1328:43:21;;;;;;;;;;8724:18:64;;;;1328:43:21;;;;;;;;-1:-1:-1;;;;;1328:43:21;-1:-1:-1;;;1328:43:21;;;1301:71;;1321:5;;1301:19;:71::i;4315:123:37:-;4387:7;4413:18;:3;:16;:18::i;4791:207::-;4874:11;;;4928:19;:3;4941:5;4928:12;:19::i;:::-;4972:18;;;;:11;;;;;:18;;;;;;;;;4791:207;-1:-1:-1;;;;4791:207:37:o;4790:922:36:-;4971:11;;4911:16;;;;4997:7;;4993:713;;5020:26;5049:28;5063:4;5069:7;5075:1;5069:3;:7;:::i;5049:28::-;5108:9;;;;-1:-1:-1;5108:9:36;;;;;-1:-1:-1;;;5151:11:36;;-1:-1:-1;;;;;5151:11:36;;5236:13;;;;5232:89;;;5276:30;;-1:-1:-1;;;5276:30:36;;;;;;;;;;;5232:89;5395:3;5384:14;;:7;:14;;;5380:163;;5418:19;;;;-1:-1:-1;;;;;;;;5418:19:36;;;;;;5380:163;;;5486:41;;;;;;;;;;;;;;;-1:-1:-1;;;;;5486:41:36;;;;;;;;;;5476:52;;;;;;;-1:-1:-1;5476:52:36;;;;;;;;;;;;;;-1:-1:-1;;;5476:52:36;;;;;;;;;;5380:163;5564:9;-1:-1:-1;5575:5:36;;-1:-1:-1;5556:25:36;;-1:-1:-1;;;5556:25:36;4993:713;-1:-1:-1;;5622:41:36;;;;;;;;;;;;;;;-1:-1:-1;;;;;5622:41:36;;;;;;;;;;5612:52;;;;;;;-1:-1:-1;5612:52:36;;;;;;;;;;;;;-1:-1:-1;;;5612:52:36;;;;;;;;;;;;-1:-1:-1;;5656:5:36;5678:17;;2956:174:37;3048:4;3064:16;;;:11;;;:16;;;;;:24;;;3105:18;3064:3;3076;3105:13;:18::i;8485:120:3:-;8535:4;8558:26;:24;:26::i;:::-;:40;-1:-1:-1;;;8558:40:3;;;;;;-1:-1:-1;8485:120:3:o;2801:183:5:-;6929:20:3;:18;:20::i;20567:5181:34:-;20615:7;20733:1;20728;:6;20724:53;;-1:-1:-1;20761:1:34;20567:5181::o;20724:53::-;21717:1;21745;-1:-1:-1;;;21765:16:34;;21761:92;;21808:3;21801:10;;;;;21836:2;21829:9;21761:92;-1:-1:-1;;;21870:2:34;:15;21866:90;;21912:2;21905:9;;;;;21939:2;21932:9;21866:90;-1:-1:-1;;;21973:2:34;:15;21969:90;;22015:2;22008:9;;;;;22042:2;22035:9;21969:90;22083:7;22076:2;:15;22072:89;;22118:2;22111:9;;;;;22145:1;22138:8;22072:89;22185:6;22178:2;:14;22174:87;;22219:1;22212:8;;;;;22245:1;22238:8;22174:87;22285:6;22278:2;:14;22274:87;;22319:1;22312:8;;;;;22345:1;22338:8;22274:87;22385:6;22378:2;:14;22374:61;;22419:1;22412:8;22374:61;22861:1;:6;22872:1;22860:13;;;;;24771:1;22860:13;24771:6;;;;:::i;:::-;;24766:2;:11;24765:18;;24760:23;;24891:1;24884:2;24880:1;:6;;;;;:::i;:::-;;24875:2;:11;24874:18;;24869:23;;25002:1;24995:2;24991:1;:6;;;;;:::i;:::-;;24986:2;:11;24985:18;;24980:23;;25111:1;25104:2;25100:1;:6;;;;;:::i;:::-;;25095:2;:11;25094:18;;25089:23;;25221:1;25214:2;25210:1;:6;;;;;:::i;:::-;;25205:2;:11;25204:18;;25199:23;;25331:1;25324:2;25320:1;:6;;;;;:::i;:::-;;25315:2;:11;25314:18;;25309:23;;25703:28;25728:2;25724:1;:6;;;;;:::i;:::-;;25719:11;;;34795:145:35;25703:28:34;25698:33;;;20567:5181;-1:-1:-1;;;20567:5181:34:o;6062:433:36:-;6219:7;6238:230;6251:4;6245:3;:10;6238:230;;;6271:11;6285:23;6298:3;6303:4;6285:12;:23::i;:::-;7532:28;7595:20;;;7660:4;7647:18;;6271:37;;-1:-1:-1;6326:35:36;;;;7643:28;;6326:29;;;:35;6322:136;;;6388:3;6381:10;;6322:136;;;6436:7;:3;6442:1;6436:7;:::i;:::-;6430:13;;6322:136;6257:211;6238:230;;4085:140:37;4172:4;4195:23;:3;4214;4195:18;:23::i;5841:153:34:-;5903:7;5976:11;5986:1;5977:5;;;5976:11;:::i;:::-;5966:21;;5967:5;;;5966:21;:::i;6867:129:38:-;6940:4;6963:26;6971:3;6983:5;6963:7;:26::i;5559:487:23:-;5690:17;;:21;5686:354;;5887:10;5881:17;5943:15;5930:10;5926:2;5922:19;5915:44;5686:354;6010:19;;-1:-1:-1;;;6010:19:23;;;;;;;;;;;8370:720:21;8450:18;8478:19;8616:4;8613:1;8606:4;8600:11;8593:4;8587;8583:15;8580:1;8573:5;8566;8561:60;8673:7;8663:176;;8717:4;8711:11;8762:16;8759:1;8754:3;8739:40;8808:16;8803:3;8796:29;8663:176;-1:-1:-1;;8916:1:21;8910:8;8866:16;;-1:-1:-1;8942:15:21;;:68;;8994:11;9009:1;8994:16;;8942:68;;;-1:-1:-1;;;;;8960:26:21;;;:31;8942:68;8938:146;;;9033:40;;-1:-1:-1;;;9033:40:21;;-1:-1:-1;;;;;574:32:64;;9033:40:21;;;556:51:64;529:18;;9033:40:21;410:203:64;7693:115:38;7756:7;7782:19;7790:3;4373:24:36;;4285:119;8150:129:38;8224:7;8250:22;8254:3;8266:5;8250:3;:22::i;6576:123::-;6646:4;6669:23;6674:3;6686:5;6669:4;:23::i;7474:138::-;7554:4;5006:21;;;:14;;;:21;;;;;;:26;;7577:28;4910:129;2910:1368;2976:4;3105:21;;;:14;;;:21;;;;;;3141:13;;3137:1135;;3508:18;3529:12;3540:1;3529:8;:12;:::i;:::-;3575:18;;3508:33;;-1:-1:-1;3555:17:38;;3575:22;;3596:1;;3575:22;:::i;:::-;3555:42;;3630:9;3616:10;:23;3612:378;;3659:17;3679:3;:11;;3691:9;3679:22;;;;;;;;:::i;:::-;;;;;;;;;3659:42;;3826:9;3800:3;:11;;3812:10;3800:23;;;;;;;;:::i;:::-;;;;;;;;;;;;:35;;;;3939:25;;;:14;;;:25;;;;;:36;;;3612:378;4068:17;;:3;;:17;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;4171:3;:14;;:21;4186:5;4171:21;;;;;;;;;;;4164:28;;;4214:4;4207:11;;;;;;;3137:1135;4256:5;4249:12;;;;;5569:118;5636:7;5662:3;:11;;5674:5;5662:18;;;;;;;;:::i;:::-;;;;;;;;;5655:25;;5569:118;;;;:::o;2336:406::-;2399:4;5006:21;;;:14;;;:21;;;;;;2415:321;;-1:-1:-1;2457:23:38;;;;;;;;:11;:23;;;;;;;;;;;;;2639:18;;2615:21;;;:14;;;:21;;;;;;:42;;;;2671:11;;2415:321;-1:-1:-1;2720:5:38;2713:12;;618:591:64;688:6;696;749:2;737:9;728:7;724:23;720:32;717:52;;;765:1;762;755:12;717:52;805:9;792:23;834:18;875:2;867:6;864:14;861:34;;;891:1;888;881:12;861:34;929:6;918:9;914:22;904:32;;974:7;967:4;963:2;959:13;955:27;945:55;;996:1;993;986:12;945:55;1036:2;1023:16;1062:2;1054:6;1051:14;1048:34;;;1078:1;1075;1068:12;1048:34;1123:7;1118:2;1109:6;1105:2;1101:15;1097:24;1094:37;1091:57;;;1144:1;1141;1134:12;1091:57;1175:2;1167:11;;;;;1197:6;;-1:-1:-1;618:591:64;;-1:-1:-1;;;;618:591:64:o;1214:163::-;1281:20;;1341:10;1330:22;;1320:33;;1310:61;;1367:1;1364;1357:12;1382:358;1449:6;1457;1510:2;1498:9;1489:7;1485:23;1481:32;1478:52;;;1526:1;1523;1516:12;1478:52;1552:23;;-1:-1:-1;;;;;1604:31:64;;1594:42;;1584:70;;1650:1;1647;1640:12;1584:70;1673:5;-1:-1:-1;1697:37:64;1730:2;1715:18;;1697:37;:::i;:::-;1687:47;;1382:358;;;;;:::o;1745:180::-;1804:6;1857:2;1845:9;1836:7;1832:23;1828:32;1825:52;;;1873:1;1870;1863:12;1825:52;-1:-1:-1;1896:23:64;;1745:180;-1:-1:-1;1745:180:64:o;2183:131::-;-1:-1:-1;;;;;2258:31:64;;2248:42;;2238:70;;2304:1;2301;2294:12;2319:749;2413:6;2421;2429;2482:2;2470:9;2461:7;2457:23;2453:32;2450:52;;;2498:1;2495;2488:12;2450:52;2537:9;2524:23;2556:31;2581:5;2556:31;:::i;:::-;2606:5;-1:-1:-1;2662:2:64;2647:18;;2634:32;2685:18;2715:14;;;2712:34;;;2742:1;2739;2732:12;2712:34;2780:6;2769:9;2765:22;2755:32;;2825:7;2818:4;2814:2;2810:13;2806:27;2796:55;;2847:1;2844;2837:12;2796:55;2887:2;2874:16;2913:2;2905:6;2902:14;2899:34;;;2929:1;2926;2919:12;2899:34;2982:7;2977:2;2967:6;2964:1;2960:14;2956:2;2952:23;2948:32;2945:45;2942:65;;;3003:1;3000;2993:12;2942:65;3034:2;3030;3026:11;3016:21;;3056:6;3046:16;;;;;2319:749;;;;;:::o;3447:383::-;3524:6;3532;3540;3593:2;3581:9;3572:7;3568:23;3564:32;3561:52;;;3609:1;3606;3599:12;3561:52;3648:9;3635:23;3667:31;3692:5;3667:31;:::i;:::-;3717:5;3769:2;3754:18;;3741:32;;-1:-1:-1;3820:2:64;3805:18;;;3792:32;;3447:383;-1:-1:-1;;;3447:383:64:o;3835:941::-;4058:2;4110:21;;;4180:13;;4083:18;;;4202:22;;;4029:4;;4058:2;4243;;4261:18;;;;4302:15;;;4029:4;4345:405;4359:6;4356:1;4353:13;4345:405;;;4418:13;;4456:9;;4444:22;;4506:11;;;4500:18;4486:12;;;4479:40;4573:11;;;4567:18;4560:26;4553:34;4539:12;;;4532:56;4611:4;4655:11;;;4649:18;4635:12;;;4628:40;4697:4;4688:14;;;;4725:15;;;;4381:1;4374:9;4345:405;;;-1:-1:-1;4767:3:64;;3835:941;-1:-1:-1;;;;;;;3835:941:64:o;4781:127::-;4842:10;4837:3;4833:20;4830:1;4823:31;4873:4;4870:1;4863:15;4897:4;4894:1;4887:15;4913:1213;5015:6;5023;5031;5084:2;5072:9;5063:7;5059:23;5055:32;5052:52;;;5100:1;5097;5090:12;5052:52;5139:9;5126:23;5158:31;5183:5;5158:31;:::i;:::-;5208:5;-1:-1:-1;5265:2:64;5250:18;;5237:32;5278:33;5237:32;5278:33;:::i;:::-;5330:7;-1:-1:-1;5388:2:64;5373:18;;5360:32;5411:18;5441:14;;;5438:34;;;5468:1;5465;5458:12;5438:34;5506:6;5495:9;5491:22;5481:32;;5551:7;5544:4;5540:2;5536:13;5532:27;5522:55;;5573:1;5570;5563:12;5522:55;5609:2;5596:16;5631:2;5627;5624:10;5621:36;;;5637:18;;:::i;:::-;5712:2;5706:9;5680:2;5766:13;;-1:-1:-1;;5762:22:64;;;5786:2;5758:31;5754:40;5742:53;;;5810:18;;;5830:22;;;5807:46;5804:72;;;5856:18;;:::i;:::-;5896:10;5892:2;5885:22;5931:2;5923:6;5916:18;5971:7;5966:2;5961;5957;5953:11;5949:20;5946:33;5943:53;;;5992:1;5989;5982:12;5943:53;6048:2;6043;6039;6035:11;6030:2;6022:6;6018:15;6005:46;6093:1;6088:2;6083;6075:6;6071:15;6067:24;6060:35;6114:6;6104:16;;;;;;;4913:1213;;;;;:::o;6131:388::-;6288:2;6277:9;6270:21;6327:6;6322:2;6311:9;6307:18;6300:34;6384:6;6376;6371:2;6360:9;6356:18;6343:48;6440:1;6411:22;;;6435:2;6407:31;;;6400:42;;;;6503:2;6482:15;;;-1:-1:-1;;6478:29:64;6463:45;6459:54;;6131:388;-1:-1:-1;6131:388:64:o;7032:127::-;7093:10;7088:3;7084:20;7081:1;7074:31;7124:4;7121:1;7114:15;7148:4;7145:1;7138:15;7164:184;7222:6;7275:2;7263:9;7254:7;7250:23;7246:32;7243:52;;;7291:1;7288;7281:12;7243:52;7314:28;7332:9;7314:28;:::i;7353:127::-;7414:10;7409:3;7405:20;7402:1;7395:31;7445:4;7442:1;7435:15;7469:4;7466:1;7459:15;7485:125;7550:9;;;7571:10;;;7568:36;;;7584:18;;:::i;7615:128::-;7682:9;;;7703:11;;;7700:37;;;7717:18;;:::i;8016:277::-;8083:6;8136:2;8124:9;8115:7;8111:23;8107:32;8104:52;;;8152:1;8149;8142:12;8104:52;8184:9;8178:16;8237:5;8230:13;8223:21;8216:5;8213:32;8203:60;;8259:1;8256;8249:12;8298:274;8391:6;8444:2;8432:9;8423:7;8419:23;8415:32;8412:52;;;8460:1;8457;8450:12;8412:52;8492:9;8486:16;8511:31;8536:5;8511:31;:::i;9389:184::-;9459:6;9512:2;9500:9;9491:7;9487:23;9483:32;9480:52;;;9528:1;9525;9518:12;9480:52;-1:-1:-1;9551:16:64;;9389:184;-1:-1:-1;9389:184:64:o;9578:136::-;9617:3;9645:5;9635:39;;9654:18;;:::i;:::-;-1:-1:-1;;;9690:18:64;;9578:136::o;9988:135::-;10027:3;10048:17;;;10045:43;;10068:18;;:::i;:::-;-1:-1:-1;10115:1:64;10104:13;;9988:135::o;10406:136::-;10441:3;-1:-1:-1;;;10462:22:64;;10459:48;;10487:18;;:::i;:::-;-1:-1:-1;10527:1:64;10523:13;;10406:136::o;10824:127::-;10885:10;10880:3;10876:20;10873:1;10866:31;10916:4;10913:1;10906:15;10940:4;10937:1;10930:15;11166:217;11206:1;11232;11222:132;;11276:10;11271:3;11267:20;11264:1;11257:31;11311:4;11308:1;11301:15;11339:4;11336:1;11329:15;11222:132;-1:-1:-1;11368:9:64;;11166:217::o;11388:127::-;11449:10;11444:3;11440:20;11437:1;11430:31;11480:4;11477:1;11470:15;11504:4;11501:1;11494:15
Swarm Source
ipfs://3bcf767418f9bf5f46216d11963df1641c0fc8ab7a0a049324415ba392f6a9f9
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in MON
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.