ETH Price: $2,957.47 (+0.60%)

Contract

0x5E305dcB433D80519Ce2B5cb0f6A05Edb42776d2

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To
Unstake And With...199419772025-12-25 17:46:281 hr ago1766684788IN
0x5E305dcB...db42776d2
0 ETH0.000001960.0012
Unstake And With...199278352025-12-25 13:50:465 hrs ago1766670646IN
0x5E305dcB...db42776d2
0 ETH0.000001860.001
Solve By Zap199258352025-12-25 13:17:265 hrs ago1766668646IN
0x5E305dcB...db42776d2
0 ETH0.000001680.00119926
Unstake And With...199117552025-12-25 9:22:469 hrs ago1766654566IN
0x5E305dcB...db42776d2
0 ETH0.000001960.00119926
Unstake And With...199100602025-12-25 8:54:3110 hrs ago1766652871IN
0x5E305dcB...db42776d2
0 ETH0.000001880.001036
Unstake And With...198441972025-12-24 14:36:4828 hrs ago1766587008IN
0x5E305dcB...db42776d2
0 ETH0.000002530.00229928
Unstake And With...198410062025-12-24 13:43:3729 hrs ago1766583817IN
0x5E305dcB...db42776d2
0 ETH0.000002820.002855
Unstake And With...198409272025-12-24 13:42:1829 hrs ago1766583738IN
0x5E305dcB...db42776d2
0 ETH0.000003040.003291
Unstake And With...198399002025-12-24 13:25:1129 hrs ago1766582711IN
0x5E305dcB...db42776d2
0 ETH0.000001710.00070016
Unstake And With...198346242025-12-24 11:57:1531 hrs ago1766577435IN
0x5E305dcB...db42776d2
0 ETH0.000001960.0012
Solve By Zap198043642025-12-24 3:32:5539 hrs ago1766547175IN
0x5E305dcB...db42776d2
0 ETH0.000001350.00000026
Unstake And With...196559342025-12-22 10:19:053 days ago1766398745IN
0x5E305dcB...db42776d2
0 ETH0.000001350.00000026
Unstake And With...196512132025-12-22 9:00:243 days ago1766394024IN
0x5E305dcB...db42776d2
0 ETH0.000001350.00000026
Unstake And With...196501962025-12-22 8:43:273 days ago1766393007IN
0x5E305dcB...db42776d2
0 ETH0.000006650.01011
Unstake And With...191953372025-12-17 2:22:288 days ago1765938148IN
0x5E305dcB...db42776d2
0 ETH0.000001350.00000026
Unstake And With...191046722025-12-16 1:11:239 days ago1765847483IN
0x5E305dcB...db42776d2
0 ETH0.000001350.00000026

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
199419772025-12-25 17:46:281 hr ago1766684788
0x5E305dcB...db42776d2
0 ETH
199419772025-12-25 17:46:281 hr ago1766684788
0x5E305dcB...db42776d2
0 ETH
199419772025-12-25 17:46:281 hr ago1766684788
0x5E305dcB...db42776d2
0 ETH
199278352025-12-25 13:50:465 hrs ago1766670646
0x5E305dcB...db42776d2
0 ETH
199278352025-12-25 13:50:465 hrs ago1766670646
0x5E305dcB...db42776d2
0 ETH
199278352025-12-25 13:50:465 hrs ago1766670646
0x5E305dcB...db42776d2
0 ETH
199258352025-12-25 13:17:265 hrs ago1766668646
0x5E305dcB...db42776d2
0 ETH
199258352025-12-25 13:17:265 hrs ago1766668646
0x5E305dcB...db42776d2
0 ETH
199258352025-12-25 13:17:265 hrs ago1766668646
0x5E305dcB...db42776d2
0 ETH
199258352025-12-25 13:17:265 hrs ago1766668646
0x5E305dcB...db42776d2
0 ETH
199117552025-12-25 9:22:469 hrs ago1766654566
0x5E305dcB...db42776d2
0 ETH
199117552025-12-25 9:22:469 hrs ago1766654566
0x5E305dcB...db42776d2
0 ETH
199117552025-12-25 9:22:469 hrs ago1766654566
0x5E305dcB...db42776d2
0 ETH
199100602025-12-25 8:54:3110 hrs ago1766652871
0x5E305dcB...db42776d2
0 ETH
199100602025-12-25 8:54:3110 hrs ago1766652871
0x5E305dcB...db42776d2
0 ETH
199100602025-12-25 8:54:3110 hrs ago1766652871
0x5E305dcB...db42776d2
0 ETH
198441972025-12-24 14:36:4828 hrs ago1766587008
0x5E305dcB...db42776d2
0 ETH
198441972025-12-24 14:36:4828 hrs ago1766587008
0x5E305dcB...db42776d2
0 ETH
198441972025-12-24 14:36:4828 hrs ago1766587008
0x5E305dcB...db42776d2
0 ETH
198410062025-12-24 13:43:3729 hrs ago1766583817
0x5E305dcB...db42776d2
0 ETH
198410062025-12-24 13:43:3729 hrs ago1766583817
0x5E305dcB...db42776d2
0 ETH
198410062025-12-24 13:43:3729 hrs ago1766583817
0x5E305dcB...db42776d2
0 ETH
198409272025-12-24 13:42:1829 hrs ago1766583738
0x5E305dcB...db42776d2
0 ETH
198409272025-12-24 13:42:1829 hrs ago1766583738
0x5E305dcB...db42776d2
0 ETH
198409272025-12-24 13:42:1829 hrs ago1766583738
0x5E305dcB...db42776d2
0 ETH
View All Internal Transactions

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
WithdrawZapTeller

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
Yes with 200 runs

Other Settings:
shanghai EvmVersion
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Ownable2StepWTR } from "./Ownable2StepWTR.sol";
import { AtomicQueue, AtomicRequest } from "./../atomic-queue/AtomicQueue.sol";
import { AtomicSolverV4 } from "./../atomic-queue/AtomicSolverV4.sol";
import { TellerWithMultiAssetSupport } from "./../base/Roles/TellerWithMultiAssetSupport.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { ReentrancyGuard } from "@solmate/utils/ReentrancyGuard.sol";

/// @notice Stores zap request information needed to fulfill a users atomic request.
/// @param deadline unix timestamp for when request is no longer valid
/// @param creationTime timestamp when request was created
/// @param offerAmount the amount of `offer` asset the user wants converted to `want` asset
/// @param minimumAssetsOut the minimum amount of want assets to receive
/// @param user The address of the zapper contract (this contract)
/// @param sender The original address that initiated the request
/// @param offer The address of the offer token
/// @param want The address of the want token
struct ZapAtomicRequest {
    uint64 deadline; // deadline to fulfill request
    uint64 creationTime; // timestamp when request was created
    uint96 offerAmount; // The amount of offer asset the zapper wants to sell.
    uint256 minimumAssetsOut; // The minimum amount of want assets to receive
    address user; // The address of the zapper contract
    address sender; // The original sender who initiated the request
    address offer; // The address of the offer token
    address want; // The address of the want token
}

/// @title WithdrawZapTeller
/// @author SuperFi Labs
/// @notice A teller that helps convert sSuperUSD to base assets by bundling instantWithdraw and updateAtomicRequest operations.
contract WithdrawZapTeller is Ownable2StepWTR, ReentrancyGuard {
    using EnumerableSet for EnumerableSet.Bytes32Set;

    /***************************************
    CONSTANTS
    ***************************************/

    /// @notice The address of the superUSD AtomicQueue contract
    AtomicQueue public immutable superUSDAtomicQueue;
    
    /// @notice The address of the sSuperUSD AtomicQueue contract
    AtomicQueue public immutable sSuperUSDAtomicQueue;

    /// @notice The address of the SuperUSD token contract
    address public immutable superUSD;

    /// @notice The address of the sSuperUSD token contract
    address public immutable sSuperUSD;

    /// @notice The address of the SuperUSD teller contract
    address public immutable superUSDTeller;

    /// @notice The address of the sSuperUSD teller contract
    address public immutable sSuperUSDTeller;

    /// @notice The address of the AtomicSolverV4 contract
    AtomicSolverV4 public immutable superUSDSolver;

    /***************************************
    STORAGE
    ***************************************/

    /// @notice The set of zap request Ids currently in the zapper.
    /// @dev Requests are removed when solve or cancel is called.
    EnumerableSet.Bytes32Set internal _existingZapWithdrawRequests;

    /// @notice Mapping of zap request Ids to ZapAtomicRequests.
    /// @dev Requests won't be removed when solve or cancel is called.
    mapping(bytes32 => ZapAtomicRequest) internal zapWithdraws;

    /***************************************
    ERRORS
    ***************************************/

    /// @notice Thrown when inputting an invalid address
    error InvalidAddress();

    /// @notice Thrown when a zap request is not found
    error ZapRequestNotFound();

    /// @notice Thrown when user tries to cancel a request they didn't create
    error UnauthorizedZapCancellation();

    /// @notice Thrown when the deadline for a zap request is in the past
    error InvalidDeadline();

    /// @notice Thrown when no tokens are received after solving a zap request
    error NoTokensReceived();

    /***************************************
    EVENTS
    ***************************************/

    /// @notice Emitted when a zap withdraw request is created
    /// @param requestId The ID of the zap request
    /// @param sender The address that initiated the request
    /// @param sSuperUSDAmount The amount of sSuperUSD unstaked
    /// @param superUSDAmount The amount of superUSD received
    /// @param offer The offer token address
    /// @param want The want token address
    /// @param deadline The deadline for the request
    event ZapWithdrawRequestCreated(
        bytes32 indexed requestId,
        address indexed sender,
        uint256 sSuperUSDAmount,
        uint256 superUSDAmount,
        address offer,
        address want,
        uint64 deadline
    );

    /// @notice Emitted when a zap withdraw request is cancelled
    /// @param requestId The ID of the cancelled zap request
    /// @param sender The address that initiated the request
    /// @param offerAmount The amount of offer tokens returned
    /// @param offer The offer token address
    /// @param want The want token address
    event ZapWithdrawRequestCancelled(
        bytes32 indexed requestId,
        address indexed sender,
        uint256 offerAmount,
        address offer,
        address want
    );

    /// @notice Emitted when a zap withdraw request is solved
    /// @param requestId The ID of the solved zap request
    /// @param sender The address that initiated the request
    /// @param offerAmount The amount of offer tokens spent
    /// @param wantAmount The amount of want tokens received
    /// @param offer The offer token address
    /// @param want The want token address
    event ZapWithdrawRequestSolved(
        bytes32 indexed requestId,
        address indexed sender,
        uint256 offerAmount,
        uint256 wantAmount,
        address offer,
        address want
    );

    /***************************************
    CONSTRUCTOR
    ***************************************/

    /// @notice Constructs the WithdrawZapTeller contract.
    /// @param initialOwner The initial owner of the contract.
    /// @param superUSD_ The address of the superUSD token contract.
    /// @param sSuperUSD_ The address of the sSuperUSD token contract.
    /// @param superUSDAtomicQueue_ The address of the SuperUSD AtomicQueue contract.
    /// @param sSuperUSDAtomicQueue_ The address of the sSuperUSD AtomicQueue contract.
    /// @param sSuperUSDTeller_ The address of the sSuperUSD teller contract.
    /// @param superUSDTeller_ The address of the SuperUSD teller contract.
    /// @param atomicSolver_ The address of the AtomicSolverV4 contract.
    constructor(
        address initialOwner,
        address superUSD_,
        address sSuperUSD_,
        address superUSDAtomicQueue_,
        address sSuperUSDAtomicQueue_,
        address superUSDTeller_,
        address sSuperUSDTeller_,
        address atomicSolver_
    ) Ownable2StepWTR(initialOwner) {
        // checks
        if(
            (initialOwner == address(0)) ||
            (superUSD_ == address(0)) ||
            (sSuperUSD_ == address(0)) ||
            (superUSDAtomicQueue_ == address(0)) ||
            (sSuperUSDAtomicQueue_ == address(0)) ||
            (sSuperUSDTeller_ == address(0)) ||
            (superUSDTeller_ == address(0)) ||
            (atomicSolver_ == address(0))
        ) revert InvalidAddress();
        // set
        superUSDAtomicQueue = AtomicQueue(superUSDAtomicQueue_);
        sSuperUSDAtomicQueue = AtomicQueue(sSuperUSDAtomicQueue_);
        superUSD = superUSD_;
        sSuperUSD = sSuperUSD_;
        superUSDTeller = superUSDTeller_;
        sSuperUSDTeller = sSuperUSDTeller_;
        superUSDSolver = AtomicSolverV4(atomicSolver_);
        // pre approve sSuperUSD to sSuperUSD atomic queue
        SafeERC20.forceApprove(IERC20(sSuperUSD_), address(sSuperUSDAtomicQueue), type(uint256).max);
        // pre approve superUSD to superUSD atomic queue
        SafeERC20.forceApprove(IERC20(superUSD_), address(superUSDAtomicQueue), type(uint256).max);
        // pre approve superUSD to sSuperUSD vault (needed for deposits via teller)
        SafeERC20.forceApprove(IERC20(superUSD_), sSuperUSD, type(uint256).max);
    }

    /***************************************
    VIEW FUNCTIONS
    ***************************************/

    /// @notice Get all existing zap withdraw request Ids currently in the zapper.
    /// @dev Includes requests that are not mature, matured, and expired. But does not include requests that have been solved.
    /// @return requestIds The request Ids.
    function getExistingZapWithdrawRequestIds() public view returns (bytes32[] memory) {
        return _existingZapWithdrawRequests.values();
    }

    /// @notice Get all existing zap withdraw requests.
    /// @dev Includes requests that are not mature, matured, and expired. But does not include requests that have been solved.
    function getExistingZapWithdrawRequests()
        external
        view
        returns (bytes32[] memory requestIds, ZapAtomicRequest[] memory requests)
    {
        requestIds = getExistingZapWithdrawRequestIds();
        uint256 requestsLength = requestIds.length;
        requests = new ZapAtomicRequest[](requestsLength);
        for (uint256 i = 0; i < requestsLength; ) {
            requests[i] = zapWithdraws[requestIds[i]];
            unchecked { ++i; }
        }
    }

    /// @notice Get all existing zap withdraw requests by sender.
    /// @dev Includes requests that are not mature, matured, and expired. But does not include requests that have been solved.
    /// @param sender The address of the sender.
    /// @return requestIds The request Ids.
    /// @return requests The requests.
    function getZapExistingWithdrawRequestsByUser(address sender)
        external
        view
        returns (bytes32[] memory requestIds, ZapAtomicRequest[] memory requests)
    {
        bytes32[] memory allExistingZapWithdrawRequestIds = _existingZapWithdrawRequests.values();
        uint256 allExistingZapWithdrawRequestsLength = allExistingZapWithdrawRequestIds.length;

        // Create arrays with maximum possible size
        requestIds = new bytes32[](allExistingZapWithdrawRequestsLength);
        requests = new ZapAtomicRequest[](allExistingZapWithdrawRequestsLength);

        // Single pass: populate arrays conditionally
        uint256 count = 0;
        for (uint256 i = 0; i < allExistingZapWithdrawRequestsLength; ) {
            bytes32 requestId = allExistingZapWithdrawRequestIds[i];
            ZapAtomicRequest memory request = zapWithdraws[requestId];
            if (request.sender == sender) {
                requestIds[count] = requestId;
                requests[count] = request;
                unchecked { ++count; }
            }
            unchecked { ++i; }
        }

        // Trim arrays to correct length using assembly
        // solhint-disable-next-line no-inline-assembly
        assembly {
            mstore(requestIds, count)
            mstore(requests, count)
        }
    }

    /// @notice Get a zap withdraw request by request Id.
    /// @dev Does verify nonce is non-zero.
    /// @param requestId The request Id.
    /// @return request The request.
    function getZapAtomicRequestById(bytes32 requestId) public view returns (ZapAtomicRequest memory) {
        return zapWithdraws[requestId];
    }

    /***************************************
    WITHDRAW FUNCTIONS
    ***************************************/

    /// @notice Unstakes sSuperUSD and withdraws to a base asset in a single transaction.
    /// @param sSuperUSDAmount The amount of sSuperUSD to unstake.
    /// @param wantAsset The base asset to withdraw to.
    /// @param minimumAssetsOut The minimum amount of base assets to receive.
    /// @param deadline The deadline for the atomic request.
    /// @return requestId The ID of the zap atomic request created.
    function unstakeAndWithdraw(
        uint256 sSuperUSDAmount,
        address wantAsset,
        uint256 minimumAssetsOut,
        uint64 deadline
    ) public nonReentrant returns (bytes32 requestId) {
        // Add deadline validation
        if (deadline <= block.timestamp) revert InvalidDeadline();
        
        // Add wantAsset validation
        if (wantAsset == address(0)) revert InvalidAddress();

        // transfer sSuperUSD from user to this contract
        SafeERC20.safeTransferFrom(IERC20(sSuperUSD), msg.sender, address(this), sSuperUSDAmount);

        // call instantWithdraw on sSuperUSD to get superUSD
        uint256 superUSDAmount = sSuperUSDAtomicQueue.instantWithdraw(
            ERC20(sSuperUSD),
            ERC20(superUSD),
            sSuperUSDAmount,
            0,
            TellerWithMultiAssetSupport(sSuperUSDTeller)
        );

        // create zap atomic request to convert superUSD to base asset
        ZapAtomicRequest memory zapRequest = ZapAtomicRequest({
            deadline: deadline,
            creationTime: uint64(block.timestamp),
            offerAmount: uint96(superUSDAmount),
            minimumAssetsOut: minimumAssetsOut,
            user: address(this), // the zapper contract is the user for the atomic request
            sender: msg.sender, // the original sender who initiated the request
            offer: superUSD,
            want: wantAsset
        });

        // store the zap request
        requestId = keccak256(abi.encode(zapRequest));
        _existingZapWithdrawRequests.add(requestId);
        zapWithdraws[requestId] = zapRequest;

        // create atomic request to convert superUSD to base asset
        AtomicRequest memory userRequest = AtomicRequest({
            deadline: deadline,
            creationTime: uint64(block.timestamp),
            offerAmount: uint96(superUSDAmount),
            user: address(this), // the zapper contract is the user for the atomic request
            offer: superUSD,
            want: wantAsset
        });

        // call updateAtomicRequest to create the withdrawal request
        superUSDAtomicQueue.updateAtomicRequest(userRequest);

        // emit event for zap request creation
        emit ZapWithdrawRequestCreated(
            requestId,
            msg.sender,
            sSuperUSDAmount,
            superUSDAmount,
            superUSD,
            wantAsset,
            deadline
        );
    }

    /// @notice Allows a sender to cancel their zap atomic request.
    /// @param zapRequest The zap request to cancel.
    function cancelByZap(ZapAtomicRequest calldata zapRequest) external nonReentrant {
        if (zapRequest.sender != msg.sender) revert UnauthorizedZapCancellation();

        bytes32 requestId = keccak256(abi.encode(zapRequest));
        if (!_existingZapWithdrawRequests.contains(requestId)) revert ZapRequestNotFound();

        // Remove from zap storage
        _existingZapWithdrawRequests.remove(requestId);

        // Create corresponding AtomicRequest to cancel in the queue
        AtomicRequest memory atomicRequest = AtomicRequest({
            deadline: zapRequest.deadline,
            creationTime: zapRequest.creationTime,
            offerAmount: zapRequest.offerAmount,
            user: zapRequest.user,
            offer: zapRequest.offer,
            want: zapRequest.want
        });

        // Cancel the atomic request in the queue
        superUSDAtomicQueue.cancelAtomicRequest(atomicRequest);

        uint256 balanceBefore = IERC20(sSuperUSD).balanceOf(address(this));

        // Stake the superUSD to get sSuperUSD
        TellerWithMultiAssetSupport(sSuperUSDTeller).deposit(ERC20(zapRequest.offer), zapRequest.offerAmount, 0);

        uint256 sSuperUSDAmount = IERC20(sSuperUSD).balanceOf(address(this)) - balanceBefore;

        // Transfer sSuperUSD back to the original sender
        SafeERC20.safeTransfer(IERC20(sSuperUSD), zapRequest.sender, sSuperUSDAmount);

        // emit event for zap request cancellation
        emit ZapWithdrawRequestCancelled(
            requestId,
            zapRequest.sender,
            sSuperUSDAmount,
            zapRequest.offer,
            zapRequest.want
        );
    }

    /// @notice Allows the admin to cancel multiple zap withdraw requests.
    /// @dev Callable by owner only.
    /// @param zapRequests The array of zap requests to cancel.
    function cancelZapAtomicRequestByAdmin(ZapAtomicRequest[] calldata zapRequests) external onlyOwner nonReentrant {
        for (uint256 i = 0; i < zapRequests.length; ++i) {
            ZapAtomicRequest calldata zapRequest = zapRequests[i];
            bytes32 requestId = keccak256(abi.encode(zapRequest));
            if (!_existingZapWithdrawRequests.contains(requestId)) revert ZapRequestNotFound();

            // Remove from zap storage
            _existingZapWithdrawRequests.remove(requestId);

            // Create corresponding AtomicRequest to cancel in the queue
            AtomicRequest memory atomicRequest = AtomicRequest({
                deadline: zapRequest.deadline,
                creationTime: zapRequest.creationTime,
                offerAmount: zapRequest.offerAmount,
                user: zapRequest.user,
                offer: zapRequest.offer,
                want: zapRequest.want
            });

            // Cancel the atomic request in the queue
            superUSDAtomicQueue.cancelAtomicRequest(atomicRequest);

            uint256 balanceBefore = IERC20(sSuperUSD).balanceOf(address(this));

            // Stake the superUSD to get sSuperUSD
            TellerWithMultiAssetSupport(sSuperUSDTeller).deposit(ERC20(zapRequest.offer), zapRequest.offerAmount, 0);

            uint256 sSuperUSDAmount = IERC20(sSuperUSD).balanceOf(address(this)) - balanceBefore;

            // Transfer superUSD back to the original sender
            SafeERC20.safeTransfer(IERC20(sSuperUSD), zapRequest.sender, sSuperUSDAmount);

            // emit event for each cancelled zap request
            emit ZapWithdrawRequestCancelled(
                requestId,
                zapRequest.sender,
                sSuperUSDAmount,
                zapRequest.offer,
                zapRequest.want
            );
        }
    }

    /// @notice Called by solvers to exchange offer asset for want asset for zap requests.
    /// @param zapRequest The zap atomic request to solve.
    function solveByZap(ZapAtomicRequest calldata zapRequest) external nonReentrant {
        bytes32 requestId = keccak256(abi.encode(zapRequest));
        if (!_existingZapWithdrawRequests.contains(requestId)) revert ZapRequestNotFound();

        // Remove from zap storage
        _existingZapWithdrawRequests.remove(requestId);

        // Create corresponding AtomicRequest to solve in the queue
        AtomicRequest memory atomicRequest = AtomicRequest({
            deadline: zapRequest.deadline,
            creationTime: zapRequest.creationTime,
            offerAmount: zapRequest.offerAmount,
            user: zapRequest.user,
            offer: zapRequest.offer,
            want: zapRequest.want
        });

        // Record balance before redeemSolve
        uint256 balanceBefore = IERC20(zapRequest.want).balanceOf(address(this));

        // Call redeemSolve instead of queue.solve
        superUSDSolver.redeemSolve(
            superUSDAtomicQueue,
            zapRequest.minimumAssetsOut,
            type(uint256).max, // maxAssets - allow unlimited since this is solving our own request
            TellerWithMultiAssetSupport(superUSDTeller),
            atomicRequest
        );

        // Get the amount of want tokens received (difference from before)
        uint256 balanceAfter = IERC20(zapRequest.want).balanceOf(address(this));
        uint256 wantAmount = balanceAfter - balanceBefore;

        if (wantAmount == 0) revert NoTokensReceived();

        // Transfer want assets from this contract to the original sender
        SafeERC20.safeTransfer(IERC20(zapRequest.want), zapRequest.sender, wantAmount);

        // emit event for zap request solution
        emit ZapWithdrawRequestSolved(
            requestId,
            zapRequest.sender,
            zapRequest.offerAmount,
            wantAmount,
            zapRequest.offer,
            zapRequest.want
        );
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";


/// @title Ownable2StepWTR
/// @author SuperFi Labs
/// @notice An extention of Ownable2Step that allows the contract owner to rescue tokens that may have been transferred into this contract.
contract Ownable2StepWTR is Ownable2Step {

    /***************************************
    ERRORS
    ***************************************/

    /// @notice Thrown when a token transfer fails
    error TransferFailed();

    /***************************************
    CONSTRUCTOR
    ***************************************/

    /// @notice Constructs the Ownable2StepWTR contract.
    /// @param initialOwner The initial owner of the contract.
    constructor(address initialOwner) Ownable(initialOwner){}

    /***************************************
    RESCUE TOKEN FUNCTION
    ***************************************/

    struct RescueTokenParam {
        address token;
        uint256 amount; // For ETH and ERC20s, the amount to transfer. For ERC721s, the tokenId
        address receiver;
    }

    /// @notice Rescues tokens that may have been transferred into this contract.
    /// Supports the gas token, ERC20s, and ERC721s.
    /// Can only be called by the contract owner.
    /// @param params The tokens to rescue.
    function rescueTokens(RescueTokenParam[] calldata params) external onlyOwner {
        for(uint256 i = 0; i < params.length; ++i) {
            address token = params[i].token;
            // if transferring the gas token
            if(token == address(0)) {
                Address.sendValue(payable(params[i].receiver), params[i].amount);
            }
            // if transferring an erc20 or erc721
            else {
                _transferToken(token, params[i].amount, params[i].receiver);
            }
        }
    }

    /***************************************
    HELPER FUNCTIONS
    ***************************************/

    /// @notice Transfers a token. Supports both ERC20 and ERC721.
    /// @param token The address of the token contract.
    /// @param amountOrID For ERC20s, the amount to transfer. For ERC721s, the tokenId.
    /// @param receiver The receiver of tokens.
    function _transferToken(address token, uint256 amountOrID, address receiver) internal {
        // try transfer()
        bool success = _callOptionalReturnBool(token, abi.encodeCall(IERC20.transfer, (receiver, amountOrID)));
        // return if transfer() was successful
        if(success) return;
        // try transferFrom()
        success = _callOptionalReturnBool(token, abi.encodeCall(IERC20.transferFrom, (address(this), receiver, amountOrID)));
        // return if transferFrom() was successful
        if(success) return;
        // revert
        revert TransferFailed();
    }

    /// @notice 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).
    /// This is a variant of _callOptionalReturn that silently catches all reverts and returns a bool instead.
    /// @param token The token targeted by the call.
    /// @param data The call data (encoded using abi.encode or one of its variants).
    function _callOptionalReturnBool(address 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 ? token.code.length > 0 : returnValue == 1);
    }
}

// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
import {ERC20} from "@solmate/tokens/ERC20.sol";
import {ReentrancyGuard} from "@solmate/utils/ReentrancyGuard.sol";
import {IAtomicSolver} from "./IAtomicSolver.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Auth, Authority} from "@solmate/auth/Auth.sol";
import {TellerWithMultiAssetSupport} from "src/base/Roles/TellerWithMultiAssetSupport.sol";
import {BoringVault} from "src/base/BoringVault.sol";
import {AccountantWithRateProviders} from "src/base/Roles/AccountantWithRateProviders.sol";
/**
 * @notice Stores request information needed to fulfill a users atomic request.
 * @param deadline unix timestamp for when request is no longer valid
 * @param creationTime timestamp when request was created
 * @param offerAmount the amount of `offer` asset the user wants converted to `want` asset
 * @param user The address of the user making the request
 * @param offer The address of the offer token
 * @param want The address of the want token
 */
struct AtomicRequest {
    uint64 deadline; // deadline to fulfill request
    uint64 creationTime; // timestamp when request was created
    uint96 offerAmount; // The amount of offer asset the user wants to sell.
    address user; // The address of the user making the request
    address offer; // The address of the offer token
    address want; // The address of the want token
}

contract AtomicQueue is ReentrancyGuard, Auth {
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using SafeTransferLib for ERC20;
    using FixedPointMathLib for uint256;

    // ========================================= GLOBAL STATE =========================================
    /**
     * @notice The set of request Ids currently in the queue.
     * @dev Requests are removed when solve or cancel is called.
     */
    EnumerableSet.Bytes32Set internal _existingWithdrawRequests;

    /**
     * @notice The maturity time of the atomic request.
     */
    uint256 public maturityTime = 1 days;

    /**
     * @notice Mapping of request Ids to AtomicRequests.
     * @dev Requests won't be removed when solve or cancel is called.
     */
    mapping(bytes32 => AtomicRequest) internal onChainWithdraws;

    /**
     * @notice This mapping tracks the total amount of 'offer' tokens in progress for withdrawal requests per want token.
     * @dev It is incremented when a new request is submitted and decremented when the request is fulfilled or cancelled.
     */
    mapping(address => mapping(address => uint256)) public withdrawInProgressAmount;

    /**
     * @notice Mapping to track whitelisted addresses, which can be solved quickly.
     */
    mapping(address => bool) public whitelist;

    /**
     * @notice The accountant contract to use for withdrawal
     */
    AccountantWithRateProviders public immutable accountant;

    /**
     * @notice The divisor used to reduce maturity time for whitelisted users.
     */
    uint256 public whitelistMaturityDivisor = 10;

    /**
     * @notice The discount(redemption fee) in parts-per-million (0.05% => 500)
     */
    uint256 public discount = 500; // 0.05% (ppm)

    /**
     * @notice Denominator for discount calculations (parts-per-million)
     */
    uint256 private constant DISCOUNT_DENOMINATOR = 1e6;

    //============================== ERRORS ===============================

    error AtomicQueue__BadWhitelistDivisor();
    error AtomicQueue__BadDiscount();
    error AtomicQueue__RemovedRequest();
    error AtomicQueue__DuplicateRequest();
    error AtomicQueue__OfferAmountIsZero();
    error AtomicQueue__UserAddressIsZero();
    error AtomicQueue__OfferAddressIsZero();
    error AtomicQueue__WantAddressIsZero();
    error AtomicQueue__InsufficientBalance();
    error AtomicQueue__DeadlineExpired();
    error AtomicQueue__RequestAccountantOfferMismatch(address offer, address vault);
    error AtomicQueue__BadUser();
    error AtomicQueue__BoringVaultTellerMismatch(address vault, address teller);
    error AtomicQueue__ZeroOfferAmount(address user);
    error AtomicQueue__InsufficientVaultLiquidity(uint256 required, uint256 available);
    error AtomicQueue__RequestNotMature(address user);
    error AtomicQueue__MinimumAssetsNotMet();
    error AtomicQueue__InstantWithdrawShortfall(uint256 expected, uint256 actual);
    error AtomicQueue__InsufficientBalanceInUserWallet(address user, uint256 required, uint256 available);
    error AtomicQueue__UnauthorizedSolver(address caller);
    //============================== EVENTS ===============================
    /**
     * @notice Emitted when `setMaturityTime` is called.
     */
    event MaturityTimeUpdated(uint256 oldMaturityTime, uint256 newMaturityTime);

    /**
     * @notice Emitted when `updateAtomicRequest` is called.
     */
    event AtomicRequestUpdated(
        bytes32 indexed requestId,
        address indexed user,
        address offerToken,
        address indexed wantToken,
        uint256 amount,
        uint256 deadline,
        uint256 timestamp
    );

    /**
     * @notice Emitted when `solve` exchanges a users offer asset for their want asset.
     */
    event AtomicRequestFulfilled(
        bytes32 indexed requestId,
        address indexed user,
        address offerToken,
        address indexed wantToken,
        uint256 offerAmountSpent,
        uint256 wantAmountReceived,
        uint256 timestamp
    );

    /**
     * @notice Emitted when `cancelAtomicRequest` is called.
     */
    event AtomicRequestCancelled(
        bytes32 indexed requestId,
        address indexed user,
        address offerToken,
        address indexed wantToken,
        uint256 amount,
        uint256 deadline,
        uint256 timestamp
    );

    /**
     * @notice Emitted when `instantWithdraw` is called.
     */
    event InstantWithdraw(
        address indexed user,
        address indexed offerToken,
        address indexed wantToken,
        uint256 offerAmount,
        uint256 wantAmount,
        uint256 timestamp
    );

    /**
     * @notice Emitted when `addToWhitelist` is called.
     */
    event WhitelistAdded(address indexed user);

    /**
     * @notice Emitted when `removeFromWhitelist` is called.
     */
    event WhitelistRemoved(address indexed user);

    /**
     * @notice Emitted when `updateWhitelistMaturityDivisor` is called.
     */
    event WhitelistMaturityDivisorUpdated(uint256 newDivisor);

    /**
     * @notice Emitted when `setDiscount` is called.
     */
    event DiscountUpdated(uint256 newDiscount);

    /**
     * @notice Emitted when `setSolver` is called.
     */
    event SolverUpdated(address newSolver);

    //============================== VARIABLES ===============================
    /**
     * @notice The solver contract to use for solving
     */
    IAtomicSolver public solver;

    /**
     * @notice Constructor
     * @param _owner The owner of the contract
     * @param _authority The authority of the contract
     * @param _accountant The accountant contract to use for withdrawal
     * @param _solver The solver contract to use for solving
     */
    constructor(address _owner, Authority _authority, address _accountant, address _solver) Auth(_owner, _authority) {
        accountant = AccountantWithRateProviders(_accountant);
        solver = IAtomicSolver(_solver);
    }

    //============================== ADMIN FUNCTIONS ===============================

    /**
     * @notice Allows the owner to update the maturity time
     * @param newMaturityTime The new maturity time in seconds
     */
    function setMaturityTime(uint256 newMaturityTime) external requiresAuth {
        uint256 oldMaturityTime = maturityTime;
        maturityTime = newMaturityTime;
        emit MaturityTimeUpdated(oldMaturityTime, newMaturityTime);
    }

    /**
     * @notice Allows the owner to update the discount
     * @param newDiscount The new discount in parts-per-million (500 = 0.05%)
     */
    function setDiscount(uint256 newDiscount) external requiresAuth {
        if (newDiscount >= DISCOUNT_DENOMINATOR) revert AtomicQueue__BadDiscount();
        discount = newDiscount;
        emit DiscountUpdated(newDiscount);
    }

    /**
     * @notice Add an address to the whitelist.
     * @dev Callable by MULTISIG_ROLE.
     * @param user The address to add to the whitelist.
     */
    function addToWhitelist(address user) external requiresAuth {
        if (user == address(0)) revert AtomicQueue__UserAddressIsZero();
        whitelist[user] = true;
        emit WhitelistAdded(user);
    }

    /**
     * @notice Remove an address from the whitelist.
     * @dev Callable by MULTISIG_ROLE.
     * @param user The address to remove from the whitelist.
     */
    function removeFromWhitelist(address user) external requiresAuth {
        if (user == address(0)) revert AtomicQueue__UserAddressIsZero();
        whitelist[user] = false;
        emit WhitelistRemoved(user);
    }

    /**
     * @notice Update the whitelist maturity divisor.
     * @dev Callable by MULTISIG_ROLE.
     * @param newDivisor The new divisor value.
     */
    function updateWhitelistMaturityDivisor(uint256 newDivisor) external requiresAuth {
        if (newDivisor == 0) revert AtomicQueue__BadWhitelistDivisor();
        whitelistMaturityDivisor = newDivisor;
        emit WhitelistMaturityDivisorUpdated(newDivisor);
    }

    /**
     * @notice Allows the owner to update the solver contract
     * @dev Callable by MULTISIG_ROLE.
     * @param newSolver The new solver contract address.
     */
    function setSolver(address newSolver) external requiresAuth {
        solver = IAtomicSolver(newSolver);
        emit SolverUpdated(newSolver);
    }

    /**
     * @notice Allows the admin to cancel multiple withdraw requests.
     * @dev Callable by MULTISIG_ROLE.
     * @param userRequests The array of user requests to cancel.
     */
    function cancelAtomicRequestByAdmin(AtomicRequest[] calldata userRequests) external requiresAuth {
        for (uint256 i = 0; i < userRequests.length; ++i) {
            AtomicRequest calldata userRequest = userRequests[i];
            bytes32 requestId = keccak256(abi.encode(userRequest));
            if (!_existingWithdrawRequests.contains(requestId)) revert AtomicQueue__RemovedRequest();
            withdrawInProgressAmount[userRequest.offer][userRequest.want] -= userRequest.offerAmount;

            _existingWithdrawRequests.remove(requestId);

            // Transfer offer shares from solver contract to user
            IAtomicSolver(solver).approveOfferForQueue(address(this), userRequest);
            ERC20(userRequest.offer).safeTransferFrom(address(solver), userRequest.user, userRequest.offerAmount);

            emit AtomicRequestCancelled(
                requestId,
                userRequest.user,
                userRequest.offer,
                userRequest.want,
                userRequest.offerAmount,
                userRequest.deadline,
                block.timestamp
            );
        }
    }

    //============================== VIEW FUNCTIONS ===============================
    /**
     * @notice Get the total amount of 'offer' tokens in progress for withdrawal requests for a specific want token.
     * @param offer The address of the offer token.
     * @param want The address of the want token.
     * @return The total amount of 'offer' tokens in progress for withdrawal requests for the specified want token.
     */
    function getTotalWithdrawInProgressAmount(address offer, address want) external view returns (uint256) {
        return withdrawInProgressAmount[offer][want];
    }

    /**
     * @notice Get all existing withdraw request Ids currently in the queue.
     * @dev Includes requests that are not mature, matured, and expired. But does not include requests that have been solved.
     * @return requestIds The request Ids.
     */
    function getExistingWithdrawRequestIds() public view returns (bytes32[] memory) {
        return _existingWithdrawRequests.values();
    }

    /**
     * @notice Get all existing withdraw requests.
     * @dev Includes requests that are not mature, matured, and expired. But does not include requests that have been solved.
     */
    function getExistingWithdrawRequests()
        external
        view
        returns (bytes32[] memory requestIds, AtomicRequest[] memory requests)
    {
        requestIds = getExistingWithdrawRequestIds();
        uint256 requestsLength = requestIds.length;
        requests = new AtomicRequest[](requestsLength);
        for (uint256 i = 0; i < requestsLength; ) {
            requests[i] = onChainWithdraws[requestIds[i]];
            unchecked { ++i; }
        }
    }

    /**
     * @notice Get all existing withdraw requests by user.
     * @dev Includes requests that are not mature, matured, and expired. But does not include requests that have been solved.
     * @param user The address of the user.
     * @return requestIds The request Ids.
     * @return requests The requests.
     */
    function getExistingWithdrawRequestsByUser(address user)
        external
        view
        returns (bytes32[] memory requestIds, AtomicRequest[] memory requests)
    {
        bytes32[] memory allExistingWithdrawRequestIds = getExistingWithdrawRequestIds();
        uint256 allExistingWithdrawRequestsLength = allExistingWithdrawRequestIds.length;

        // First pass: count how many requests belong to this user
        uint256 userRequestCount = 0;
        for (uint256 i = 0; i < allExistingWithdrawRequestsLength; ) {
            if (onChainWithdraws[allExistingWithdrawRequestIds[i]].user == user) {
                userRequestCount++;
            }
            unchecked { ++i; }
        }

        // Initialize arrays with the correct size
        requestIds = new bytes32[](userRequestCount);
        requests = new AtomicRequest[](userRequestCount);

        // Second pass: populate the arrays with user's requests
        uint256 index = 0;
        for (uint256 i = 0; i < allExistingWithdrawRequestsLength; ) {
            bytes32 requestId = allExistingWithdrawRequestIds[i];
            AtomicRequest memory request = onChainWithdraws[requestId];
            if (request.user == user) {
                requestIds[index] = requestId;
                requests[index] = request;
                unchecked { ++index; }
            }
            unchecked { ++i; }
        }
    }

    /**
     * @notice Get a withdraw request by request Id.
     * @dev Does verify nonce is non-zero.
     * @param requestId The request Id.
     * @return request The request.
     */
    function getAtomicRequestById(bytes32 requestId) public view returns (AtomicRequest memory) {
        return onChainWithdraws[requestId];
    }

    /**
     * @notice Preview the amount of want assets that would be received for an atomic request.
     * @dev This is a view function that calculates the expected output without executing the transaction.
     * @param request The atomic request to preview.
     * @return wantAmountReceived The expected amount of want assets to be received.
     */
    function previewReceivedAmount(AtomicRequest calldata request) external view returns (uint256 wantAmountReceived) {
        // Basic validation (similar to checkAtomicRequestValid but without queue existence check)
        if (request.offerAmount == 0) revert AtomicQueue__OfferAmountIsZero();
        if (request.user == address(0)) revert AtomicQueue__UserAddressIsZero();
        if (request.offer == address(0)) revert AtomicQueue__OfferAddressIsZero();
        if (request.want == address(0)) revert AtomicQueue__WantAddressIsZero();
        if (block.timestamp > request.deadline) revert AtomicQueue__DeadlineExpired();

        // Get the offer token decimals
        ERC20 offer = ERC20(request.offer);
        uint8 offerDecimals = offer.decimals();

        // Get the rate and apply discount (same logic as in solve function)
        uint256 safeRate = accountant.getRateInQuoteSafe(ERC20(request.want));
        uint256 safeAtomicPriceWithDiscount = safeRate.mulDivDown(DISCOUNT_DENOMINATOR - discount, DISCOUNT_DENOMINATOR);

        // Calculate the want amount
        wantAmountReceived = _calculateAssetAmount(request.offerAmount, safeAtomicPriceWithDiscount, offerDecimals);
    }

    //============================== HELPER FUNCTIONS ===============================

    /**
     * @notice Helper function that validates a withdraw request.
     * @dev Reverts with specific error if the request is invalid.
     *      It is possible for a withdraw request to pass validation here, but solvers 
     *      may not be able to include the user in `solve` unless some other state is changed.
     * @param userRequest the full request struct to validate (should have correct .offer, .want, .user fields)
     */
    function checkAtomicRequestValid(AtomicRequest calldata userRequest)
        public
        view
    {
        bytes32 requestId = keccak256(abi.encode(userRequest));
        if (!_existingWithdrawRequests.contains(requestId)) revert AtomicQueue__RemovedRequest();

        address requestUser = userRequest.user;
        ERC20 offer = ERC20(userRequest.offer);

        // Validate offerAmount is nonzero.
        if (userRequest.offerAmount == 0) revert AtomicQueue__OfferAmountIsZero();
        // Validate user address is not zero.
        if (requestUser == address(0)) revert AtomicQueue__UserAddressIsZero();
        // Validate offer address is not zero.
        if (address(offer) == address(0)) revert AtomicQueue__OfferAddressIsZero();
        // Validate want address is not zero.
        if (userRequest.want == address(0)) revert AtomicQueue__WantAddressIsZero();

        // Validate deadline.
        if (block.timestamp > userRequest.deadline) revert AtomicQueue__DeadlineExpired();
    }

    //============================== USER FUNCTIONS ===============================

    /**
     * @notice Allows user to add their withdraw request.
     * @dev This function will completely ignore the provided atomic price and calculate a new one based off the
     *      the accountant rate in quote.
     * @param userRequest the users request
     */
    function updateAtomicRequest(AtomicRequest memory userRequest) external nonReentrant returns (bytes32) {
        if (userRequest.offer != address(accountant.vault())) revert AtomicQueue__RequestAccountantOfferMismatch(address(userRequest.offer), address(accountant.vault()));
        if (userRequest.user != msg.sender) revert AtomicQueue__BadUser();

        // try to gate rate from the accountant, should revert if the want token is not supported
        accountant.getRateInQuoteSafe(ERC20(userRequest.want));

        // Normalize creation time to prevent bypassing maturity
        userRequest.creationTime = uint64(block.timestamp);

        // Validate basic fields at submission time
        if (userRequest.offerAmount == 0) revert AtomicQueue__OfferAmountIsZero();
        if (userRequest.offer == address(0)) revert AtomicQueue__OfferAddressIsZero();
        if (userRequest.want == address(0)) revert AtomicQueue__WantAddressIsZero();
        if (userRequest.offerAmount > ERC20(userRequest.offer).balanceOf(userRequest.user)) revert AtomicQueue__InsufficientBalance();
        if (block.timestamp > userRequest.deadline) revert AtomicQueue__DeadlineExpired();

        bytes32 requestId = keccak256(abi.encode(userRequest));
        if (!_existingWithdrawRequests.add(requestId)) revert AtomicQueue__DuplicateRequest();

        onChainWithdraws[requestId] = userRequest;
        withdrawInProgressAmount[userRequest.offer][userRequest.want] += userRequest.offerAmount;

        // Transfer offer shares from user to solver contract
        ERC20(userRequest.offer).safeTransferFrom(userRequest.user, address(solver), userRequest.offerAmount);

        emit AtomicRequestUpdated(
            requestId,
            msg.sender,
            userRequest.offer,
            userRequest.want,
            userRequest.offerAmount,
            userRequest.deadline,
            block.timestamp
        );

        return requestId;
    }

    /**
     * @notice Allows user to cancel their withdraw request.
     * @param userRequest the user's request
     */
    function cancelAtomicRequest(AtomicRequest calldata userRequest) external {
        if (userRequest.user != msg.sender) revert AtomicQueue__BadUser();
        bytes32 requestId = keccak256(abi.encode(userRequest));
        if (!_existingWithdrawRequests.contains(requestId)) revert AtomicQueue__RemovedRequest();
        withdrawInProgressAmount[userRequest.offer][userRequest.want] -= userRequest.offerAmount;

        _existingWithdrawRequests.remove(requestId);

        // Transfer offer shares from solver contract to user
        IAtomicSolver(solver).approveOfferForQueue(address(this), userRequest);
        ERC20(userRequest.offer).safeTransferFrom(address(solver), userRequest.user, userRequest.offerAmount);

        emit AtomicRequestCancelled(
            requestId,
            userRequest.user,
            userRequest.offer,
            userRequest.want,
            userRequest.offerAmount,
            userRequest.deadline,
            block.timestamp
        );
    }

    /**
    * @notice Allows role granted users to instantly withdraw without going through the request queue.
    * @dev Callable by role granted users only.
    * @dev Ensures that the withdrawal amount plus pending queue withdrawals don't exceed vault liquidity.
    * @param offer The vault share token to burn
    * @param want The underlying asset to receive
    * @param offerAmount Amount of shares to withdraw
    * @param minimumAssetsOut Minimum amount of assets expected
    * @param teller The teller contract to use for withdrawal
    */
    function instantWithdraw(
        ERC20 offer,
        ERC20 want,
        uint256 offerAmount,
        uint256 minimumAssetsOut,
        TellerWithMultiAssetSupport teller
    ) external nonReentrant requiresAuth returns (uint256 assetsOut) {
        // Validate inputs
        if (offerAmount == 0) revert AtomicQueue__ZeroOfferAmount(msg.sender);
        
        // Get vault from accountant
        BoringVault vault = accountant.vault();
        if (address(offer) != address(vault)) revert AtomicQueue__RequestAccountantOfferMismatch(address(offer), address(vault));
        if (address(offer) != address(teller.vault())) revert AtomicQueue__BoringVaultTellerMismatch(address(offer), address(teller));
        uint256 ONE_SHARE = 10 ** offer.decimals();
        
        // Calculate assets that will be withdrawn
        assetsOut = offerAmount.mulDivDown(
            accountant.getRateInQuoteSafe(want), 
            ONE_SHARE
        );

        uint256 assetOutWithDiscount = assetsOut.mulDivDown(DISCOUNT_DENOMINATOR - discount, DISCOUNT_DENOMINATOR);
        
        // Calculate assets needed for pending withdrawal requests for this want token
        uint256 pendingWithdrawAssets = withdrawInProgressAmount[address(offer)][address(want)].mulDivDown(
            accountant.getRateInQuoteSafe(want),
            ONE_SHARE
        );
        
        // Check vault has enough liquidity
        uint256 vaultBalance = want.balanceOf(address(vault));
        uint256 totalRequired = assetOutWithDiscount + pendingWithdrawAssets;
        
        if (totalRequired > vaultBalance) {
            revert AtomicQueue__InsufficientVaultLiquidity(totalRequired, vaultBalance);
        }
        
        // Ensure minimum output is met
        if (assetOutWithDiscount < minimumAssetsOut) {
            revert AtomicQueue__MinimumAssetsNotMet();
        }
        
        // Transfer shares from user to this contract
        offer.safeTransferFrom(msg.sender, address(this), offerAmount);
        
        // Execute withdrawal through teller
        assetsOut = teller.bulkWithdraw(want, offerAmount, minimumAssetsOut, address(this));

        if (assetsOut < assetOutWithDiscount) {
            revert AtomicQueue__InstantWithdrawShortfall(assetOutWithDiscount, assetsOut);
        }

        uint256 excessAssets = assetsOut - assetOutWithDiscount;
        if (excessAssets > 0) {
            want.safeTransfer(address(vault), excessAssets);
        }

        want.safeTransfer(msg.sender, assetOutWithDiscount);
        assetsOut = assetOutWithDiscount;

        emit InstantWithdraw(
            msg.sender,
            address(offer),
            address(want),
            offerAmount,
            assetOutWithDiscount,
            block.timestamp
        );
    }

    //============================== SOLVER FUNCTIONS ===============================

    /**
     * @notice Called by solvers in order to exchange offer asset for want asset.
     * @notice Solvers are optimistically transferred the offer asset, then are required to
     *         approve this contract to spend enough of want assets to cover the request.
     * @dev It is very likely `solve` TXs will be front run if broadcasted to public mem pools,
     *      so solvers should use private mem pools.
     * @param runData extra data that is passed back to solver when `finishSolve` is called
     * @param request the atomic request to solve
     */
    function solve(
        bytes calldata runData,
        AtomicRequest calldata request
    ) external nonReentrant {
        ERC20 offer = ERC20(request.offer);
        ERC20 want = ERC20(request.want);
        address user = request.user;
        
        // Save offer asset decimals.
        uint8 offerDecimals = offer.decimals();

        checkAtomicRequestValid(request);

        // Check maturity time
        if (
            block.timestamp
                < request.creationTime
                    + (whitelist[user] ? maturityTime / whitelistMaturityDivisor : maturityTime)
        ) {
            revert AtomicQueue__RequestNotMature(user);
        }

        // Check if the caller is the solver
        if (msg.sender != address(solver)) revert AtomicQueue__UnauthorizedSolver(msg.sender);

        uint256 safeRate = accountant.getRateInQuoteSafe(ERC20(request.want));
        uint256 safeAtomicPriceWithDiscount = safeRate.mulDivDown(DISCOUNT_DENOMINATOR - discount, DISCOUNT_DENOMINATOR);

        // Calculate want assets needed
        uint256 assetsForWant = _calculateAssetAmount(request.offerAmount, safeAtomicPriceWithDiscount, offerDecimals);

        // // Transfer offer shares from user to solver contract
        // offer.safeTransferFrom(user, solver, request.offerAmount);

        // Call solver contract to finish the solve
        IAtomicSolver(solver).finishSolve(runData, msg.sender, offer, want, request.offerAmount, assetsForWant, address(accountant.vault()));

        // Transfer want assets from solver contract to user
        want.safeTransferFrom(address(solver), user, assetsForWant);

        // Decrease the withdraw in progress amount
        withdrawInProgressAmount[address(offer)][address(want)] -= request.offerAmount;

        bytes32 requestId = keccak256(abi.encode(request));
        // Emit event
        emit AtomicRequestFulfilled(
            requestId, user, address(offer), address(want), request.offerAmount, assetsForWant, block.timestamp
        );

        // Remove request from queue
        _existingWithdrawRequests.remove(requestId);
    }

    //============================== INTERNAL FUNCTIONS ===============================

    /**
     * @notice Helper function to calculate the amount of want assets a users wants in exchange for
     *         `offerAmount` of offer asset.
     */
    function _calculateAssetAmount(uint256 offerAmount, uint256 atomicPrice, uint8 offerDecimals)
        internal
        pure
        returns (uint256)
    {
        return atomicPrice.mulDivDown(offerAmount, 10 ** offerDecimals);
    }
}

// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

import {AtomicQueue, ERC20, SafeTransferLib, AtomicRequest} from "./AtomicQueue.sol";
import {IAtomicSolver} from "./IAtomicSolver.sol";
import {Auth, Authority} from "@solmate/auth/Auth.sol";
import {ERC4626} from "@solmate/tokens/ERC4626.sol";
import {IWEETH} from "src/interfaces/IStaking.sol";
import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
import {TellerWithMultiAssetSupport} from "src/base/Roles/TellerWithMultiAssetSupport.sol";
import {Multicall} from "@openzeppelin/contracts/utils/Multicall.sol";

/**
 * @title AtomicSolverV4
 * @author crispymangoes
 */
contract AtomicSolverV4 is IAtomicSolver, Auth, Multicall {
    using SafeTransferLib for ERC20;
    using FixedPointMathLib for uint256;
    // ========================================= ENUMS =========================================

    /**
     * @notice The Solve Type, used in `finishSolve` to determine the logic used.
     * @notice P2P Solver wants to swap share.asset() for user(s) shares
     * @notice REDEEM Solver needs to redeem shares, then can cover user(s) required assets.
     * @notice MIGRATION_REDEEM Solver needs to redeem Cellar shares for BoringVault shares, then withdraw from BoringVault.
     * @dev DO NOT USE MIGRATION_REDEEM IF `offer` Cellar does not exclusively hold BoringVault shares.
     */
    enum SolveType {
        P2P,
        REDEEM,
        MIGRATION_REDEEM
    }

    //============================== ERRORS ===============================

    error AtomicSolverV4___WrongInitiator();
    error AtomicSolverV4___AlreadyInSolveContext();
    error AtomicSolverV4___FailedToSolve();
    error AtomicSolverV4___SolveMaxAssetsExceeded(uint256 actualAssets, uint256 maxAssets);
    // error AtomicSolverV4___P2PSolveMinSharesNotMet(uint256 actualShares, uint256 minShares);
    error AtomicSolverV4___BoringVaultTellerMismatch(address vault, address teller);
    error AtomicSolverV4___NoBoringVaultSharesReceived();
    // error AtomicSolverV4___OnlySelf();

    //============================== IMMUTABLES ===============================

    constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}

    //============================== ADMIN FUNCTIONS ===============================

    /**
     * @notice Allows the owner to rescue tokens from the contract.
     * @dev This should not normally be used, but it is possible that when performing a MIGRATION_REDEEM,
     *      the redemption of Cellar shares will return assets other than BoringVault shares.
     *      If the amount of assets is significant, it is very likely the solve will revert, but it is
     *      not guaranteed to revert, hence this function.
     */
    function rescueTokens(ERC20 token, uint256 amount) external requiresAuth {
        if (amount == type(uint256).max) amount = token.balanceOf(address(this));
        token.safeTransfer(msg.sender, amount);
    }

    //============================== SOLVE FUNCTIONS ===============================
    // /**
    //  * @notice Solver wants to exchange p2p share.asset() for withdraw queue shares.
    //  * @dev Solver should approve this contract to spend share.asset().
    //  */
    // function p2pSolve(
    //     AtomicQueue queue,
    //     uint256 minOfferReceived,
    //     uint256 maxAssets,
    //     AtomicRequest calldata request
    // ) external requiresAuth {
    //     bytes memory runData = abi.encode(SolveType.P2P, msg.sender, minOfferReceived, maxAssets);

    //     // Solve for `users`.
    //     queue.solve(runData, address(this), request);
    // }

    /**
     * @notice Solver wants to redeem withdraw offer shares, to help cover withdraw.
     * @dev `offer` MUST be an ERC4626 vault.
     */
    function redeemSolve(
        AtomicQueue queue,
        uint256 minimumAssetsOut,
        uint256 maxAssets,
        TellerWithMultiAssetSupport teller,
        AtomicRequest calldata request
    ) external requiresAuth {
        bytes memory runData = abi.encode(SolveType.REDEEM, msg.sender, minimumAssetsOut, maxAssets, teller);

        // Solve for `users`.
        queue.solve(runData, request);
    }

    // /**
    //  * @notice Allows a user to solve their own request to redeem Boring Vault shares.
    //  * @dev The user must be the same as the request user.
    //  */
    // function redeemSelfSolve(
    //     AtomicQueue queue,
    //     uint256 minimumAssetsOut,
    //     uint256 maxAssets,
    //     TellerWithMultiAssetSupport teller,
    //     AtomicRequest calldata request
    // ) external requiresAuth {
    //     if (request.user != msg.sender) revert AtomicSolverV4___OnlySelf();
    //     bytes memory runData = abi.encode(SolveType.REDEEM, msg.sender, minimumAssetsOut, maxAssets, teller);

    //     queue.solve(runData, address(this), request);
    // }

    // function migrationRedeemSolve(
    //     AtomicQueue queue,
    //     uint256 minimumAssetsOut,
    //     uint256 maxAssets,
    //     TellerWithMultiAssetSupport teller,
    //     AtomicRequest calldata request
    // ) external requiresAuth {
    //     bytes memory runData = abi.encode(SolveType.MIGRATION_REDEEM, msg.sender, minimumAssetsOut, maxAssets, teller);

    //     // Solve for `users`.
    //     queue.solve(runData, address(this), request);
    // }

    //============================== ISOLVER FUNCTIONS ===============================

    /**
     * @notice Implement the finishSolve function WithdrawQueue expects to call.
     * @dev nonReentrant is not needed on this function because it is impossible to reenter,
     *      because the above solve functions have the nonReentrant modifier.
     *      The only way to have the first 2 checks pass is if the msg.sender is the queue,
     *      and this contract is msg.sender of `Queue.solve()`, which is only called in the above
     *      functions.
     */
    function finishSolve(
        bytes calldata runData,
        address initiator,
        ERC20 offer,
        ERC20 want,
        uint256 offerReceived,
        uint256 wantApprovalAmount,
        address vault
    ) external requiresAuth {
        if (initiator != address(this)) revert AtomicSolverV4___WrongInitiator();

        // address queue = msg.sender;

        // SolveType _type = abi.decode(runData, (SolveType));

        // if (_type == SolveType.P2P) {
        //     _p2pSolve(queue, runData, offer, want, offerReceived, wantApprovalAmount);
        // } else if (_type == SolveType.REDEEM) {
            _redeemSolve(msg.sender, runData, offer, want, offerReceived, wantApprovalAmount, vault);
        // } else if (_type == SolveType.MIGRATION_REDEEM) {
        //     _migrationRedeemSolve(queue, runData, offer, want, offerReceived, wantApprovalAmount);
        // } else {
        //     revert AtomicSolverV4___FailedToSolve();
        // }
    }

    function approveOfferForQueue(
        address queue,
        AtomicRequest calldata request
    ) external requiresAuth {
        ERC20 offer = ERC20(request.offer);
        offer.safeApprove(queue, 0);
        offer.safeApprove(queue, request.offerAmount);
    }

    //============================== HELPER FUNCTIONS ===============================

    // /**
    //  * @notice Helper function containing the logic to handle p2p solves.
    //  */
    // function _p2pSolve(
    //     address queue,
    //     bytes memory runData,
    //     ERC20 offer,
    //     ERC20 want,
    //     uint256 offerReceived,
    //     uint256 wantApprovalAmount
    // ) internal {
    //     (, address solver, uint256 minOfferReceived, uint256 maxAssets) =
    //         abi.decode(runData, (SolveType, address, uint256, uint256));

    //     // Make sure solver is receiving the minimum amount of offer.
    //     if (offerReceived < minOfferReceived) {
    //         revert AtomicSolverV4___P2PSolveMinSharesNotMet(offerReceived, minOfferReceived);
    //     }

    //     // Make sure solvers `maxAssets` was not exceeded.
    //     if (wantApprovalAmount > maxAssets) {
    //         revert AtomicSolverV4___SolveMaxAssetsExceeded(wantApprovalAmount, maxAssets);
    //     }

    //     // Transfer required want from solver.
    //     want.safeTransferFrom(solver, address(this), wantApprovalAmount);

    //     // Transfer offer to solver.
    //     offer.safeTransfer(solver, offerReceived);

    //     // Approve queue to spend wantApprovalAmount.
    //     want.safeApprove(queue, wantApprovalAmount);
    // }

    /**
     * @notice Helper function containing the logic to handle redeem solves.
     */
    function _redeemSolve(
        address queue,
        bytes memory runData,
        ERC20 offer,
        ERC20 want,
        uint256 offerReceived,
        uint256 wantApprovalAmount,
        address vault
    ) internal {
        (, address solver, uint256 minimumAssetsOut, uint256 maxAssets, TellerWithMultiAssetSupport teller) =
            abi.decode(runData, (SolveType, address, uint256, uint256, TellerWithMultiAssetSupport));

        if (address(offer) != address(teller.vault())) {
            revert AtomicSolverV4___BoringVaultTellerMismatch(address(offer), address(teller));
        }
        // Make sure solvers `maxAssets` was not exceeded.
        if (wantApprovalAmount > maxAssets) {
            revert AtomicSolverV4___SolveMaxAssetsExceeded(wantApprovalAmount, maxAssets);
        }

        // Redeem the shares, sending assets to this contract.
        uint256 assetsOut = teller.bulkWithdraw(want, offerReceived, minimumAssetsOut, address(this));

        uint256 excessAssets = assetsOut - wantApprovalAmount;
        if (excessAssets > 0) { // means there is excess assets from discount, transfer to boring vault
            want.safeTransfer(vault, excessAssets);
        }

        // // Transfer required assets from solver.
        // want.safeTransferFrom(solver, address(this), wantApprovalAmount);

        // Approve queue to spend wantApprovalAmount.
        want.safeApprove(queue, 0);
        want.safeApprove(queue, wantApprovalAmount);
    }

    // /**
    //  * @notice Helper function containing the logic to handle migration redeem solves.
    //  * @dev DO NOT USE THIS FUNCTION IF `offer` Cellar does not exclusively hold BoringVault shares.
    //  */
    // function _migrationRedeemSolve(
    //     address queue,
    //     bytes memory runData,
    //     ERC20 offer,
    //     ERC20 want,
    //     uint256 offerReceived,
    //     uint256 wantApprovalAmount
    // ) internal {
    //     (, address solver, uint256 minimumAssetsOut, uint256 maxAssets, TellerWithMultiAssetSupport teller) =
    //         abi.decode(runData, (SolveType, address, uint256, uint256, TellerWithMultiAssetSupport));

    //     // Make sure solvers `maxAssets` was not exceeded.
    //     if (wantApprovalAmount > maxAssets) {
    //         revert AtomicSolverV4___SolveMaxAssetsExceeded(wantApprovalAmount, maxAssets);
    //     }

    //     ERC20 boringVaultShare = ERC20(address(teller.vault()));

    //     // Offer is Cellar share, so redeem it to get BoringVault shares.
    //     uint256 bvShareDelta = boringVaultShare.balanceOf(address(this));
    //     ERC4626(address(offer)).redeem(offerReceived, address(this), address(this));
    //     bvShareDelta = boringVaultShare.balanceOf(address(this)) - bvShareDelta;

    //     // Make sure we received BoringVault shares.
    //     if (bvShareDelta == 0) {
    //         revert AtomicSolverV4___NoBoringVaultSharesReceived();
    //     }

    //     // Withdraw the BoringVault shares, sending assets to solver.
    //     teller.bulkWithdraw(want, bvShareDelta, minimumAssetsOut, solver);

    //     // Transfer required assets from solver.
    //     want.safeTransferFrom(solver, address(this), wantApprovalAmount);

    //     // Approve queue to spend wantApprovalAmount.
    //     want.safeApprove(queue, wantApprovalAmount);
    // }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import {ERC20} from "@solmate/tokens/ERC20.sol";
import {WETH} from "@solmate/tokens/WETH.sol";
import {BoringVault} from "src/base/BoringVault.sol";
import {AccountantWithRateProviders} from "src/base/Roles/AccountantWithRateProviders.sol";
import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
import {BeforeTransferHook} from "src/interfaces/BeforeTransferHook.sol";
import {Auth, Authority} from "@solmate/auth/Auth.sol";
import {ReentrancyGuard} from "@solmate/utils/ReentrancyGuard.sol";

contract TellerWithMultiAssetSupport is Auth, BeforeTransferHook, ReentrancyGuard {
    using FixedPointMathLib for uint256;
    using SafeTransferLib for ERC20;
    using SafeTransferLib for WETH;

    // ========================================= CONSTANTS =========================================

    /**
     * @notice Native address used to tell the contract to handle native asset deposits.
     */
    address internal constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    /**
     * @notice The maximum possible share lock period.
     */
    uint256 internal constant MAX_SHARE_LOCK_PERIOD = 3 days;

    // ========================================= STATE =========================================

    /**
     * @notice Mapping ERC20s to an isSupported bool.
     */
    mapping(ERC20 => bool) public isSupported;

    /**
     * @notice The deposit nonce used to map to a deposit hash.
     */
    uint96 public depositNonce = 1;

    /**
     * @notice After deposits, shares are locked to the msg.sender's address
     *         for `shareLockPeriod`.
     * @dev During this time all trasnfers from msg.sender will revert, and
     *      deposits are refundable.
     */
    uint64 public shareLockPeriod;

    /**
     * @notice Used to pause calls to `deposit` and `depositWithPermit`.
     */
    bool public isPaused;

    /**
     * @dev Maps deposit nonce to keccak256(address receiver, address depositAsset, uint256 depositAmount, uint256 shareAmount, uint256 timestamp, uint256 shareLockPeriod).
     */
    mapping(uint256 => bytes32) public publicDepositHistory;

    /**
     * @notice Maps user address to the time their shares will be unlocked.
     */
    mapping(address => uint256) public shareUnlockTime;

    //============================== ERRORS ===============================

    error TellerWithMultiAssetSupport__ShareLockPeriodTooLong();
    error TellerWithMultiAssetSupport__SharesAreLocked();
    error TellerWithMultiAssetSupport__SharesAreUnLocked();
    error TellerWithMultiAssetSupport__BadDepositHash();
    error TellerWithMultiAssetSupport__AssetNotSupported();
    error TellerWithMultiAssetSupport__ZeroAssets();
    error TellerWithMultiAssetSupport__MinimumMintNotMet();
    error TellerWithMultiAssetSupport__MinimumAssetsNotMet();
    error TellerWithMultiAssetSupport__PermitFailedAndAllowanceTooLow();
    error TellerWithMultiAssetSupport__ZeroShares();
    error TellerWithMultiAssetSupport__DualDeposit();
    error TellerWithMultiAssetSupport__Paused();

    //============================== EVENTS ===============================

    event Paused();
    event Unpaused();
    event AssetAdded(address indexed asset);
    event AssetRemoved(address indexed asset);
    event Deposit(
        uint256 indexed nonce,
        address indexed receiver,
        address indexed depositAsset,
        uint256 depositAmount,
        uint256 shareAmount,
        uint256 depositTimestamp,
        uint256 shareLockPeriodAtTimeOfDeposit
    );
    event BulkDeposit(address indexed asset, uint256 depositAmount);
    event BulkWithdraw(address indexed asset, uint256 shareAmount);
    event DepositRefunded(uint256 indexed nonce, bytes32 depositHash, address indexed user);

    //============================== IMMUTABLES ===============================

    /**
     * @notice The BoringVault this contract is working with.
     */
    BoringVault public immutable vault;

    /**
     * @notice The AccountantWithRateProviders this contract is working with.
     */
    AccountantWithRateProviders public immutable accountant;

    /**
     * @notice One share of the BoringVault.
     */
    uint256 internal immutable ONE_SHARE;

    /**
     * @notice The native wrapper contract.
     */
    WETH public immutable nativeWrapper;

    constructor(address _owner, address _vault, address _accountant, address _weth)
        Auth(_owner, Authority(address(0)))
    {
        vault = BoringVault(payable(_vault));
        ONE_SHARE = 10 ** vault.decimals();
        accountant = AccountantWithRateProviders(_accountant);
        nativeWrapper = WETH(payable(_weth));
    }

    // ========================================= ADMIN FUNCTIONS =========================================

    /**
     * @notice Pause this contract, which prevents future calls to `deposit` and `depositWithPermit`.
     * @dev Callable by MULTISIG_ROLE.
     */
    function pause() external requiresAuth {
        isPaused = true;
        emit Paused();
    }

    /**
     * @notice Unpause this contract, which allows future calls to `deposit` and `depositWithPermit`.
     * @dev Callable by MULTISIG_ROLE.
     */
    function unpause() external requiresAuth {
        isPaused = false;
        emit Unpaused();
    }

    /**
     * @notice Adds this asset as a deposit asset.
     * @dev The accountant must also support pricing this asset, else the `deposit` call will revert.
     * @dev Callable by OWNER_ROLE.
     */
    function addAsset(ERC20 asset) external requiresAuth {
        isSupported[asset] = true;
        emit AssetAdded(address(asset));
    }

    /**
     * @notice Removes this asset as a deposit asset.
     * @dev Callable by OWNER_ROLE.
     */
    function removeAsset(ERC20 asset) external requiresAuth {
        isSupported[asset] = false;
        emit AssetRemoved(address(asset));
    }

    /**
     * @notice Sets the share lock period.
     * @dev This not only locks shares to the user address, but also serves as the pending deposit period, where deposits can be reverted.
     * @dev If a new shorter share lock period is set, users with pending share locks could make a new deposit to receive 1 wei shares,
     *      and have their shares unlock sooner than their original deposit allows. This state would allow for the user deposit to be refunded,
     *      but only if they have not transferred their shares out of there wallet. This is an accepted limitation, and should be known when decreasing
     *      the share lock period.
     * @dev Callable by OWNER_ROLE.
     */
    function setShareLockPeriod(uint64 _shareLockPeriod) external requiresAuth {
        if (_shareLockPeriod > MAX_SHARE_LOCK_PERIOD) revert TellerWithMultiAssetSupport__ShareLockPeriodTooLong();
        shareLockPeriod = _shareLockPeriod;
    }

    // ========================================= BeforeTransferHook FUNCTIONS =========================================

    /**
     * @notice Implement beforeTransfer hook to check if shares are locked.
     */
    function beforeTransfer(address from, address, address) public view virtual {
        if (shareUnlockTime[from] > block.timestamp) revert TellerWithMultiAssetSupport__SharesAreLocked();
    }

    // ========================================= REVERT DEPOSIT FUNCTIONS =========================================

    /**
     * @notice Allows DEPOSIT_REFUNDER_ROLE to revert a pending deposit.
     * @dev Once a deposit share lock period has passed, it can no longer be reverted.
     * @dev It is possible the admin does not setup the BoringVault to call the transfer hook,
     *      but this contract can still be saving share lock state. In the event this happens
     *      deposits are still refundable if the user has not transferred their shares.
     *      But there is no guarantee that the user has not transferred their shares.
     * @dev Callable by STRATEGIST_MULTISIG_ROLE.
     */
    function refundDeposit(
        uint256 nonce,
        address receiver,
        address depositAsset,
        uint256 depositAmount,
        uint256 shareAmount,
        uint256 depositTimestamp,
        uint256 shareLockUpPeriodAtTimeOfDeposit
    ) external requiresAuth {
        if ((block.timestamp - depositTimestamp) > shareLockUpPeriodAtTimeOfDeposit) {
            // Shares are already unlocked, so we can not revert deposit.
            revert TellerWithMultiAssetSupport__SharesAreUnLocked();
        }
        bytes32 depositHash = keccak256(
            abi.encode(
                receiver, depositAsset, depositAmount, shareAmount, depositTimestamp, shareLockUpPeriodAtTimeOfDeposit
            )
        );
        if (publicDepositHistory[nonce] != depositHash) revert TellerWithMultiAssetSupport__BadDepositHash();

        // Delete hash to prevent refund gas.
        delete publicDepositHistory[nonce];

        // If deposit used native asset, send user back wrapped native asset.
        depositAsset = depositAsset == NATIVE ? address(nativeWrapper) : depositAsset;
        // Burn shares and refund assets to receiver.
        vault.exit(receiver, ERC20(depositAsset), depositAmount, receiver, shareAmount);

        emit DepositRefunded(nonce, depositHash, receiver);
    }

    // ========================================= USER FUNCTIONS =========================================

    /**
     * @notice Allows users to deposit into the BoringVault, if this contract is not paused.
     * @dev Publicly callable.
     */
    function deposit(ERC20 depositAsset, uint256 depositAmount, uint256 minimumMint)
        external
        payable
        requiresAuth
        nonReentrant
        returns (uint256 shares)
    {
        if (isPaused) revert TellerWithMultiAssetSupport__Paused();
        if (!isSupported[depositAsset]) revert TellerWithMultiAssetSupport__AssetNotSupported();

        if (address(depositAsset) == NATIVE) {
            if (msg.value == 0) revert TellerWithMultiAssetSupport__ZeroAssets();
            nativeWrapper.deposit{value: msg.value}();
            depositAmount = msg.value;
            shares = depositAmount.mulDivDown(ONE_SHARE, accountant.getRateInQuoteSafe(nativeWrapper));
            if (shares < minimumMint) revert TellerWithMultiAssetSupport__MinimumMintNotMet();
            // `from` is address(this) since user already sent value.
            nativeWrapper.safeApprove(address(vault), depositAmount);
            vault.enter(address(this), nativeWrapper, depositAmount, msg.sender, shares);
        } else {
            if (msg.value > 0) revert TellerWithMultiAssetSupport__DualDeposit();
            shares = _erc20Deposit(depositAsset, depositAmount, minimumMint, msg.sender);
        }

        _afterPublicDeposit(msg.sender, depositAsset, depositAmount, shares, shareLockPeriod);
    }

    /**
     * @notice Allows users to deposit into BoringVault using permit.
     * @dev Publicly callable.
     */
    function depositWithPermit(
        ERC20 depositAsset,
        uint256 depositAmount,
        uint256 minimumMint,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external requiresAuth nonReentrant returns (uint256 shares) {
        if (isPaused) revert TellerWithMultiAssetSupport__Paused();
        if (!isSupported[depositAsset]) revert TellerWithMultiAssetSupport__AssetNotSupported();

        try depositAsset.permit(msg.sender, address(vault), depositAmount, deadline, v, r, s) {}
        catch {
            if (depositAsset.allowance(msg.sender, address(vault)) < depositAmount) {
                revert TellerWithMultiAssetSupport__PermitFailedAndAllowanceTooLow();
            }
        }
        shares = _erc20Deposit(depositAsset, depositAmount, minimumMint, msg.sender);

        _afterPublicDeposit(msg.sender, depositAsset, depositAmount, shares, shareLockPeriod);
    }

    /**
     * @notice Allows on ramp role to deposit into this contract.
     * @dev Does NOT support native deposits.
     * @dev Callable by SOLVER_ROLE.
     */
    function bulkDeposit(ERC20 depositAsset, uint256 depositAmount, uint256 minimumMint, address to)
        external
        requiresAuth
        nonReentrant
        returns (uint256 shares)
    {
        if (!isSupported[depositAsset]) revert TellerWithMultiAssetSupport__AssetNotSupported();

        shares = _erc20Deposit(depositAsset, depositAmount, minimumMint, to);
        emit BulkDeposit(address(depositAsset), depositAmount);
    }

    /**
     * @notice Allows off ramp role to withdraw from this contract.
     * @dev Callable by SOLVER_ROLE.
     */
    function bulkWithdraw(ERC20 withdrawAsset, uint256 shareAmount, uint256 minimumAssets, address to)
        external
        requiresAuth
        returns (uint256 assetsOut)
    {
        if (!isSupported[withdrawAsset]) revert TellerWithMultiAssetSupport__AssetNotSupported();

        if (shareAmount == 0) revert TellerWithMultiAssetSupport__ZeroShares();
        assetsOut = shareAmount.mulDivDown(accountant.getRateInQuoteSafe(withdrawAsset), ONE_SHARE);
        if (assetsOut < minimumAssets) revert TellerWithMultiAssetSupport__MinimumAssetsNotMet();
        vault.exit(to, withdrawAsset, assetsOut, msg.sender, shareAmount);
        emit BulkWithdraw(address(withdrawAsset), shareAmount);
    }

    // ========================================= INTERNAL HELPER FUNCTIONS =========================================

    /**
     * @notice Implements a common ERC20 deposit into BoringVault.
     */
    function _erc20Deposit(ERC20 depositAsset, uint256 depositAmount, uint256 minimumMint, address to)
        internal
        returns (uint256 shares)
    {
        if (depositAmount == 0) revert TellerWithMultiAssetSupport__ZeroAssets();
        shares = depositAmount.mulDivDown(ONE_SHARE, accountant.getRateInQuoteSafe(depositAsset));
        if (shares < minimumMint) revert TellerWithMultiAssetSupport__MinimumMintNotMet();
        vault.enter(msg.sender, depositAsset, depositAmount, to, shares);
    }

    /**
     * @notice Handle share lock logic, and event.
     */
    function _afterPublicDeposit(
        address user,
        ERC20 depositAsset,
        uint256 depositAmount,
        uint256 shares,
        uint256 currentShareLockPeriod
    ) internal {
        shareUnlockTime[user] = block.timestamp + currentShareLockPeriod;

        uint256 nonce = depositNonce;
        publicDepositHistory[nonce] =
            keccak256(abi.encode(user, depositAsset, depositAmount, shares, block.timestamp, currentShareLockPeriod));
        depositNonce++;
        emit Deposit(nonce, user, address(depositAsset), depositAmount, shares, block.timestamp, currentShareLockPeriod);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @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.
 *
 * ```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 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 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;

        /// @solidity memory-safe-assembly
        assembly {
            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 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;

        /// @solidity memory-safe-assembly
        assembly {
            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 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;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

File 10 of 45 : ReentrancyGuard.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    uint256 private locked = 1;

    modifier nonReentrant() virtual {
        require(locked == 1, "REENTRANCY");

        locked = 2;

        _;

        locked = 1;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

// 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.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

import {Ownable} from "./Ownable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
    /*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant MAX_UINT256 = 2**256 - 1;

    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
    }

    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
    }

    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
    }

    /*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // Divide x * y by the denominator.
            z := div(mul(x, y), denominator)
        }
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // If x * y modulo the denominator is strictly greater than 0,
            // 1 is added to round up the division of x * y by the denominator.
            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
        }
    }

    function rpow(
        uint256 x,
        uint256 n,
        uint256 scalar
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            switch x
            case 0 {
                switch n
                case 0 {
                    // 0 ** 0 = 1
                    z := scalar
                }
                default {
                    // 0 ** n = 0
                    z := 0
                }
            }
            default {
                switch mod(n, 2)
                case 0 {
                    // If n is even, store scalar in z for now.
                    z := scalar
                }
                default {
                    // If n is odd, store x in z for now.
                    z := x
                }

                // Shifting right by 1 is like dividing by 2.
                let half := shr(1, scalar)

                for {
                    // Shift n right by 1 before looping to halve it.
                    n := shr(1, n)
                } n {
                    // Shift n right by 1 each iteration to halve it.
                    n := shr(1, n)
                } {
                    // Revert immediately if x ** 2 would overflow.
                    // Equivalent to iszero(eq(div(xx, x), x)) here.
                    if shr(128, x) {
                        revert(0, 0)
                    }

                    // Store x squared.
                    let xx := mul(x, x)

                    // Round to the nearest number.
                    let xxRound := add(xx, half)

                    // Revert if xx + half overflowed.
                    if lt(xxRound, xx) {
                        revert(0, 0)
                    }

                    // Set x to scaled xxRound.
                    x := div(xxRound, scalar)

                    // If n is even:
                    if mod(n, 2) {
                        // Compute z * x.
                        let zx := mul(z, x)

                        // If z * x overflowed:
                        if iszero(eq(div(zx, x), z)) {
                            // Revert if x is non-zero.
                            if iszero(iszero(x)) {
                                revert(0, 0)
                            }
                        }

                        // Round to the nearest number.
                        let zxRound := add(zx, half)

                        // Revert if zx + half overflowed.
                        if lt(zxRound, zx) {
                            revert(0, 0)
                        }

                        // Return properly scaled zxRound.
                        z := div(zxRound, scalar)
                    }
                }
            }
        }
    }

    /*//////////////////////////////////////////////////////////////
                        GENERAL NUMBER UTILITIES
    //////////////////////////////////////////////////////////////*/

    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let y := x // We start y at x, which will help us make our initial estimate.

            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // We check y >= 2^(k + 8) but shift right by k bits
            // each branch to ensure that if x >= 256, then y >= 256.
            if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                y := shr(128, y)
                z := shl(64, z)
            }
            if iszero(lt(y, 0x1000000000000000000)) {
                y := shr(64, y)
                z := shl(32, z)
            }
            if iszero(lt(y, 0x10000000000)) {
                y := shr(32, y)
                z := shl(16, z)
            }
            if iszero(lt(y, 0x1000000)) {
                y := shr(16, y)
                z := shl(8, z)
            }

            // Goal was to get z*z*y within a small factor of x. More iterations could
            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).
            // We ensured y >= 256 so that the relative difference between y and y+1 is small.
            // That's not possible if x < 256 but we can just verify those cases exhaustively.

            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.

            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.

            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.

            // There is no overflow risk here since y < 2^136 after the first branch above.
            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If x+1 is a perfect square, the Babylonian method cycles between
            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
            z := sub(z, lt(div(x, z), z))
        }
    }

    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Mod x by y. Note this will return
            // 0 instead of reverting if y is zero.
            z := mod(x, y)
        }
    }

    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // Divide x by y. Note this will return
            // 0 instead of reverting if y is zero.
            r := div(x, y)
        }
    }

    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Add 1 to x * y if x % y > 0. Note this will
            // return 0 instead of reverting if y is zero.
            z := add(gt(mod(x, y), 0), div(x, y))
        }
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        ERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
            mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "APPROVE_FAILED");
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;

import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { AtomicRequest, AtomicQueue } from "./AtomicQueue.sol";

interface IAtomicSolver {
    /**
     * @notice This function must be implemented in order for an address to be a `solver`
     *         for the AtomicQueue
     * @param runData arbitrary bytes data that is dependent on how each solver is setup
     *        it could contain swap data, or flash loan data, etc..
     * @param initiator the address that initiated a solve
     * @param offer the ERC20 asset sent to the solver
     * @param want the ERC20 asset the solver must approve the queue for
     * @param assetsToOffer the amount of `offer` sent to the solver
     * @param assetsForWant the amount of `want` the solver must approve the queue for
     * @param vault the address of the vault
     */
    function finishSolve(
        bytes calldata runData,
        address initiator,
        ERC20 offer,
        ERC20 want,
        uint256 assetsToOffer,
        uint256 assetsForWant,
        address vault
    ) external;

    /**
     * @notice Approve the offer for the queue to spend
     * @param queue the address of the queue
     * @param request the atomic request to approve
     */
    function approveOfferForQueue(
        address queue,
        AtomicRequest calldata request
    ) external;
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
    event OwnershipTransferred(address indexed user, address indexed newOwner);

    event AuthorityUpdated(address indexed user, Authority indexed newAuthority);

    address public owner;

    Authority public authority;

    constructor(address _owner, Authority _authority) {
        owner = _owner;
        authority = _authority;

        emit OwnershipTransferred(msg.sender, _owner);
        emit AuthorityUpdated(msg.sender, _authority);
    }

    modifier requiresAuth() virtual {
        require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");

        _;
    }

    function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
        Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.

        // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
        // aware that this makes protected functions uncallable even to the owner if the authority is out of order.
        return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
    }

    function setAuthority(Authority newAuthority) public virtual {
        // We check if the caller is the owner first because we want to ensure they can
        // always swap out the authority even if it's reverting or using up a lot of gas.
        require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));

        authority = newAuthority;

        emit AuthorityUpdated(msg.sender, newAuthority);
    }

    function transferOwnership(address newOwner) public virtual requiresAuth {
        owner = newOwner;

        emit OwnershipTransferred(msg.sender, newOwner);
    }
}

/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
    function canCall(
        address user,
        address target,
        bytes4 functionSig
    ) external view returns (bool);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
import {ERC20} from "@solmate/tokens/ERC20.sol";
import {BeforeTransferHook} from "src/interfaces/BeforeTransferHook.sol";
import {Auth, Authority} from "@solmate/auth/Auth.sol";
import {ERC20Upgradeable} from "@openzeppelin-contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {Initializable} from "@openzeppelin-contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin-contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC165} from "@openzeppelin/contracts/interfaces/IERC165.sol";

contract BoringVault is Auth, Initializable, ERC20Upgradeable, UUPSUpgradeable, ERC721Holder, ERC1155Holder {
    using Address for address;
    using SafeTransferLib for ERC20;
    using FixedPointMathLib for uint256;

    // ========================================= STATE =========================================

    /**
     * @notice Contract responsbile for implementing `beforeTransfer`.
     */
    BeforeTransferHook public hook;

    uint8 private _decimals;

    uint256 public maxTotalSupply = 10_000_000 * 1e6;

    //============================== EVENTS ===============================

    event Enter(address indexed from, address indexed asset, uint256 amount, address indexed to, uint256 shares);
    event Exit(address indexed to, address indexed asset, uint256 amount, address indexed from, uint256 shares);

    //============================== ERRORS ===============================
    error NotSuperchainERC20Bridge();

    //============================== CONSTRUCTOR ===============================
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() Auth(address(0), Authority(address(0))) {
        _disableInitializers();
    }

    function initialize(
        address _owner,
        Authority _authority,
        string memory _name,
        string memory _symbol,
        uint8 decimals_
    ) public initializer {
        __ERC20_init(_name, _symbol);
        __UUPSUpgradeable_init();
        owner = _owner;
        authority = _authority;
        _decimals = decimals_;
        maxTotalSupply = 10_000_000 * 1e6;
    }

    function _authorizeUpgrade(address newImplementation)
        internal
        override
        requiresAuth
    {}

    //============================== MANAGE ===============================

    /**
     * @notice Allows manager to make an arbitrary function call from this contract.
     * @dev Callable by MANAGER_ROLE.
     */
    function manage(address target, bytes calldata data, uint256 value)
        external
        requiresAuth
        returns (bytes memory result)
    {
        result = target.functionCallWithValue(data, value);
    }

    /**
     * @notice Allows manager to make arbitrary function calls from this contract.
     * @dev Callable by MANAGER_ROLE.
     */
    function manage(address[] calldata targets, bytes[] calldata data, uint256[] calldata values)
        external
        requiresAuth
        returns (bytes[] memory results)
    {
        uint256 targetsLength = targets.length;
        results = new bytes[](targetsLength);
        for (uint256 i; i < targetsLength; ++i) {
            results[i] = targets[i].functionCallWithValue(data[i], values[i]);
        }
    }

    //============================== ENTER ===============================

    /**
     * @notice Allows minter to mint shares, in exchange for assets.
     * @dev If assetAmount is zero, no assets are transferred in.
     * @dev Callable by MINTER_ROLE.
     */
    function enter(address from, ERC20 asset, uint256 assetAmount, address to, uint256 shareAmount)
        external
        requiresAuth
    {
        // Check if total supply would exceed max
        require(totalSupply() + shareAmount <= maxTotalSupply, "Exceeds max total supply");

        // Transfer assets in
        if (assetAmount > 0) asset.safeTransferFrom(from, address(this), assetAmount);

        // Mint shares.
        _mint(to, shareAmount);

        emit Enter(from, address(asset), assetAmount, to, shareAmount);
    }

    //============================== EXIT ===============================

    /**
     * @notice Allows burner to burn shares, in exchange for assets.
     * @dev If assetAmount is zero, no assets are transferred out.
     * @dev Callable by BURNER_ROLE.
     */
    function exit(address to, ERC20 asset, uint256 assetAmount, address from, uint256 shareAmount)
        external
        requiresAuth
    {
        // Burn shares.
        _burn(from, shareAmount);

        // Transfer assets out.
        if (assetAmount > 0) asset.safeTransfer(to, assetAmount);

        emit Exit(to, address(asset), assetAmount, from, shareAmount);
    }

    //============================== BEFORE TRANSFER HOOK ===============================
    /**
     * @notice Sets the share locker.
     * @notice If set to zero address, the share locker logic is disabled.
     * @dev Callable by OWNER_ROLE.
     */
    function setBeforeTransferHook(address _hook) external requiresAuth {
        hook = BeforeTransferHook(_hook);
    }

    /**
     * @notice Call `beforeTransferHook` passing in `from` `to`, and `msg.sender`.
     */
    function _callBeforeTransfer(address from, address to) internal view {
        if (address(hook) != address(0)) hook.beforeTransfer(from, to, msg.sender);
    }

    function transfer(address to, uint256 amount) public override returns (bool) {
        _callBeforeTransfer(msg.sender, to);
        return super.transfer(to, amount);
    }

    function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
        _callBeforeTransfer(from, to);
        return super.transferFrom(from, to, amount);
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 _interfaceId) public view virtual override (ERC1155Holder) returns (bool) {
        return _interfaceId == type(IERC20).interfaceId
            || _interfaceId == type(IERC165).interfaceId || super.supportsInterface(_interfaceId);
    }

    //============================== RECEIVE ===============================

    receive() external payable {}

    function decimals() public view override returns (uint8) {
        return _decimals;
    }

    /**
     * @notice Sets the maximum total supply of shares.
     * @dev Callable by authorized roles.
     */
    function setMaxTotalSupply(uint256 _maxTotalSupply) external requiresAuth {
        maxTotalSupply = _maxTotalSupply;
    }

    /// @notice Sets the name and symbol of the token.
    /// @dev Callable by authorized roles.
    /// @param name_ The name of the token.
    /// @param symbol_ The symbol of the token.
    function setNameAndSymbol(string calldata name_, string calldata symbol_) external requiresAuth {
        // get storage
        bytes32 ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
        ERC20Upgradeable.ERC20Storage storage $;
        assembly {
            $.slot := ERC20StorageLocation
        }
        // set name and symbol in storage
        $._name = name_;
        $._symbol = symbol_;
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
import {IRateProvider} from "src/interfaces/IRateProvider.sol";
import {ERC20} from "@solmate/tokens/ERC20.sol";
import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
import {BoringVault} from "src/base/BoringVault.sol";
import {Auth, Authority} from "@solmate/auth/Auth.sol";
import {IPausable} from "src/interfaces/IPausable.sol";

contract AccountantWithRateProviders is Auth, IRateProvider, IPausable {
    using FixedPointMathLib for uint256;
    using SafeTransferLib for ERC20;

    // ========================================= STRUCTS =========================================

    /**
     * @param payoutAddress the address `claimFees` sends fees to
     * @param highwaterMark the highest value of the BoringVault's share price
     * @param feesOwedInBase total pending fees owed in terms of base
     * @param totalSharesLastUpdate total amount of shares the last exchange rate update
     * @param exchangeRate the current exchange rate in terms of base
     * @param allowedExchangeRateChangeUpper the max allowed change to exchange rate from an update
     * @param allowedExchangeRateChangeLower the min allowed change to exchange rate from an update
     * @param lastUpdateTimestamp the block timestamp of the last exchange rate update
     * @param isPaused whether or not this contract is paused
     * @param minimumUpdateDelayInSeconds the minimum amount of time that must pass between
     *        exchange rate updates, such that the update won't trigger the contract to be paused
     * @param managementFee the management fee
     * @param performanceFee the performance fee
     */
    struct AccountantState {
        address payoutAddress;
        uint96 highwaterMark;
        uint128 feesOwedInBase;
        uint128 totalSharesLastUpdate;
        uint96 exchangeRate;
        uint16 allowedExchangeRateChangeUpper;
        uint16 allowedExchangeRateChangeLower;
        uint64 lastUpdateTimestamp;
        bool isPaused;
        uint24 minimumUpdateDelayInSeconds;
        uint16 managementFee;
        uint16 performanceFee;
    }

    /**
     * @param isPeggedToBase whether or not the asset is 1:1 with the base asset
     * @param rateProvider the rate provider for this asset if `isPeggedToBase` is false
     */
    struct RateProviderData {
        bool isPeggedToBase;
        IRateProvider rateProvider;
    }

    // ========================================= STATE =========================================

    /**
     * @notice Store the accountant state in 3 packed slots.
     */
    AccountantState public accountantState;

    /**
     * @notice Maps ERC20s to their RateProviderData.
     */
    mapping(ERC20 => RateProviderData) public rateProviderData;

    //============================== ERRORS ===============================

    error AccountantWithRateProviders__UpperBoundTooSmall();
    error AccountantWithRateProviders__LowerBoundTooLarge();
    error AccountantWithRateProviders__ManagementFeeTooLarge();
    error AccountantWithRateProviders__PerformanceFeeTooLarge();
    error AccountantWithRateProviders__Paused();
    error AccountantWithRateProviders__ZeroFeesOwed();
    error AccountantWithRateProviders__OnlyCallableByBoringVault();
    error AccountantWithRateProviders__UpdateDelayTooLarge();
    error AccountantWithRateProviders__ExchangeRateAboveHighwaterMark();

    //============================== EVENTS ===============================

    event Paused();
    event Unpaused();
    event DelayInSecondsUpdated(uint24 oldDelay, uint24 newDelay);
    event UpperBoundUpdated(uint16 oldBound, uint16 newBound);
    event LowerBoundUpdated(uint16 oldBound, uint16 newBound);
    event ManagementFeeUpdated(uint16 oldFee, uint16 newFee);
    event PerformanceFeeUpdated(uint16 oldFee, uint16 newFee);
    event PayoutAddressUpdated(address oldPayout, address newPayout);
    event RateProviderUpdated(address asset, bool isPegged, address rateProvider);
    event ExchangeRateUpdated(uint96 oldRate, uint96 newRate, uint64 currentTime);
    event FeesClaimed(address indexed feeAsset, uint256 amount);
    event HighwaterMarkReset();

    //============================== IMMUTABLES ===============================

    /**
     * @notice The base asset rates are provided in.
     */
    ERC20 public immutable base;

    /**
     * @notice The decimals rates are provided in.
     */
    uint8 public immutable decimals;

    /**
     * @notice The BoringVault this accountant is working with.
     *         Used to determine share supply for fee calculation.
     */
    BoringVault public immutable vault;

    /**
     * @notice One share of the BoringVault.
     */
    uint256 internal immutable ONE_SHARE;

    constructor(
        address _owner,
        address _vault,
        address payoutAddress,
        uint96 startingExchangeRate,
        address _base,
        uint16 allowedExchangeRateChangeUpper,
        uint16 allowedExchangeRateChangeLower,
        uint24 minimumUpdateDelayInSeconds,
        uint16 managementFee,
        uint16 performanceFee
    ) Auth(_owner, Authority(address(0))) {
        base = ERC20(_base);
        decimals = ERC20(_base).decimals();
        vault = BoringVault(payable(_vault));
        ONE_SHARE = 10 ** vault.decimals();
        accountantState = AccountantState({
            payoutAddress: payoutAddress,
            highwaterMark: startingExchangeRate,
            feesOwedInBase: 0,
            totalSharesLastUpdate: uint128(vault.totalSupply()),
            exchangeRate: startingExchangeRate,
            allowedExchangeRateChangeUpper: allowedExchangeRateChangeUpper,
            allowedExchangeRateChangeLower: allowedExchangeRateChangeLower,
            lastUpdateTimestamp: uint64(block.timestamp),
            isPaused: false,
            minimumUpdateDelayInSeconds: minimumUpdateDelayInSeconds,
            managementFee: managementFee,
            performanceFee: performanceFee
        });
    }

    // ========================================= ADMIN FUNCTIONS =========================================
    /**
     * @notice Pause this contract, which prevents future calls to `updateExchangeRate`, and any safe rate
     *         calls will revert.
     * @dev Callable by MULTISIG_ROLE.
     */
    function pause() external requiresAuth {
        accountantState.isPaused = true;
        emit Paused();
    }

    /**
     * @notice Unpause this contract, which allows future calls to `updateExchangeRate`, and any safe rate
     *         calls will stop reverting.
     * @dev Callable by MULTISIG_ROLE.
     */
    function unpause() external requiresAuth {
        accountantState.isPaused = false;
        emit Unpaused();
    }

    /**
     * @notice Update the minimum time delay between `updateExchangeRate` calls.
     * @dev There are no input requirements, as it is possible the admin would want
     *      the exchange rate updated as frequently as needed.
     * @dev Callable by OWNER_ROLE.
     */
    function updateDelay(uint24 minimumUpdateDelayInSeconds) external requiresAuth {
        if (minimumUpdateDelayInSeconds > 14 days) revert AccountantWithRateProviders__UpdateDelayTooLarge();
        uint24 oldDelay = accountantState.minimumUpdateDelayInSeconds;
        accountantState.minimumUpdateDelayInSeconds = minimumUpdateDelayInSeconds;
        emit DelayInSecondsUpdated(oldDelay, minimumUpdateDelayInSeconds);
    }

    /**
     * @notice Update the allowed upper bound change of exchange rate between `updateExchangeRateCalls`.
     * @dev Callable by OWNER_ROLE.
     */
    function updateUpper(uint16 allowedExchangeRateChangeUpper) external requiresAuth {
        if (allowedExchangeRateChangeUpper < 1e4) revert AccountantWithRateProviders__UpperBoundTooSmall();
        uint16 oldBound = accountantState.allowedExchangeRateChangeUpper;
        accountantState.allowedExchangeRateChangeUpper = allowedExchangeRateChangeUpper;
        emit UpperBoundUpdated(oldBound, allowedExchangeRateChangeUpper);
    }

    /**
     * @notice Update the allowed lower bound change of exchange rate between `updateExchangeRateCalls`.
     * @dev Callable by OWNER_ROLE.
     */
    function updateLower(uint16 allowedExchangeRateChangeLower) external requiresAuth {
        if (allowedExchangeRateChangeLower > 1e4) revert AccountantWithRateProviders__LowerBoundTooLarge();
        uint16 oldBound = accountantState.allowedExchangeRateChangeLower;
        accountantState.allowedExchangeRateChangeLower = allowedExchangeRateChangeLower;
        emit LowerBoundUpdated(oldBound, allowedExchangeRateChangeLower);
    }

    /**
     * @notice Update the management fee to a new value.
     * @dev Callable by OWNER_ROLE.
     */
    function updateManagementFee(uint16 managementFee) external requiresAuth {
        if (managementFee > 0.2e4) revert AccountantWithRateProviders__ManagementFeeTooLarge();
        uint16 oldFee = accountantState.managementFee;
        accountantState.managementFee = managementFee;
        emit ManagementFeeUpdated(oldFee, managementFee);
    }

    /**
     * @notice Update the performance fee to a new value.
     * @dev Callable by OWNER_ROLE.
     */
    function updatePerformanceFee(uint16 performanceFee) external requiresAuth {
        if (performanceFee > 0.5e4) revert AccountantWithRateProviders__PerformanceFeeTooLarge();
        uint16 oldFee = accountantState.performanceFee;
        accountantState.performanceFee = performanceFee;
        emit PerformanceFeeUpdated(oldFee, performanceFee);
    }

    /**
     * @notice Update the payout address fees are sent to.
     * @dev Callable by OWNER_ROLE.
     */
    function updatePayoutAddress(address payoutAddress) external requiresAuth {
        address oldPayout = accountantState.payoutAddress;
        accountantState.payoutAddress = payoutAddress;
        emit PayoutAddressUpdated(oldPayout, payoutAddress);
    }

    /**
     * @notice Update the rate provider data for a specific `asset`.
     * @dev Rate providers must return rates in terms of `base` or
     * an asset pegged to base and they must use the same decimals
     * as `asset`.
     * @dev Callable by OWNER_ROLE.
     */
    function setRateProviderData(ERC20 asset, bool isPeggedToBase, address rateProvider) external requiresAuth {
        rateProviderData[asset] =
            RateProviderData({isPeggedToBase: isPeggedToBase, rateProvider: IRateProvider(rateProvider)});
        emit RateProviderUpdated(address(asset), isPeggedToBase, rateProvider);
    }

    /**
     * @notice Reset the highwater mark to the current exchange rate.
     * @dev Callable by OWNER_ROLE.
     */
    function resetHighwaterMark() external virtual requiresAuth {
        AccountantState storage state = accountantState;

        if (state.exchangeRate > state.highwaterMark) {
            revert AccountantWithRateProviders__ExchangeRateAboveHighwaterMark();
        }

        uint64 currentTime = uint64(block.timestamp);
        uint256 currentTotalShares = vault.totalSupply();
        _calculateFeesOwed(state, state.exchangeRate, state.exchangeRate, currentTotalShares, currentTime);
        state.totalSharesLastUpdate = uint128(currentTotalShares);
        state.highwaterMark = accountantState.exchangeRate;
        state.lastUpdateTimestamp = currentTime;

        emit HighwaterMarkReset();
    }

    // ========================================= UPDATE EXCHANGE RATE/FEES FUNCTIONS =========================================

    /**
     * @notice Updates this contract exchangeRate.
     * @dev If new exchange rate is outside of accepted bounds, or if not enough time has passed, this
     *      will pause the contract, and this function will NOT calculate fees owed.
     * @dev Callable by UPDATE_EXCHANGE_RATE_ROLE.
     */
    function updateExchangeRate(uint96 newExchangeRate) external requiresAuth {
        AccountantState storage state = accountantState;
        if (state.isPaused) revert AccountantWithRateProviders__Paused();
        uint64 currentTime = uint64(block.timestamp);
        uint256 currentExchangeRate = state.exchangeRate;
        uint256 currentTotalShares = vault.totalSupply();
        if (
            currentTime < state.lastUpdateTimestamp + state.minimumUpdateDelayInSeconds
                || newExchangeRate > currentExchangeRate.mulDivDown(state.allowedExchangeRateChangeUpper, 1e4)
                || newExchangeRate < currentExchangeRate.mulDivDown(state.allowedExchangeRateChangeLower, 1e4)
        ) {
            // Instead of reverting, pause the contract. This way the exchange rate updater is able to update the exchange rate
            // to a better value, and pause it.
            state.isPaused = true;
        } else {
            _calculateFeesOwed(state, newExchangeRate, currentExchangeRate, currentTotalShares, currentTime);
        }

        newExchangeRate = _setExchangeRate(newExchangeRate, state);
        state.totalSharesLastUpdate = uint128(currentTotalShares);
        state.lastUpdateTimestamp = currentTime;

        emit ExchangeRateUpdated(uint96(currentExchangeRate), newExchangeRate, currentTime);
    }

    /**
     * @notice Claim pending fees.
     * @dev This function must be called by the BoringVault.
     * @dev This function will lose precision if the exchange rate
     *      decimals is greater than the feeAsset's decimals.
     */
    function claimFees(ERC20 feeAsset) external {
        if (msg.sender != address(vault)) revert AccountantWithRateProviders__OnlyCallableByBoringVault();

        AccountantState storage state = accountantState;
        if (state.isPaused) revert AccountantWithRateProviders__Paused();
        if (state.feesOwedInBase == 0) revert AccountantWithRateProviders__ZeroFeesOwed();

        // Determine amount of fees owed in feeAsset.
        uint256 feesOwedInFeeAsset;
        RateProviderData memory data = rateProviderData[feeAsset];
        if (address(feeAsset) == address(base)) {
            feesOwedInFeeAsset = state.feesOwedInBase;
        } else {
            uint8 feeAssetDecimals = ERC20(feeAsset).decimals();
            uint256 feesOwedInBaseUsingFeeAssetDecimals =
                changeDecimals(state.feesOwedInBase, decimals, feeAssetDecimals);
            if (data.isPeggedToBase) {
                feesOwedInFeeAsset = feesOwedInBaseUsingFeeAssetDecimals;
            } else {
                uint256 rate = data.rateProvider.getRate();
                feesOwedInFeeAsset = feesOwedInBaseUsingFeeAssetDecimals.mulDivDown(10 ** feeAssetDecimals, rate);
            }
        }
        // Zero out fees owed.
        state.feesOwedInBase = 0;
        // Transfer fee asset to payout address.
        feeAsset.safeTransferFrom(msg.sender, state.payoutAddress, feesOwedInFeeAsset);

        emit FeesClaimed(address(feeAsset), feesOwedInFeeAsset);
    }

    // ========================================= RATE FUNCTIONS =========================================

    /**
     * @notice Get this BoringVault's current rate in the base.
     */
    function getRate() public view returns (uint256 rate) {
        rate = accountantState.exchangeRate;
    }

    /**
     * @notice Get this BoringVault's current rate in the base.
     * @dev Revert if paused.
     */
    function getRateSafe() external view returns (uint256 rate) {
        if (accountantState.isPaused) revert AccountantWithRateProviders__Paused();
        rate = getRate();
    }

    /**
     * @notice Get this BoringVault's current rate in the provided quote.
     * @dev `quote` must have its RateProviderData set, else this will revert.
     * @dev This function will lose precision if the exchange rate
     *      decimals is greater than the quote's decimals.
     */
    function getRateInQuote(ERC20 quote) public view returns (uint256 rateInQuote) {
        if (address(quote) == address(base)) {
            rateInQuote = accountantState.exchangeRate;
        } else {
            RateProviderData memory data = rateProviderData[quote];
            uint8 quoteDecimals = ERC20(quote).decimals();
            uint256 exchangeRateInQuoteDecimals = changeDecimals(accountantState.exchangeRate, decimals, quoteDecimals);
            if (data.isPeggedToBase) {
                rateInQuote = exchangeRateInQuoteDecimals;
            } else {
                uint256 quoteRate = data.rateProvider.getRate();
                uint256 oneQuote = 10 ** quoteDecimals;
                rateInQuote = oneQuote.mulDivDown(exchangeRateInQuoteDecimals, quoteRate);
            }
        }
    }

    /**
     * @notice Get this BoringVault's current rate in the provided quote.
     * @dev `quote` must have its RateProviderData set, else this will revert.
     * @dev Revert if paused.
     */
    function getRateInQuoteSafe(ERC20 quote) external view returns (uint256 rateInQuote) {
        if (accountantState.isPaused) revert AccountantWithRateProviders__Paused();
        rateInQuote = getRateInQuote(quote);
    }

    // ========================================= INTERNAL HELPER FUNCTIONS =========================================
    /**
     * @notice Used to change the decimals of precision used for an amount.
     */
    function changeDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) {
        if (fromDecimals == toDecimals) {
            return amount;
        } else if (fromDecimals < toDecimals) {
            return amount * 10 ** (toDecimals - fromDecimals);
        } else {
            return amount / 10 ** (fromDecimals - toDecimals);
        }
    }

    /**
     * @notice Set the exchange rate.
     */
    function _setExchangeRate(uint96 newExchangeRate, AccountantState storage state)
        internal
        virtual
        returns (uint96)
    {
        state.exchangeRate = newExchangeRate;
        return newExchangeRate;
    }
 
    /**
     * @notice Calculate management fees.
     */
    function _calculateManagementFee(
        uint128 totalSharesLastUpdate,
        uint64 lastUpdateTimestamp,
        uint16 managementFee,
        uint96 newExchangeRate,
        uint256 currentExchangeRate,
        uint256 currentTotalShares,
        uint64 currentTime
    ) internal view returns (uint256 managementFeesOwedInBase, uint256 shareSupplyToUse) {
        shareSupplyToUse = currentTotalShares;
        // Use the minimum between current total supply and total supply for last update.
        if (totalSharesLastUpdate < shareSupplyToUse) {
            shareSupplyToUse = totalSharesLastUpdate;
        }

        // Determine management fees owned.
        if (managementFee > 0) {
            uint256 timeDelta = currentTime - lastUpdateTimestamp;
            uint256 minimumAssets = newExchangeRate > currentExchangeRate
                ? shareSupplyToUse.mulDivDown(currentExchangeRate, ONE_SHARE)
                : shareSupplyToUse.mulDivDown(newExchangeRate, ONE_SHARE);
            uint256 managementFeesAnnual = minimumAssets.mulDivDown(managementFee, 1e4);
            managementFeesOwedInBase = managementFeesAnnual.mulDivDown(timeDelta, 365 days);
        }
    }

    /**
     * @notice Calculate performance fees.
     */
    function _calculatePerformanceFee(
        uint96 newExchangeRate,
        uint256 shareSupplyToUse,
        uint96 datum,
        uint16 performanceFee
    ) internal view returns (uint256 performanceFeesOwedInBase, uint256 yieldEarned) {
        uint256 changeInExchangeRate = newExchangeRate - datum;
        yieldEarned = changeInExchangeRate.mulDivDown(shareSupplyToUse, ONE_SHARE);
        if (performanceFee > 0) {
            performanceFeesOwedInBase = yieldEarned.mulDivDown(performanceFee, 1e4);
        }
    }

    /**
     * @notice Calculate fees owed in base.
     * @dev This function will update the highwater mark if the new exchange rate is higher.
     */
    function _calculateFeesOwed(
        AccountantState storage state,
        uint96 newExchangeRate,
        uint256 currentExchangeRate,
        uint256 currentTotalShares,
        uint64 currentTime
    ) internal virtual {
        // Only update fees if we are not paused.
        // Update fee accounting.
        (uint256 newFeesOwedInBase, uint256 shareSupplyToUse) = _calculateManagementFee(
            state.totalSharesLastUpdate,
            state.lastUpdateTimestamp,
            state.managementFee,
            newExchangeRate,
            currentExchangeRate,
            currentTotalShares,
            currentTime
        );

        // Account for performance fees.
        if (newExchangeRate > state.highwaterMark) {
            (uint256 performanceFeesOwedInBase,) =
                _calculatePerformanceFee(newExchangeRate, shareSupplyToUse, state.highwaterMark, state.performanceFee);

            // Add performance fees to fees owed.
            newFeesOwedInBase += performanceFeesOwedInBase;

            // Always update the highwater mark if the new exchange rate is higher.
            // This way if we are not iniitiall taking performance fees, we can start taking them
            // without back charging them on past performance.
            state.highwaterMark = newExchangeRate;
        }

        state.feesOwedInBase += uint128(newFeesOwedInBase);
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";
import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
import {FixedPointMathLib} from "../utils/FixedPointMathLib.sol";

/// @notice Minimal ERC4626 tokenized Vault implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC4626.sol)
abstract contract ERC4626 is ERC20 {
    using SafeTransferLib for ERC20;
    using FixedPointMathLib for uint256;

    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed caller,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /*//////////////////////////////////////////////////////////////
                               IMMUTABLES
    //////////////////////////////////////////////////////////////*/

    ERC20 public immutable asset;

    constructor(
        ERC20 _asset,
        string memory _name,
        string memory _symbol
    ) ERC20(_name, _symbol, _asset.decimals()) {
        asset = _asset;
    }

    /*//////////////////////////////////////////////////////////////
                        DEPOSIT/WITHDRAWAL LOGIC
    //////////////////////////////////////////////////////////////*/

    function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {
        // Check for rounding error since we round down in previewDeposit.
        require((shares = previewDeposit(assets)) != 0, "ZERO_SHARES");

        // Need to transfer before minting or ERC777s could reenter.
        asset.safeTransferFrom(msg.sender, address(this), assets);

        _mint(receiver, shares);

        emit Deposit(msg.sender, receiver, assets, shares);

        afterDeposit(assets, shares);
    }

    function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {
        assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.

        // Need to transfer before minting or ERC777s could reenter.
        asset.safeTransferFrom(msg.sender, address(this), assets);

        _mint(receiver, shares);

        emit Deposit(msg.sender, receiver, assets, shares);

        afterDeposit(assets, shares);
    }

    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) public virtual returns (uint256 shares) {
        shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.

        if (msg.sender != owner) {
            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.

            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
        }

        beforeWithdraw(assets, shares);

        _burn(owner, shares);

        emit Withdraw(msg.sender, receiver, owner, assets, shares);

        asset.safeTransfer(receiver, assets);
    }

    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) public virtual returns (uint256 assets) {
        if (msg.sender != owner) {
            uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.

            if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
        }

        // Check for rounding error since we round down in previewRedeem.
        require((assets = previewRedeem(shares)) != 0, "ZERO_ASSETS");

        beforeWithdraw(assets, shares);

        _burn(owner, shares);

        emit Withdraw(msg.sender, receiver, owner, assets, shares);

        asset.safeTransfer(receiver, assets);
    }

    /*//////////////////////////////////////////////////////////////
                            ACCOUNTING LOGIC
    //////////////////////////////////////////////////////////////*/

    function totalAssets() public view virtual returns (uint256);

    function convertToShares(uint256 assets) public view virtual returns (uint256) {
        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.

        return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());
    }

    function convertToAssets(uint256 shares) public view virtual returns (uint256) {
        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.

        return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);
    }

    function previewDeposit(uint256 assets) public view virtual returns (uint256) {
        return convertToShares(assets);
    }

    function previewMint(uint256 shares) public view virtual returns (uint256) {
        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.

        return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);
    }

    function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
        uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.

        return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());
    }

    function previewRedeem(uint256 shares) public view virtual returns (uint256) {
        return convertToAssets(shares);
    }

    /*//////////////////////////////////////////////////////////////
                     DEPOSIT/WITHDRAWAL LIMIT LOGIC
    //////////////////////////////////////////////////////////////*/

    function maxDeposit(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    function maxMint(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    function maxWithdraw(address owner) public view virtual returns (uint256) {
        return convertToAssets(balanceOf[owner]);
    }

    function maxRedeem(address owner) public view virtual returns (uint256) {
        return balanceOf[owner];
    }

    /*//////////////////////////////////////////////////////////////
                          INTERNAL HOOKS LOGIC
    //////////////////////////////////////////////////////////////*/

    function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}

    function afterDeposit(uint256 assets, uint256 shares) internal virtual {}
}

File 22 of 45 : IStaking.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.21;

// Swell
interface ISWETH {
    function deposit() external payable;
}

// EtherFi
interface ILiquidityPool {
    function deposit() external payable returns (uint256);

    function requestWithdraw(address recipient, uint256 amount) external returns (uint256);

    function amountForShare(uint256 shares) external view returns (uint256);

    function etherFiAdminContract() external view returns (address);

    function addEthAmountLockedForWithdrawal(uint128 _amount) external;
}

interface IWithdrawRequestNft {
    struct WithdrawRequest {
        uint96 amountOfEEth;
        uint96 shareOfEEth;
        bool isValid;
        uint32 feeGwei;
    }

    function claimWithdraw(uint256 tokenId) external;

    function getRequest(uint256 requestId) external view returns (WithdrawRequest memory);

    function finalizeRequests(uint256 requestId) external;

    function owner() external view returns (address);

    function updateAdmin(address admin, bool isAdmin) external;
}

interface IWEETH {
    function wrap(uint256 amount) external returns (uint256);

    function unwrap(uint256 amount) external returns (uint256);

    function getRate() external view returns (uint256);
}

// Kelp DAO
interface ILRTDepositPool {
    function depositAsset(
        address asset,
        uint256 depositAmount,
        uint256 minRSETHAmountToReceive,
        string calldata referralId
    ) external;
}

// Lido
interface ISTETH {
    function submit(address referral) external payable returns (uint256);
}

interface IWSTETH {
    function wrap(uint256 amount) external returns (uint256);

    function unwrap(uint256 amount) external returns (uint256);
}

interface IUNSTETH {
    struct WithdrawalRequestStatus {
        /// @notice stETH token amount that was locked on withdrawal queue for this request
        uint256 amountOfStETH;
        /// @notice amount of stETH shares locked on withdrawal queue for this request
        uint256 amountOfShares;
        /// @notice address that can claim or transfer this request
        address owner;
        /// @notice timestamp of when the request was created, in seconds
        uint256 timestamp;
        /// @notice true, if request is finalized
        bool isFinalized;
        /// @notice true, if request is claimed. Request is claimable if (isFinalized && !isClaimed)
        bool isClaimed;
    }

    function getWithdrawalStatus(uint256[] calldata _requestIds)
        external
        view
        returns (WithdrawalRequestStatus[] memory statuses);

    function requestWithdrawals(uint256[] calldata _amounts, address _owner)
        external
        returns (uint256[] memory requestIds);

    function claimWithdrawal(uint256 _requestId) external;

    function claimWithdrawals(uint256[] calldata _requestIds, uint256[] calldata _hints) external;

    function finalize(uint256 _lastRequestIdToBeFinalized, uint256 _maxShareRate) external payable;

    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    function FINALIZE_ROLE() external view returns (bytes32);

    function getLastFinalizedRequestId() external view returns (uint256);

    function getLastCheckpointIndex() external view returns (uint256);

    function findCheckpointHints(uint256[] memory requestIds, uint256 firstIndex, uint256 lastIndex)
        external
        view
        returns (uint256[] memory);

    function getClaimableEther(uint256[] memory requestIds, uint256[] memory hints)
        external
        view
        returns (uint256[] memory);
}

// Renzo
interface IRestakeManager {
    function depositETH() external payable;
}

// Stader
interface IStakePoolManager {
    function deposit(address _receiver) external payable returns (uint256);

    function getExchangeRate() external view returns (uint256);
}

interface IStaderConfig {
    function getDecimals() external view returns (uint256);
}

interface IUserWithdrawManager {
    struct WithdrawRequest {
        address owner;
        uint256 ethXAmount;
        uint256 ethExpected;
        uint256 ethFinalized;
        uint256 requestTime;
    }

    function requestWithdraw(uint256 _ethXAmount, address _owner) external returns (uint256);

    function claim(uint256 _requestId) external;

    function userWithdrawRequests(uint256) external view returns (WithdrawRequest memory);

    function finalizeUserWithdrawalRequest() external;
}

File 23 of 45 : Multicall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Multicall.sol)

pragma solidity ^0.8.20;

import {Address} from "./Address.sol";
import {Context} from "./Context.sol";

/**
 * @dev Provides a function to batch together multiple calls in a single external call.
 *
 * Consider any assumption about calldata validation performed by the sender may be violated if it's not especially
 * careful about sending transactions invoking {multicall}. For example, a relay address that filters function
 * selectors won't filter calls nested within a {multicall} operation.
 *
 * NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).
 * If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`
 * to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of
 * {_msgSender} are not propagated to subcalls.
 */
abstract contract Multicall is Context {
    /**
     * @dev Receives and executes a batch of function calls on this contract.
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
        bytes memory context = msg.sender == _msgSender()
            ? new bytes(0)
            : msg.data[msg.data.length - _contextSuffixLength():];

        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
        }
        return results;
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "./ERC20.sol";

import {SafeTransferLib} from "../utils/SafeTransferLib.sol";

/// @notice Minimalist and modern Wrapped Ether implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/WETH.sol)
/// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)
contract WETH is ERC20("Wrapped Ether", "WETH", 18) {
    using SafeTransferLib for address;

    event Deposit(address indexed from, uint256 amount);

    event Withdrawal(address indexed to, uint256 amount);

    function deposit() public payable virtual {
        _mint(msg.sender, msg.value);

        emit Deposit(msg.sender, msg.value);
    }

    function withdraw(uint256 amount) public virtual {
        _burn(msg.sender, amount);

        emit Withdrawal(msg.sender, amount);

        msg.sender.safeTransferETH(amount);
    }

    receive() external payable virtual {
        deposit();
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface BeforeTransferHook {
    function beforeTransfer(address from, address to, address operator) external view;
}

// 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;
    }
}

File 27 of 45 : ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/utils/ERC721Holder.sol)

pragma solidity ^0.8.20;

import {IERC721Receiver} from "../IERC721Receiver.sol";

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
 * {IERC721-setApprovalForAll}.
 */
abstract contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/utils/ERC1155Holder.sol)

pragma solidity ^0.8.20;

import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
import {IERC1155Receiver} from "../IERC1155Receiver.sol";

/**
 * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 */
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }

    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20
    struct ERC20Storage {
        mapping(address account => uint256) _balances;

        mapping(address account => mapping(address spender => uint256)) _allowances;

        uint256 _totalSupply;

        string _name;
        string _symbol;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;

    function _getERC20Storage() private pure returns (ERC20Storage storage $) {
        assembly {
            $.slot := ERC20StorageLocation
        }
    }

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        ERC20Storage storage $ = _getERC20Storage();
        $._name = name_;
        $._symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            $._totalSupply += value;
        } else {
            uint256 fromBalance = $._balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                $._balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                $._totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                $._balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        ERC20Storage storage $ = _getERC20Storage();
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        $._allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.20;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

File 32 of 45 : IERC165.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";

File 33 of 45 : IRateProvider.sol
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity ^0.8.0;

interface IRateProvider {
    function getRate() external view returns (uint256);
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface IPausable {
    function pause() external;
    function unpause() external;
}

File 35 of 45 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 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.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// 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.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

File 41 of 45 : draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.20;

import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 */
library ERC1967Utils {
    // We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
    // This will be fixed in Solidity 0.8.21. At that point we should remove these events.
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// 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) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

Settings
{
  "remappings": [
    "@solmate/=lib/solmate/src/",
    "@forge-std/=lib/forge-std/src/",
    "@ds-test/=lib/forge-std/lib/ds-test/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@layerzerolabs/lz-evm-protocol-v2/=lib/OAppAuth/lib/LayerZero-V2/packages/layerzero-v2/evm/protocol/",
    "@ccip/=lib/ccip/",
    "@oapp-auth/=lib/OAppAuth/src/",
    "@cryptoalgebra/Algebra/=lib/Algebra/src/core/",
    "@devtools-oapp-evm/=lib/OAppAuth/lib/devtools/packages/oapp-evm/contracts/oapp/",
    "@layerzerolabs/lz-evm-messagelib-v2/=lib/OAppAuth/node_modules/@layerzerolabs/lz-evm-messagelib-v2/",
    "@layerzerolabs/oapp-evm/=lib/OAppAuth/lib/devtools/packages/oapp-evm/",
    "@lz-oapp-evm/=lib/OAppAuth/lib/LayerZero-V2/packages/layerzero-v2/evm/oapp/contracts/oapp/",
    "@sbu/=lib/OAppAuth/lib/solidity-bytes-utils/",
    "LayerZero-V2/=lib/OAppAuth/lib/",
    "OAppAuth/=lib/OAppAuth/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solidity-bytes-utils/=lib/OAppAuth/node_modules/solidity-bytes-utils/",
    "solmate/=lib/solmate/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "shanghai",
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"initialOwner","type":"address"},{"internalType":"address","name":"superUSD_","type":"address"},{"internalType":"address","name":"sSuperUSD_","type":"address"},{"internalType":"address","name":"superUSDAtomicQueue_","type":"address"},{"internalType":"address","name":"sSuperUSDAtomicQueue_","type":"address"},{"internalType":"address","name":"superUSDTeller_","type":"address"},{"internalType":"address","name":"sSuperUSDTeller_","type":"address"},{"internalType":"address","name":"atomicSolver_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidDeadline","type":"error"},{"inputs":[],"name":"NoTokensReceived","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"TransferFailed","type":"error"},{"inputs":[],"name":"UnauthorizedZapCancellation","type":"error"},{"inputs":[],"name":"ZapRequestNotFound","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"requestId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"offerAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"offer","type":"address"},{"indexed":false,"internalType":"address","name":"want","type":"address"}],"name":"ZapWithdrawRequestCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"requestId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"sSuperUSDAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"superUSDAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"offer","type":"address"},{"indexed":false,"internalType":"address","name":"want","type":"address"},{"indexed":false,"internalType":"uint64","name":"deadline","type":"uint64"}],"name":"ZapWithdrawRequestCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"requestId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"offerAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"wantAmount","type":"uint256"},{"indexed":false,"internalType":"address","name":"offer","type":"address"},{"indexed":false,"internalType":"address","name":"want","type":"address"}],"name":"ZapWithdrawRequestSolved","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"deadline","type":"uint64"},{"internalType":"uint64","name":"creationTime","type":"uint64"},{"internalType":"uint96","name":"offerAmount","type":"uint96"},{"internalType":"uint256","name":"minimumAssetsOut","type":"uint256"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"offer","type":"address"},{"internalType":"address","name":"want","type":"address"}],"internalType":"struct ZapAtomicRequest","name":"zapRequest","type":"tuple"}],"name":"cancelByZap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"deadline","type":"uint64"},{"internalType":"uint64","name":"creationTime","type":"uint64"},{"internalType":"uint96","name":"offerAmount","type":"uint96"},{"internalType":"uint256","name":"minimumAssetsOut","type":"uint256"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"offer","type":"address"},{"internalType":"address","name":"want","type":"address"}],"internalType":"struct ZapAtomicRequest[]","name":"zapRequests","type":"tuple[]"}],"name":"cancelZapAtomicRequestByAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getExistingZapWithdrawRequestIds","outputs":[{"internalType":"bytes32[]","name":"","type":"bytes32[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getExistingZapWithdrawRequests","outputs":[{"internalType":"bytes32[]","name":"requestIds","type":"bytes32[]"},{"components":[{"internalType":"uint64","name":"deadline","type":"uint64"},{"internalType":"uint64","name":"creationTime","type":"uint64"},{"internalType":"uint96","name":"offerAmount","type":"uint96"},{"internalType":"uint256","name":"minimumAssetsOut","type":"uint256"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"offer","type":"address"},{"internalType":"address","name":"want","type":"address"}],"internalType":"struct ZapAtomicRequest[]","name":"requests","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"}],"name":"getZapAtomicRequestById","outputs":[{"components":[{"internalType":"uint64","name":"deadline","type":"uint64"},{"internalType":"uint64","name":"creationTime","type":"uint64"},{"internalType":"uint96","name":"offerAmount","type":"uint96"},{"internalType":"uint256","name":"minimumAssetsOut","type":"uint256"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"offer","type":"address"},{"internalType":"address","name":"want","type":"address"}],"internalType":"struct ZapAtomicRequest","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"getZapExistingWithdrawRequestsByUser","outputs":[{"internalType":"bytes32[]","name":"requestIds","type":"bytes32[]"},{"components":[{"internalType":"uint64","name":"deadline","type":"uint64"},{"internalType":"uint64","name":"creationTime","type":"uint64"},{"internalType":"uint96","name":"offerAmount","type":"uint96"},{"internalType":"uint256","name":"minimumAssetsOut","type":"uint256"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"offer","type":"address"},{"internalType":"address","name":"want","type":"address"}],"internalType":"struct ZapAtomicRequest[]","name":"requests","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"internalType":"struct Ownable2StepWTR.RescueTokenParam[]","name":"params","type":"tuple[]"}],"name":"rescueTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sSuperUSD","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sSuperUSDAtomicQueue","outputs":[{"internalType":"contract AtomicQueue","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sSuperUSDTeller","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"deadline","type":"uint64"},{"internalType":"uint64","name":"creationTime","type":"uint64"},{"internalType":"uint96","name":"offerAmount","type":"uint96"},{"internalType":"uint256","name":"minimumAssetsOut","type":"uint256"},{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"offer","type":"address"},{"internalType":"address","name":"want","type":"address"}],"internalType":"struct ZapAtomicRequest","name":"zapRequest","type":"tuple"}],"name":"solveByZap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"superUSD","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"superUSDAtomicQueue","outputs":[{"internalType":"contract AtomicQueue","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"superUSDSolver","outputs":[{"internalType":"contract AtomicSolverV4","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"superUSDTeller","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"sSuperUSDAmount","type":"uint256"},{"internalType":"address","name":"wantAsset","type":"address"},{"internalType":"uint256","name":"minimumAssetsOut","type":"uint256"},{"internalType":"uint64","name":"deadline","type":"uint64"}],"name":"unstakeAndWithdraw","outputs":[{"internalType":"bytes32","name":"requestId","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"}]

610160604052600160025534801562000016575f80fd5b5060405162002e7538038062002e75833981016040819052620000399162000557565b87806001600160a01b0381166200006a57604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b6200007581620001a6565b50506001600160a01b03881615806200009557506001600160a01b038716155b80620000a857506001600160a01b038616155b80620000bb57506001600160a01b038516155b80620000ce57506001600160a01b038416155b80620000e157506001600160a01b038216155b80620000f457506001600160a01b038316155b806200010757506001600160a01b038116155b15620001265760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0380861660805284811660a081905288821660c05287821660e0528482166101005283821661012052908216610140526200016c9087905f19620001c4565b62000182876080515f19620001c460201b60201c565b620001988760e0515f19620001c460201b60201c565b505050505050505062000649565b600180546001600160a01b0319169055620001c1816200028f565b50565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b0390811663095ea7b360e01b179091526200021e9085908390620002de16565b6200028957604080516001600160a01b03851660248201525f6044808301919091528251808303909101815260649091019091526020810180516001600160e01b0390811663095ea7b360e01b179091526200027d9186916200038816565b62000289848262000388565b50505050565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f805f846001600160a01b031684604051620002fb9190620005fa565b5f604051808303815f865af19150503d805f811462000336576040519150601f19603f3d011682016040523d82523d5f602084013e6200033b565b606091505b5091509150818015620003695750805115806200036957508080602001905181019062000369919062000628565b80156200037f57505f856001600160a01b03163b115b95945050505050565b5f6200039e6001600160a01b03841683620003f5565b905080515f14158015620003c5575080806020019051810190620003c3919062000628565b155b15620003f057604051635274afe760e01b81526001600160a01b038416600482015260240162000061565b505050565b60606200040483835f6200040b565b9392505050565b606081471015620004325760405163cd78605960e01b815230600482015260240162000061565b5f80856001600160a01b031684866040516200044f9190620005fa565b5f6040518083038185875af1925050503d805f81146200048b576040519150601f19603f3d011682016040523d82523d5f602084013e62000490565b606091505b509092509050620004a3868383620004ad565b9695505050505050565b606082620004c657620004c08262000511565b62000404565b8151158015620004de57506001600160a01b0384163b155b156200050957604051639996b31560e01b81526001600160a01b038516600482015260240162000061565b508062000404565b805115620005225780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b80516001600160a01b038116811462000552575f80fd5b919050565b5f805f805f805f80610100898b03121562000570575f80fd5b6200057b896200053b565b97506200058b60208a016200053b565b96506200059b60408a016200053b565b9550620005ab60608a016200053b565b9450620005bb60808a016200053b565b9350620005cb60a08a016200053b565b9250620005db60c08a016200053b565b9150620005eb60e08a016200053b565b90509295985092959890939650565b5f82515f5b818110156200061b5760208186018101518583015201620005ff565b505f920191825250919050565b5f6020828403121562000639575f80fd5b8151801515811462000404575f80fd5b60805160a05160c05160e051610100516101205161014051612740620007355f395f818161034301526117a101525f81816102f80152818161054b01528181610cc6015261139401525f81816101a201526117f901525f818161024d015281816104ae015281816104ec01528181610c4801528181610da801528181610e22015281816113160152818161147601526114f001525f8181610163015281816105140152818161062e015281816107a6015261086601525f8181610226015261057401525f81816101de015281816107e001528181610bbb0152818161128901526117ce01526127405ff3fe608060405234801561000f575f80fd5b5060043610610131575f3560e01c8063715018a6116100b457806398aa943a1161007957806398aa943a146102e0578063c79a7666146102f3578063dd0e27b91461031a578063e30c39781461032d578063e670be251461033e578063f2fde38b14610365575f80fd5b8063715018a61461029a57806379ba5097146102a25780638da5cb5b146102aa5780638e868683146102ba57806395f4f8b5146102cd575f80fd5b80633a5bcbf2116100fa5780633a5bcbf2146102005780634d78286114610221578063534a25b4146102485780635c6050201461026f578063611d41f214610285575f80fd5b80620f796414610135578063110ba08f1461015e5780631e5d80381461019d57806326c3eed2146101c45780632dedcedf146101d9575b5f80fd5b6101486101433660046121a1565b610378565b6040516101559190612238565b60405180910390f35b6101857f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b039091168152602001610155565b6101857f000000000000000000000000000000000000000000000000000000000000000081565b6101cc610418565b6040516101559190612280565b6101857f000000000000000000000000000000000000000000000000000000000000000081565b61021361020e3660046122c3565b610429565b604051908152602001610155565b6101857f000000000000000000000000000000000000000000000000000000000000000081565b6101857f000000000000000000000000000000000000000000000000000000000000000081565b6102776108ea565b604051610155929190612306565b610298610293366004612366565b610a38565b005b610298610ee8565b610298610efb565b5f546001600160a01b0316610185565b6102776102c836600461237d565b610f3f565b6102986102db366004612396565b611110565b6102986102ee366004612366565b6115c4565b6101857f000000000000000000000000000000000000000000000000000000000000000081565b610298610328366004612404565b6119d2565b6001546001600160a01b0316610185565b6101857f000000000000000000000000000000000000000000000000000000000000000081565b61029861037336600461237d565b611ad5565b61038061215e565b505f9081526005602081815260409283902083516101008101855281546001600160401b038082168352600160401b82041693820193909352600160801b9092046001600160601b0316938201939093526001830154606082015260028301546001600160a01b0390811660808301526003840154811660a08301526004840154811660c0830152929091015490911660e082015290565b60606104246003611b45565b905090565b5f6002546001146104555760405162461bcd60e51b815260040161044c90612460565b60405180910390fd5b60028055426001600160401b0383161161048257604051631da7447960e21b815260040160405180910390fd5b6001600160a01b0384166104a95760405163e6c4247b60e01b815260040160405180910390fd5b6104d57f0000000000000000000000000000000000000000000000000000000000000000333088611b58565b6040516366f9863d60e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f000000000000000000000000000000000000000000000000000000000000000081166024830152604482018790525f606483018190527f000000000000000000000000000000000000000000000000000000000000000082166084840152917f00000000000000000000000000000000000000000000000000000000000000009091169063cdf30c7a9060a4016020604051808303815f875af11580156105bc573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105e09190612484565b60408051610100810182526001600160401b03868116825242166020808301919091526001600160601b03841682840152606082018890523060808301523360a08301526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660c0840152891660e083015291519293509161066d91839101612238565b60408051601f1981840301815291905280516020909101209250610692600384611bc5565b505f838152600560208181526040928390208451815486840151878701516001600160401b039384166fffffffffffffffffffffffffffffffff1990931692909217600160401b91841691909102176bffffffffffffffffffffffff60801b1916600160801b6001600160601b039283160217835560608088015160018501556080808901516002860180546001600160a01b03199081166001600160a01b039384161790915560a0808c0151600389018054841691851691909117905560c0808d01516004808b01805486169287169290921790915560e08e015199909b0180549093169884169890981790915589519687018a528d8616875242909516968601969096529189168488015230908401527f00000000000000000000000000000000000000000000000000000000000000008416908301528a831690820152925163062f551160e01b81527f00000000000000000000000000000000000000000000000000000000000000009091169163062f551191610815918591016124fa565b6020604051808303815f875af1158015610831573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108559190612484565b5060408051898152602081018590527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0390811682840152891660608201526001600160401b03871660808201529051339186917f0c679deac13aefadec8860041b13bfcde474795dd659228c4b3fba3a448abb8c9181900360a00190a35050600160025550949350505050565b6060806108f5610418565b8051909250806001600160401b0381111561091257610912612508565b60405190808252806020026020018201604052801561094b57816020015b61093861215e565b8152602001906001900390816109305790505b5091505f5b81811015610a325760055f85838151811061096d5761096d61251c565b60209081029190910181015182528181019290925260409081015f2081516101008101835281546001600160401b038082168352600160401b82041694820194909452600160801b9093046001600160601b0316918301919091526001810154606083015260028101546001600160a01b0390811660808401526003820154811660a08401526004820154811660c08401526005909101541660e08201528351849083908110610a1f57610a1f61251c565b6020908102919091010152600101610950565b50509091565b600254600114610a5a5760405162461bcd60e51b815260040161044c90612460565b6002805533610a6f60c0830160a0840161237d565b6001600160a01b031614610a9657604051636543f89560e01b815260040160405180910390fd5b5f81604051602001610aa89190612546565b60408051601f1981840301815291905280516020909101209050610acd600382611bd9565b610aea5760405163d393393360e01b815260040160405180910390fd5b610af5600382611bf0565b506040805160c081019091525f9080610b116020860186612606565b6001600160401b03168152602001846020016020810190610b329190612606565b6001600160401b03168152602001610b50606086016040870161261f565b6001600160601b03168152602001610b6e60a086016080870161237d565b6001600160a01b03168152602001610b8c60e0860160c0870161237d565b6001600160a01b03168152602001610bab610100860160e0870161237d565b6001600160a01b031681525090507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e09bd8e9826040518263ffffffff1660e01b8152600401610c0591906124fa565b5f604051808303815f87803b158015610c1c575f80fd5b505af1158015610c2e573d5f803e3d5ffd5b50506040516370a0823160e01b81523060048201525f92507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691506370a0823190602401602060405180830381865afa158015610c96573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cba9190612484565b90506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016630efe6a8b610cfb60e0870160c0880161237d565b610d0b606088016040890161261f565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526001600160601b031660248201525f60448201526064016020604051808303815f875af1158015610d62573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d869190612484565b506040516370a0823160e01b81523060048201525f9082906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a0823190602401602060405180830381865afa158015610ded573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e119190612484565b610e1b919061264c565b9050610e577f0000000000000000000000000000000000000000000000000000000000000000610e5160c0880160a0890161237d565b83611bfb565b610e6760c0860160a0870161237d565b6001600160a01b0316847f8d232a6d8b11fa3030da0de7e73ef3ef70a8e8147cc6e8be31609c896869b62183610ea360e08a0160c08b0161237d565b610eb46101008b0160e08c0161237d565b604080519384526001600160a01b03928316602085015291169082015260600160405180910390a350506001600255505050565b610ef0611c2c565b610ef95f611c58565b565b60015433906001600160a01b03168114610f335760405163118cdaa760e01b81526001600160a01b038216600482015260240161044c565b610f3c81611c58565b50565b6060805f610f4d6003611b45565b8051909150806001600160401b03811115610f6a57610f6a612508565b604051908082528060200260200182016040528015610f93578160200160208202803683370190505b509350806001600160401b03811115610fae57610fae612508565b604051908082528060200260200182016040528015610fe757816020015b610fd461215e565b815260200190600190039081610fcc5790505b5092505f805b82811015611101575f8482815181106110085761100861251c565b6020908102919091018101515f818152600580845260409182902082516101008101845281546001600160401b038082168352600160401b82041696820196909652600160801b9095046001600160601b0316928501929092526001820154606085015260028201546001600160a01b0390811660808601526003830154811660a086018190526004840154821660c08701529290910154811660e0850152919350908a1690036110f757818885815181106110c6576110c661251c565b602002602001018181525050808785815181106110e5576110e561251c565b60200260200101819052508360010193505b5050600101610fed565b50808552808452505050915091565b611118611c2c565b60025460011461113a5760405162461bcd60e51b815260040161044c90612460565b600280555f5b818110156115ba573683838381811061115b5761115b61251c565b9050610100020190505f816040516020016111769190612546565b60408051601f198184030181529190528051602090910120905061119b600382611bd9565b6111b85760405163d393393360e01b815260040160405180910390fd5b6111c3600382611bf0565b506040805160c081019091525f90806111df6020860186612606565b6001600160401b031681526020018460200160208101906112009190612606565b6001600160401b0316815260200161121e606086016040870161261f565b6001600160601b0316815260200161123c60a086016080870161237d565b6001600160a01b0316815260200161125a60e0860160c0870161237d565b6001600160a01b03168152602001611279610100860160e0870161237d565b6001600160a01b031681525090507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e09bd8e9826040518263ffffffff1660e01b81526004016112d391906124fa565b5f604051808303815f87803b1580156112ea575f80fd5b505af11580156112fc573d5f803e3d5ffd5b50506040516370a0823160e01b81523060048201525f92507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031691506370a0823190602401602060405180830381865afa158015611364573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113889190612484565b90506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016630efe6a8b6113c960e0870160c0880161237d565b6113d9606088016040890161261f565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526001600160601b031660248201525f60448201526064016020604051808303815f875af1158015611430573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114549190612484565b506040516370a0823160e01b81523060048201525f9082906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a0823190602401602060405180830381865afa1580156114bb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114df9190612484565b6114e9919061264c565b905061151f7f0000000000000000000000000000000000000000000000000000000000000000610e5160c0880160a0890161237d565b61152f60c0860160a0870161237d565b6001600160a01b0316847f8d232a6d8b11fa3030da0de7e73ef3ef70a8e8147cc6e8be31609c896869b6218361156b60e08a0160c08b0161237d565b61157c6101008b0160e08c0161237d565b604080519384526001600160a01b03928316602085015291169082015260600160405180910390a35050505050806115b39061265f565b9050611140565b5050600160025550565b6002546001146115e65760405162461bcd60e51b815260040161044c90612460565b600280556040515f906115fd908390602001612546565b60408051601f1981840301815291905280516020909101209050611622600382611bd9565b61163f5760405163d393393360e01b815260040160405180910390fd5b61164a600382611bf0565b506040805160c081019091525f90806116666020860186612606565b6001600160401b031681526020018460200160208101906116879190612606565b6001600160401b031681526020016116a5606086016040870161261f565b6001600160601b031681526020016116c360a086016080870161237d565b6001600160a01b031681526020016116e160e0860160c0870161237d565b6001600160a01b03168152602001611700610100860160e0870161237d565b6001600160a01b0316905290505f61171f610100850160e0860161237d565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015611763573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117879190612484565b6040516360abb91160e01b81529091506001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906360abb91190611823907f0000000000000000000000000000000000000000000000000000000000000000906060890135905f19907f0000000000000000000000000000000000000000000000000000000000000000908990600401612677565b5f604051808303815f87803b15801561183a575f80fd5b505af115801561184c573d5f803e3d5ffd5b505f9250611864915050610100860160e0870161237d565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa1580156118a8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118cc9190612484565b90505f6118d9838361264c565b9050805f036118fb57604051639671a89f60e01b815260040160405180910390fd5b61191f61190f610100880160e0890161237d565b610e5160c0890160a08a0161237d565b61192f60c0870160a0880161237d565b6001600160a01b0316857ffa71f2880df1dd2e3bb1419d54e01d8769d6fd20b59f539879e936b26f4638e161196a60608a0160408b0161261f565b8461197b60e08c0160c08d0161237d565b61198c6101008d0160e08e0161237d565b604080516001600160601b0395909516855260208501939093526001600160a01b0391821684840152166060830152519081900360800190a35050600160025550505050565b6119da611c2c565b5f5b81811015611ad0575f8383838181106119f7576119f761251c565b611a0d926020606090920201908101915061237d565b90506001600160a01b038116611a7057611a6b848484818110611a3257611a3261251c565b9050606002016040016020810190611a4a919061237d565b858585818110611a5c57611a5c61251c565b90506060020160200135611c71565b611abf565b611abf81858585818110611a8657611a8661251c565b90506060020160200135868686818110611aa257611aa261251c565b9050606002016040016020810190611aba919061237d565b611d04565b50611ac98161265f565b90506119dc565b505050565b611add611c2c565b600180546001600160a01b0383166001600160a01b03199091168117909155611b0d5f546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b60605f611b5183611de3565b9392505050565b6040516001600160a01b038481166024830152838116604483015260648201839052611bbf9186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611e3c565b50505050565b5f611bd08383611e9d565b90505b92915050565b5f8181526001830160205260408120541515611bd0565b5f611bd08383611ee9565b6040516001600160a01b03838116602483015260448201839052611ad091859182169063a9059cbb90606401611b8d565b5f546001600160a01b03163314610ef95760405163118cdaa760e01b815233600482015260240161044c565b600180546001600160a01b0319169055610f3c81611fd3565b80471015611c945760405163cd78605960e01b815230600482015260240161044c565b5f826001600160a01b0316826040515f6040518083038185875af1925050503d805f8114611cdd576040519150601f19603f3d011682016040523d82523d5f602084013e611ce2565b606091505b5050905080611ad057604051630a12f52160e11b815260040160405180910390fd5b6040516001600160a01b0382166024820152604481018390525f90611d5790859060640160408051601f198184030181529190526020810180516001600160e01b031663a9059cbb60e01b179052612022565b90508015611d655750505050565b6040513060248201526001600160a01b038316604482015260648101849052611dbc90859060840160408051601f198184030181529190526020810180516001600160e01b03166323b872dd60e01b179052612022565b90508015611dca5750505050565b6040516312171d8360e31b815260040160405180910390fd5b6060815f01805480602002602001604051908101604052809291908181526020018280548015611e3057602002820191905f5260205f20905b815481526020019060010190808311611e1c575b50505050509050919050565b5f611e506001600160a01b0384168361206b565b905080515f14158015611e74575080806020019051810190611e7291906126ab565b155b15611ad057604051635274afe760e01b81526001600160a01b038416600482015260240161044c565b5f818152600183016020526040812054611ee257508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155611bd3565b505f611bd3565b5f8181526001830160205260408120548015611fc3575f611f0b60018361264c565b85549091505f90611f1e9060019061264c565b9050808214611f7d575f865f018281548110611f3c57611f3c61251c565b905f5260205f200154905080875f018481548110611f5c57611f5c61251c565b5f918252602080832090910192909255918252600188019052604090208390555b8554869080611f8e57611f8e6126ca565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050611bd3565b5f915050611bd3565b5092915050565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f805f8060205f8651602088015f8a5af192503d91505f519050828015612061575081156120535780600114612061565b5f866001600160a01b03163b115b9695505050505050565b6060611bd083835f845f80856001600160a01b0316848660405161208f91906126de565b5f6040518083038185875af1925050503d805f81146120c9576040519150601f19603f3d011682016040523d82523d5f602084013e6120ce565b606091505b50915091506120618683836060826120ee576120e982612135565b611b51565b815115801561210557506001600160a01b0384163b155b1561212e57604051639996b31560e01b81526001600160a01b038516600482015260240161044c565b5080611b51565b8051156121455780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60408051610100810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915290565b5f602082840312156121b1575f80fd5b5035919050565b6001600160401b03808251168352806020830151166020840152506001600160601b03604082015116604083015260608101516060830152608081015160018060a01b0380821660808501528060a08401511660a08501528060c08401511660c0850152505060e0810151611ad060e08401826001600160a01b03169052565b6101008101611bd382846121b8565b5f8151808452602080850194508084015f5b8381101561227557815187529582019590820190600101612259565b509495945050505050565b602081525f611bd06020830184612247565b80356001600160a01b03811681146122a8575f80fd5b919050565b80356001600160401b03811681146122a8575f80fd5b5f805f80608085870312156122d6575f80fd5b843593506122e660208601612292565b9250604085013591506122fb606086016122ad565b905092959194509250565b604081525f6123186040830185612247565b8281036020848101919091528451808352858201928201905f5b81811015612359576123458386516121b8565b938301936101009290920191600101612332565b5090979650505050505050565b5f6101008284031215612377575f80fd5b50919050565b5f6020828403121561238d575f80fd5b611bd082612292565b5f80602083850312156123a7575f80fd5b82356001600160401b03808211156123bd575f80fd5b818501915085601f8301126123d0575f80fd5b8135818111156123de575f80fd5b8660208260081b85010111156123f2575f80fd5b60209290920196919550909350505050565b5f8060208385031215612415575f80fd5b82356001600160401b038082111561242b575f80fd5b818501915085601f83011261243e575f80fd5b81358181111561244c575f80fd5b8660206060830285010111156123f2575f80fd5b6020808252600a90820152695245454e5452414e435960b01b604082015260600190565b5f60208284031215612494575f80fd5b5051919050565b80516001600160401b039081168352602080830151909116908301526040808201516001600160601b0316908301526060808201516001600160a01b039081169184019190915260808083015182169084015260a09182015116910152565b60c08101611bd3828461249b565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b80356001600160601b03811681146122a8575f80fd5b61010081016001600160401b038061255d856122ad565b1683528061256d602086016122ad565b166020840152506001600160601b0361258860408501612530565b166040830152606083810135908301526001600160a01b036125ac60808501612292565b1660808301526125be60a08401612292565b6001600160a01b031660a08301526125d860c08401612292565b6001600160a01b031660c08301526125f260e08401612292565b6001600160a01b03811660e0840152611fcc565b5f60208284031215612616575f80fd5b611bd0826122ad565b5f6020828403121561262f575f80fd5b611bd082612530565b634e487b7160e01b5f52601160045260245ffd5b81810381811115611bd357611bd3612638565b5f6001820161267057612670612638565b5060010190565b6001600160a01b0386811682526020820186905260408201859052831660608201526101408101612061608083018461249b565b5f602082840312156126bb575f80fd5b81518015158114611b51575f80fd5b634e487b7160e01b5f52603160045260245ffd5b5f82515f5b818110156126fd57602081860181015185830152016126e3565b505f92019182525091905056fea2646970667358221220f72b50bddcd991a193b6f056c8ca90380628d9e3ac223728cb63c5becf77066264736f6c634300081500330000000000000000000000008ab8aeef444aee718a275a8325795fe90cf162c400000000000000000000000015f3ee2f609fbae0bc48e3a071d66dd917c682eb000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd000000000000000000000000f3aa6324aa5c9ded16eb7ed651152ac30588bac1000000000000000000000000d484d2991d168b33cc61e25f80af0145883bc465000000000000000000000000f62d61f304c9c65c96a94c2b0b93c8f93c96e91d000000000000000000000000a8aa5c00d6c3f7a77fc5769770f6bc7b9244699b0000000000000000000000001db629316b3fb6b026f9ebd5c379a72235a4d5e9

Deployed Bytecode

0x608060405234801561000f575f80fd5b5060043610610131575f3560e01c8063715018a6116100b457806398aa943a1161007957806398aa943a146102e0578063c79a7666146102f3578063dd0e27b91461031a578063e30c39781461032d578063e670be251461033e578063f2fde38b14610365575f80fd5b8063715018a61461029a57806379ba5097146102a25780638da5cb5b146102aa5780638e868683146102ba57806395f4f8b5146102cd575f80fd5b80633a5bcbf2116100fa5780633a5bcbf2146102005780634d78286114610221578063534a25b4146102485780635c6050201461026f578063611d41f214610285575f80fd5b80620f796414610135578063110ba08f1461015e5780631e5d80381461019d57806326c3eed2146101c45780632dedcedf146101d9575b5f80fd5b6101486101433660046121a1565b610378565b6040516101559190612238565b60405180910390f35b6101857f00000000000000000000000015f3ee2f609fbae0bc48e3a071d66dd917c682eb81565b6040516001600160a01b039091168152602001610155565b6101857f000000000000000000000000f62d61f304c9c65c96a94c2b0b93c8f93c96e91d81565b6101cc610418565b6040516101559190612280565b6101857f000000000000000000000000f3aa6324aa5c9ded16eb7ed651152ac30588bac181565b61021361020e3660046122c3565b610429565b604051908152602001610155565b6101857f000000000000000000000000d484d2991d168b33cc61e25f80af0145883bc46581565b6101857f000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd81565b6102776108ea565b604051610155929190612306565b610298610293366004612366565b610a38565b005b610298610ee8565b610298610efb565b5f546001600160a01b0316610185565b6102776102c836600461237d565b610f3f565b6102986102db366004612396565b611110565b6102986102ee366004612366565b6115c4565b6101857f000000000000000000000000a8aa5c00d6c3f7a77fc5769770f6bc7b9244699b81565b610298610328366004612404565b6119d2565b6001546001600160a01b0316610185565b6101857f0000000000000000000000001db629316b3fb6b026f9ebd5c379a72235a4d5e981565b61029861037336600461237d565b611ad5565b61038061215e565b505f9081526005602081815260409283902083516101008101855281546001600160401b038082168352600160401b82041693820193909352600160801b9092046001600160601b0316938201939093526001830154606082015260028301546001600160a01b0390811660808301526003840154811660a08301526004840154811660c0830152929091015490911660e082015290565b60606104246003611b45565b905090565b5f6002546001146104555760405162461bcd60e51b815260040161044c90612460565b60405180910390fd5b60028055426001600160401b0383161161048257604051631da7447960e21b815260040160405180910390fd5b6001600160a01b0384166104a95760405163e6c4247b60e01b815260040160405180910390fd5b6104d57f000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd333088611b58565b6040516366f9863d60e11b81526001600160a01b037f000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd811660048301527f00000000000000000000000015f3ee2f609fbae0bc48e3a071d66dd917c682eb81166024830152604482018790525f606483018190527f000000000000000000000000a8aa5c00d6c3f7a77fc5769770f6bc7b9244699b82166084840152917f000000000000000000000000d484d2991d168b33cc61e25f80af0145883bc4659091169063cdf30c7a9060a4016020604051808303815f875af11580156105bc573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105e09190612484565b60408051610100810182526001600160401b03868116825242166020808301919091526001600160601b03841682840152606082018890523060808301523360a08301526001600160a01b037f00000000000000000000000015f3ee2f609fbae0bc48e3a071d66dd917c682eb811660c0840152891660e083015291519293509161066d91839101612238565b60408051601f1981840301815291905280516020909101209250610692600384611bc5565b505f838152600560208181526040928390208451815486840151878701516001600160401b039384166fffffffffffffffffffffffffffffffff1990931692909217600160401b91841691909102176bffffffffffffffffffffffff60801b1916600160801b6001600160601b039283160217835560608088015160018501556080808901516002860180546001600160a01b03199081166001600160a01b039384161790915560a0808c0151600389018054841691851691909117905560c0808d01516004808b01805486169287169290921790915560e08e015199909b0180549093169884169890981790915589519687018a528d8616875242909516968601969096529189168488015230908401527f00000000000000000000000015f3ee2f609fbae0bc48e3a071d66dd917c682eb8416908301528a831690820152925163062f551160e01b81527f000000000000000000000000f3aa6324aa5c9ded16eb7ed651152ac30588bac19091169163062f551191610815918591016124fa565b6020604051808303815f875af1158015610831573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108559190612484565b5060408051898152602081018590527f00000000000000000000000015f3ee2f609fbae0bc48e3a071d66dd917c682eb6001600160a01b0390811682840152891660608201526001600160401b03871660808201529051339186917f0c679deac13aefadec8860041b13bfcde474795dd659228c4b3fba3a448abb8c9181900360a00190a35050600160025550949350505050565b6060806108f5610418565b8051909250806001600160401b0381111561091257610912612508565b60405190808252806020026020018201604052801561094b57816020015b61093861215e565b8152602001906001900390816109305790505b5091505f5b81811015610a325760055f85838151811061096d5761096d61251c565b60209081029190910181015182528181019290925260409081015f2081516101008101835281546001600160401b038082168352600160401b82041694820194909452600160801b9093046001600160601b0316918301919091526001810154606083015260028101546001600160a01b0390811660808401526003820154811660a08401526004820154811660c08401526005909101541660e08201528351849083908110610a1f57610a1f61251c565b6020908102919091010152600101610950565b50509091565b600254600114610a5a5760405162461bcd60e51b815260040161044c90612460565b6002805533610a6f60c0830160a0840161237d565b6001600160a01b031614610a9657604051636543f89560e01b815260040160405180910390fd5b5f81604051602001610aa89190612546565b60408051601f1981840301815291905280516020909101209050610acd600382611bd9565b610aea5760405163d393393360e01b815260040160405180910390fd5b610af5600382611bf0565b506040805160c081019091525f9080610b116020860186612606565b6001600160401b03168152602001846020016020810190610b329190612606565b6001600160401b03168152602001610b50606086016040870161261f565b6001600160601b03168152602001610b6e60a086016080870161237d565b6001600160a01b03168152602001610b8c60e0860160c0870161237d565b6001600160a01b03168152602001610bab610100860160e0870161237d565b6001600160a01b031681525090507f000000000000000000000000f3aa6324aa5c9ded16eb7ed651152ac30588bac16001600160a01b031663e09bd8e9826040518263ffffffff1660e01b8152600401610c0591906124fa565b5f604051808303815f87803b158015610c1c575f80fd5b505af1158015610c2e573d5f803e3d5ffd5b50506040516370a0823160e01b81523060048201525f92507f000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd6001600160a01b031691506370a0823190602401602060405180830381865afa158015610c96573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cba9190612484565b90506001600160a01b037f000000000000000000000000a8aa5c00d6c3f7a77fc5769770f6bc7b9244699b16630efe6a8b610cfb60e0870160c0880161237d565b610d0b606088016040890161261f565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526001600160601b031660248201525f60448201526064016020604051808303815f875af1158015610d62573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d869190612484565b506040516370a0823160e01b81523060048201525f9082906001600160a01b037f000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd16906370a0823190602401602060405180830381865afa158015610ded573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e119190612484565b610e1b919061264c565b9050610e577f000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd610e5160c0880160a0890161237d565b83611bfb565b610e6760c0860160a0870161237d565b6001600160a01b0316847f8d232a6d8b11fa3030da0de7e73ef3ef70a8e8147cc6e8be31609c896869b62183610ea360e08a0160c08b0161237d565b610eb46101008b0160e08c0161237d565b604080519384526001600160a01b03928316602085015291169082015260600160405180910390a350506001600255505050565b610ef0611c2c565b610ef95f611c58565b565b60015433906001600160a01b03168114610f335760405163118cdaa760e01b81526001600160a01b038216600482015260240161044c565b610f3c81611c58565b50565b6060805f610f4d6003611b45565b8051909150806001600160401b03811115610f6a57610f6a612508565b604051908082528060200260200182016040528015610f93578160200160208202803683370190505b509350806001600160401b03811115610fae57610fae612508565b604051908082528060200260200182016040528015610fe757816020015b610fd461215e565b815260200190600190039081610fcc5790505b5092505f805b82811015611101575f8482815181106110085761100861251c565b6020908102919091018101515f818152600580845260409182902082516101008101845281546001600160401b038082168352600160401b82041696820196909652600160801b9095046001600160601b0316928501929092526001820154606085015260028201546001600160a01b0390811660808601526003830154811660a086018190526004840154821660c08701529290910154811660e0850152919350908a1690036110f757818885815181106110c6576110c661251c565b602002602001018181525050808785815181106110e5576110e561251c565b60200260200101819052508360010193505b5050600101610fed565b50808552808452505050915091565b611118611c2c565b60025460011461113a5760405162461bcd60e51b815260040161044c90612460565b600280555f5b818110156115ba573683838381811061115b5761115b61251c565b9050610100020190505f816040516020016111769190612546565b60408051601f198184030181529190528051602090910120905061119b600382611bd9565b6111b85760405163d393393360e01b815260040160405180910390fd5b6111c3600382611bf0565b506040805160c081019091525f90806111df6020860186612606565b6001600160401b031681526020018460200160208101906112009190612606565b6001600160401b0316815260200161121e606086016040870161261f565b6001600160601b0316815260200161123c60a086016080870161237d565b6001600160a01b0316815260200161125a60e0860160c0870161237d565b6001600160a01b03168152602001611279610100860160e0870161237d565b6001600160a01b031681525090507f000000000000000000000000f3aa6324aa5c9ded16eb7ed651152ac30588bac16001600160a01b031663e09bd8e9826040518263ffffffff1660e01b81526004016112d391906124fa565b5f604051808303815f87803b1580156112ea575f80fd5b505af11580156112fc573d5f803e3d5ffd5b50506040516370a0823160e01b81523060048201525f92507f000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd6001600160a01b031691506370a0823190602401602060405180830381865afa158015611364573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906113889190612484565b90506001600160a01b037f000000000000000000000000a8aa5c00d6c3f7a77fc5769770f6bc7b9244699b16630efe6a8b6113c960e0870160c0880161237d565b6113d9606088016040890161261f565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526001600160601b031660248201525f60448201526064016020604051808303815f875af1158015611430573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114549190612484565b506040516370a0823160e01b81523060048201525f9082906001600160a01b037f000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd16906370a0823190602401602060405180830381865afa1580156114bb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114df9190612484565b6114e9919061264c565b905061151f7f000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd610e5160c0880160a0890161237d565b61152f60c0860160a0870161237d565b6001600160a01b0316847f8d232a6d8b11fa3030da0de7e73ef3ef70a8e8147cc6e8be31609c896869b6218361156b60e08a0160c08b0161237d565b61157c6101008b0160e08c0161237d565b604080519384526001600160a01b03928316602085015291169082015260600160405180910390a35050505050806115b39061265f565b9050611140565b5050600160025550565b6002546001146115e65760405162461bcd60e51b815260040161044c90612460565b600280556040515f906115fd908390602001612546565b60408051601f1981840301815291905280516020909101209050611622600382611bd9565b61163f5760405163d393393360e01b815260040160405180910390fd5b61164a600382611bf0565b506040805160c081019091525f90806116666020860186612606565b6001600160401b031681526020018460200160208101906116879190612606565b6001600160401b031681526020016116a5606086016040870161261f565b6001600160601b031681526020016116c360a086016080870161237d565b6001600160a01b031681526020016116e160e0860160c0870161237d565b6001600160a01b03168152602001611700610100860160e0870161237d565b6001600160a01b0316905290505f61171f610100850160e0860161237d565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015611763573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117879190612484565b6040516360abb91160e01b81529091506001600160a01b037f0000000000000000000000001db629316b3fb6b026f9ebd5c379a72235a4d5e916906360abb91190611823907f000000000000000000000000f3aa6324aa5c9ded16eb7ed651152ac30588bac1906060890135905f19907f000000000000000000000000f62d61f304c9c65c96a94c2b0b93c8f93c96e91d908990600401612677565b5f604051808303815f87803b15801561183a575f80fd5b505af115801561184c573d5f803e3d5ffd5b505f9250611864915050610100860160e0870161237d565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa1580156118a8573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118cc9190612484565b90505f6118d9838361264c565b9050805f036118fb57604051639671a89f60e01b815260040160405180910390fd5b61191f61190f610100880160e0890161237d565b610e5160c0890160a08a0161237d565b61192f60c0870160a0880161237d565b6001600160a01b0316857ffa71f2880df1dd2e3bb1419d54e01d8769d6fd20b59f539879e936b26f4638e161196a60608a0160408b0161261f565b8461197b60e08c0160c08d0161237d565b61198c6101008d0160e08e0161237d565b604080516001600160601b0395909516855260208501939093526001600160a01b0391821684840152166060830152519081900360800190a35050600160025550505050565b6119da611c2c565b5f5b81811015611ad0575f8383838181106119f7576119f761251c565b611a0d926020606090920201908101915061237d565b90506001600160a01b038116611a7057611a6b848484818110611a3257611a3261251c565b9050606002016040016020810190611a4a919061237d565b858585818110611a5c57611a5c61251c565b90506060020160200135611c71565b611abf565b611abf81858585818110611a8657611a8661251c565b90506060020160200135868686818110611aa257611aa261251c565b9050606002016040016020810190611aba919061237d565b611d04565b50611ac98161265f565b90506119dc565b505050565b611add611c2c565b600180546001600160a01b0383166001600160a01b03199091168117909155611b0d5f546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b60605f611b5183611de3565b9392505050565b6040516001600160a01b038481166024830152838116604483015260648201839052611bbf9186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611e3c565b50505050565b5f611bd08383611e9d565b90505b92915050565b5f8181526001830160205260408120541515611bd0565b5f611bd08383611ee9565b6040516001600160a01b03838116602483015260448201839052611ad091859182169063a9059cbb90606401611b8d565b5f546001600160a01b03163314610ef95760405163118cdaa760e01b815233600482015260240161044c565b600180546001600160a01b0319169055610f3c81611fd3565b80471015611c945760405163cd78605960e01b815230600482015260240161044c565b5f826001600160a01b0316826040515f6040518083038185875af1925050503d805f8114611cdd576040519150601f19603f3d011682016040523d82523d5f602084013e611ce2565b606091505b5050905080611ad057604051630a12f52160e11b815260040160405180910390fd5b6040516001600160a01b0382166024820152604481018390525f90611d5790859060640160408051601f198184030181529190526020810180516001600160e01b031663a9059cbb60e01b179052612022565b90508015611d655750505050565b6040513060248201526001600160a01b038316604482015260648101849052611dbc90859060840160408051601f198184030181529190526020810180516001600160e01b03166323b872dd60e01b179052612022565b90508015611dca5750505050565b6040516312171d8360e31b815260040160405180910390fd5b6060815f01805480602002602001604051908101604052809291908181526020018280548015611e3057602002820191905f5260205f20905b815481526020019060010190808311611e1c575b50505050509050919050565b5f611e506001600160a01b0384168361206b565b905080515f14158015611e74575080806020019051810190611e7291906126ab565b155b15611ad057604051635274afe760e01b81526001600160a01b038416600482015260240161044c565b5f818152600183016020526040812054611ee257508154600181810184555f848152602080822090930184905584548482528286019093526040902091909155611bd3565b505f611bd3565b5f8181526001830160205260408120548015611fc3575f611f0b60018361264c565b85549091505f90611f1e9060019061264c565b9050808214611f7d575f865f018281548110611f3c57611f3c61251c565b905f5260205f200154905080875f018481548110611f5c57611f5c61251c565b5f918252602080832090910192909255918252600188019052604090208390555b8554869080611f8e57611f8e6126ca565b600190038181905f5260205f20015f90559055856001015f8681526020019081526020015f205f905560019350505050611bd3565b5f915050611bd3565b5092915050565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f805f8060205f8651602088015f8a5af192503d91505f519050828015612061575081156120535780600114612061565b5f866001600160a01b03163b115b9695505050505050565b6060611bd083835f845f80856001600160a01b0316848660405161208f91906126de565b5f6040518083038185875af1925050503d805f81146120c9576040519150601f19603f3d011682016040523d82523d5f602084013e6120ce565b606091505b50915091506120618683836060826120ee576120e982612135565b611b51565b815115801561210557506001600160a01b0384163b155b1561212e57604051639996b31560e01b81526001600160a01b038516600482015260240161044c565b5080611b51565b8051156121455780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60408051610100810182525f80825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915290565b5f602082840312156121b1575f80fd5b5035919050565b6001600160401b03808251168352806020830151166020840152506001600160601b03604082015116604083015260608101516060830152608081015160018060a01b0380821660808501528060a08401511660a08501528060c08401511660c0850152505060e0810151611ad060e08401826001600160a01b03169052565b6101008101611bd382846121b8565b5f8151808452602080850194508084015f5b8381101561227557815187529582019590820190600101612259565b509495945050505050565b602081525f611bd06020830184612247565b80356001600160a01b03811681146122a8575f80fd5b919050565b80356001600160401b03811681146122a8575f80fd5b5f805f80608085870312156122d6575f80fd5b843593506122e660208601612292565b9250604085013591506122fb606086016122ad565b905092959194509250565b604081525f6123186040830185612247565b8281036020848101919091528451808352858201928201905f5b81811015612359576123458386516121b8565b938301936101009290920191600101612332565b5090979650505050505050565b5f6101008284031215612377575f80fd5b50919050565b5f6020828403121561238d575f80fd5b611bd082612292565b5f80602083850312156123a7575f80fd5b82356001600160401b03808211156123bd575f80fd5b818501915085601f8301126123d0575f80fd5b8135818111156123de575f80fd5b8660208260081b85010111156123f2575f80fd5b60209290920196919550909350505050565b5f8060208385031215612415575f80fd5b82356001600160401b038082111561242b575f80fd5b818501915085601f83011261243e575f80fd5b81358181111561244c575f80fd5b8660206060830285010111156123f2575f80fd5b6020808252600a90820152695245454e5452414e435960b01b604082015260600190565b5f60208284031215612494575f80fd5b5051919050565b80516001600160401b039081168352602080830151909116908301526040808201516001600160601b0316908301526060808201516001600160a01b039081169184019190915260808083015182169084015260a09182015116910152565b60c08101611bd3828461249b565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b80356001600160601b03811681146122a8575f80fd5b61010081016001600160401b038061255d856122ad565b1683528061256d602086016122ad565b166020840152506001600160601b0361258860408501612530565b166040830152606083810135908301526001600160a01b036125ac60808501612292565b1660808301526125be60a08401612292565b6001600160a01b031660a08301526125d860c08401612292565b6001600160a01b031660c08301526125f260e08401612292565b6001600160a01b03811660e0840152611fcc565b5f60208284031215612616575f80fd5b611bd0826122ad565b5f6020828403121561262f575f80fd5b611bd082612530565b634e487b7160e01b5f52601160045260245ffd5b81810381811115611bd357611bd3612638565b5f6001820161267057612670612638565b5060010190565b6001600160a01b0386811682526020820186905260408201859052831660608201526101408101612061608083018461249b565b5f602082840312156126bb575f80fd5b81518015158114611b51575f80fd5b634e487b7160e01b5f52603160045260245ffd5b5f82515f5b818110156126fd57602081860181015185830152016126e3565b505f92019182525091905056fea2646970667358221220f72b50bddcd991a193b6f056c8ca90380628d9e3ac223728cb63c5becf77066264736f6c63430008150033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000008ab8aeef444aee718a275a8325795fe90cf162c400000000000000000000000015f3ee2f609fbae0bc48e3a071d66dd917c682eb000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd000000000000000000000000f3aa6324aa5c9ded16eb7ed651152ac30588bac1000000000000000000000000d484d2991d168b33cc61e25f80af0145883bc465000000000000000000000000f62d61f304c9c65c96a94c2b0b93c8f93c96e91d000000000000000000000000a8aa5c00d6c3f7a77fc5769770f6bc7b9244699b0000000000000000000000001db629316b3fb6b026f9ebd5c379a72235a4d5e9

-----Decoded View---------------
Arg [0] : initialOwner (address): 0x8Ab8aEEf444AeE718A275a8325795FE90CF162c4
Arg [1] : superUSD_ (address): 0x15f3Ee2F609FBAe0bC48E3a071D66DD917C682EB
Arg [2] : sSuperUSD_ (address): 0x139450C2dCeF827C9A2a0Bb1CB5506260940c9fd
Arg [3] : superUSDAtomicQueue_ (address): 0xf3aA6324Aa5C9Ded16Eb7ED651152aC30588BAc1
Arg [4] : sSuperUSDAtomicQueue_ (address): 0xd484d2991D168b33cC61e25f80af0145883Bc465
Arg [5] : superUSDTeller_ (address): 0xF62D61F304C9c65C96a94c2b0b93c8f93C96e91D
Arg [6] : sSuperUSDTeller_ (address): 0xa8aA5c00d6c3f7A77FC5769770f6bC7b9244699b
Arg [7] : atomicSolver_ (address): 0x1DB629316B3fB6B026f9ebD5c379a72235a4d5E9

-----Encoded View---------------
8 Constructor Arguments found :
Arg [0] : 0000000000000000000000008ab8aeef444aee718a275a8325795fe90cf162c4
Arg [1] : 00000000000000000000000015f3ee2f609fbae0bc48e3a071d66dd917c682eb
Arg [2] : 000000000000000000000000139450c2dcef827c9a2a0bb1cb5506260940c9fd
Arg [3] : 000000000000000000000000f3aa6324aa5c9ded16eb7ed651152ac30588bac1
Arg [4] : 000000000000000000000000d484d2991d168b33cc61e25f80af0145883bc465
Arg [5] : 000000000000000000000000f62d61f304c9c65c96a94c2b0b93c8f93c96e91d
Arg [6] : 000000000000000000000000a8aa5c00d6c3f7a77fc5769770f6bc7b9244699b
Arg [7] : 0000000000000000000000001db629316b3fb6b026f9ebd5c379a72235a4d5e9


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
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.