Skip to content
Verified contractExactMIT

GpPurchaserV3

Address0x0823fad0616093b9779657da8f053faab316dc4a
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
21,541,937
Creation transaction
0x80c36f8e66…82400006c2

src/GpPurchaserV3.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.20;

/** 
 *    $$\                           $$\                         
 *    $$ |                          $$ |                        
 *    $$ |      $$$$$$\   $$$$$$\ $$$$$$\    $$$$$$\  $$\   $$\ 
 *    $$ |     $$  __$$\ $$  __$$\\_$$  _|  $$  __$$\ \$$\ $$  |
 *    $$ |     $$ /  $$ |$$ /  $$ | $$ |    $$$$$$$$ | \$$$$  / 
 *    $$ |     $$ |  $$ |$$ |  $$ | $$ |$$\ $$   ____| $$  $$<  
 *    $$$$$$$$\\$$$$$$  |\$$$$$$  | \$$$$  |\$$$$$$$\ $$  /\$$\ 
 *    \________|\______/  \______/   \____/  \_______|\__/  \__|
*/       

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
// import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {IERC20Permit} from '@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol';
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IWrapNative.sol";
import "./IAggregator.sol";

contract GpPurchaserV3 is 
    ReentrancyGuard, 
    Initializable, 
    UUPSUpgradeable{

    uint256 public constant VERSION = 3;
    address admin;
    uint256 constant INIT_INDEX = 1 << 255;
    mapping(address => uint256) public nonce;
    mapping (address => bool) public isOwner;

    IWrapNative public wrapNative;
    IAggregator private aggregator;
    uint256[] private _indexOfErc20;
    uint256 private _indexOfNative;
    uint256 delegateConfirmThreshold;
    uint256 updateOwnerConfirmThreshold;
    uint256 withdrawOwnerConfirmThreshold;
    uint256 updateAdminConfirmThreshold;
    mapping(address => bool) private updateOwnerChecker;
    mapping (address => bool) private withdrawOwnerChecker;
    mapping (address => bool) private updateAdminChecker;
    address[] public ownerList;
    mapping(address=> bool) private _isDuplicate;

    struct UpdateOwnerRequest{
        address oldOwner;
        address newOwner;
        uint256 confirmCount;
    }

    struct UpdateAdminRequest{
        address newAdmin;
        uint256 confirmCount;
    }

    struct WithdrawRequest{
        address token;
        address to;
        uint256 amount;
        uint256 confirmCount;
    }

    struct DelegateRequest {
        uint256 marketId;
        uint256 _consumedGp;
        uint256 _delegatedValue;
        bool _continueIfFailed;
        uint256 _selfValue;
        bytes _inputData;
    }

    UpdateOwnerRequest[] public updateOwnerRequests;
    WithdrawRequest[] public withdrawRequests;
    UpdateAdminRequest[] public updateAdminRequests;
    
    event DelegateBuyExecuted(address[] _token, address requester, uint256[] consumedGp, uint256[] delegatedValue, uint256[] selfValue, uint256[] endTime, bytes[][] adminSignature);
    event Deposit(address _tokenAddress, address sponsor, uint256 amount);
    event ConsumeTokens (address _sender, address[] _tokenAddress, uint256[] amount);

    error AdminNotAllowed();
    error ArrayLengthNotMatched();
    error ValueNotMatch();
    error AllowanceNotEnough();
    error BalanceNotEnough();
    error DuplicateToken();
    error WithdrawError();
    error RefundFailed();
    error SignatureExpired();
    error ContractBalanceNotEnough(address _token);
    error OwnerArrayNotMatchConfirmThreshold();
    error AlreadyOwner();
    error NotAnOwner();
    error SomeSignError();
    error DuplcatedSigner();
    error AlreadyAnOwner();
    error AlreadyConfirmed();
    error CandidateCannotConfirm();
    error InvalidRequestIndex();
    error InvalidReceiver();
    error AlreadyAnAdmin();
    error NotAnAdmin();

    modifier onlyOwner{
        if (!isOwner[msg.sender]){
            revert NotAnOwner();
        }
        _;
    }
    
    modifier onlyAdmin{
        if (!(admin == msg.sender)){
            revert NotAnAdmin();
        }
        _;
    }

    /**
     * @dev the same ability of constructor, but it is for proxy mechanism.
     */ 
    function initialize(address[] calldata _owners, address _aggregator_addr, address _wrapNative, address _admin) public initializer{
        __UUPSUpgradeable_init();
        aggregator = IAggregator(_aggregator_addr);
        wrapNative = IWrapNative(_wrapNative);

        admin = _admin;

        _indexOfNative = INIT_INDEX;
        
        delegateConfirmThreshold = 3;
        updateOwnerConfirmThreshold = 2;
        withdrawOwnerConfirmThreshold = 2;
        updateAdminConfirmThreshold = 2;

        if (_owners.length != delegateConfirmThreshold){
            revert OwnerArrayNotMatchConfirmThreshold();
        }else{
            for(uint256 i = 0 ; i < delegateConfirmThreshold; i++){
                if (isOwner[_owners[i]]){
                    revert AlreadyOwner();
                }
                isOwner[_owners[i]] = true;
                ownerList.push(_owners[i]);
            }
        }
    }

    //  ---------------------------------------
    // |     Public/External Write-Function    |
    //  ---------------------------------------

    function delegateBuy(
        address[] memory _tokens,
        uint256[] memory _consumedGps,
        uint256[] memory _delegatedValue,
        uint256[] memory _selfValue,
        uint256[] memory _endTime,
        bytes memory _inputData,
        bytes[][] calldata _adminSignature
    ) external nonReentrant() payable {
        if ((_tokens.length != _consumedGps.length) ||
            (_consumedGps.length != _delegatedValue.length) ||
            (_tokens.length != _delegatedValue.length)||
            (_adminSignature.length != _tokens.length) ||
            (_selfValue.length != _tokens.length) ||
            (_endTime.length != _consumedGps.length)
        ){
            revert ArrayLengthNotMatched();
        }

        for(uint256 i = 0 ; i < _tokens.length; i++){
            if (_endTime[i] < block.timestamp){
                revert SignatureExpired();
            }
            if (_tokens[i] == address(wrapNative)){
                _checkAndSwapWrapToken(_delegatedValue[i]);
            }
            if (_tokens[i] != address(0) && IERC20(_tokens[i]).balanceOf(address(this)) < _delegatedValue[i]){
                revert ContractBalanceNotEnough(_tokens[i]);
            }
            if (_tokens[i] == address(0) && address(this).balance < _delegatedValue[i]){
                revert ContractBalanceNotEnough(_tokens[i]);
            }
            _checkBalanceAndSig(_tokens[i], _consumedGps[i], _delegatedValue[i], _selfValue[i], _endTime[i], _adminSignature[i]);
        }

        _transferERC20(_tokens, _selfValue);
        
        _delegateBuy(_tokens, _delegatedValue, _selfValue, _inputData);

        nonce[msg.sender]++;

        emit DelegateBuyExecuted(_tokens, msg.sender, _consumedGps, _delegatedValue, _selfValue, _endTime, _adminSignature);
        
    }

    //  ---------------------------------------
    // |             Admin Function           |
    //  ---------------------------------------

    function updateAggregator(address _new_address) external onlyOwner{
        aggregator = IAggregator(_new_address);
    }

    function approveErc20(address _token, address _target, uint256 _amount) external onlyOwner{
        IERC20(_token).approve(_target, _amount);
    }

    function requestUpdateAdmin(address _newAdmin) external onlyOwner{
        if (admin == _newAdmin){
            revert AlreadyAnAdmin();
        }
        
        updateAdminRequests.push(
            UpdateAdminRequest({
                newAdmin: _newAdmin,
                confirmCount: 1
            })
        );
        updateAdminChecker[msg.sender] = true;  
    }

    function requestUpdateOwner(address _oldOwner, address _newOwner) external onlyOwner{
        if (!isOwner[_oldOwner]){
            revert NotAnOwner();
        }
        if (isOwner[_newOwner]){
            revert AlreadyAnOwner();
        }
        updateOwnerRequests.push(
            UpdateOwnerRequest({
                oldOwner: _oldOwner,
                newOwner: _newOwner,
                confirmCount: 1
            })
        );
        updateOwnerChecker[msg.sender] = true;  
    }

    function requestWithdraw(address _token, address _to, uint256 _amount) external onlyOwner(){
        if ( address(this).balance < _amount){
            revert BalanceNotEnough();
        }
        withdrawRequests.push(
            WithdrawRequest({
                token: _token,
                to: _to,
                amount: _amount,
                confirmCount: 1
            })
        );
        withdrawOwnerChecker[msg.sender] = true;
    }

    function confirmUpdateOwner(uint256 _index) external onlyOwner{
        if(_index >= updateOwnerRequests.length){
            revert InvalidRequestIndex();
        } 
        UpdateOwnerRequest storage request = updateOwnerRequests[_index];

        if (updateOwnerChecker[msg.sender]){
            revert AlreadyConfirmed();
        }
        // if (msg.sender == request.oldOwner){
        //     revert CandidateCannotConfirm();
        // }
        request.confirmCount += 1;

        if (request.confirmCount == updateOwnerConfirmThreshold){
            isOwner[request.oldOwner] = false;
            isOwner[request.newOwner] = true;

            for(uint256 i = 0 ; i < ownerList.length; i++){
                if (ownerList[i] == request.oldOwner){
                    ownerList[i] = request.newOwner;
                    break;
                }
            }

            for(uint256 j = 0 ;j < ownerList.length; j++){
                if(updateOwnerChecker[ownerList[j]]){
                    updateOwnerChecker[ownerList[j]] = false;
                }
            }

            if (updateOwnerRequests.length == 1 ||
                (updateOwnerRequests.length - 1) == _index){
                updateOwnerRequests.pop();
            }else{
                UpdateOwnerRequest memory tmp = updateOwnerRequests[_index];
                updateOwnerRequests[_index] = updateOwnerRequests[updateOwnerRequests.length - 1];
                updateOwnerRequests[updateOwnerRequests.length - 1] = tmp;
                updateOwnerRequests.pop();
            }
        }
    }

    function confirmUpdateAdmin(uint256 _index) external onlyOwner{
        if(_index >= updateAdminRequests.length){
            revert InvalidRequestIndex();
        } 
        UpdateAdminRequest storage request = updateAdminRequests[_index];

        if (updateAdminChecker[msg.sender]){
            revert AlreadyConfirmed();
        }
        request.confirmCount += 1;

        if (request.confirmCount == updateAdminConfirmThreshold){
            admin = request.newAdmin;

            for(uint256 j = 0 ;j < ownerList.length; j++){
                if(updateAdminChecker[ownerList[j]]){
                    updateAdminChecker[ownerList[j]] = false;
                }
            }
            if (updateAdminRequests.length == 1 ||
                (updateAdminRequests.length - 1) == _index){
                updateAdminRequests.pop();
            }else{
                UpdateAdminRequest memory tmp = updateAdminRequests[_index];
                updateAdminRequests[_index] = updateAdminRequests[updateAdminRequests.length - 1];
                updateAdminRequests[updateAdminRequests.length - 1] = tmp;
                updateAdminRequests.pop();
            }
        }
    }

    function confirmWithdraw(uint256 _index) external nonReentrant() onlyOwner{
        if(_index >= withdrawRequests.length){
            revert InvalidRequestIndex();
        } 
        WithdrawRequest storage request = withdrawRequests[_index];

        if (withdrawOwnerChecker[msg.sender]){
            revert AlreadyConfirmed();
        }

        request.confirmCount += 1;

        if (request.confirmCount == withdrawOwnerConfirmThreshold){

            _withdraw(request.token, request.to, request.amount);

            for(uint256 j = 0 ;j < ownerList.length; j++){
                if(withdrawOwnerChecker[ownerList[j]]){
                    withdrawOwnerChecker[ownerList[j]] = false;
                }
            }

            if (withdrawRequests.length == 1 ||
                (withdrawRequests.length - 1) == _index){
                withdrawRequests.pop();
            }else{
                WithdrawRequest memory tmp = withdrawRequests[_index];
                withdrawRequests[_index] = withdrawRequests[withdrawRequests.length - 1];
                withdrawRequests[withdrawRequests.length - 1] = tmp;
                withdrawRequests.pop();
            }
        }
    }

    //  ---------------------------------------
    // |           Internal Function          |
    //  ---------------------------------------

    /**
     * @dev The function overrides one from UUPSUpgradeable to ensure that only an admin can update it.
     */ 
    function _authorizeUpgrade(address newImplementation) internal view onlyAdmin override {
        require(newImplementation != address(0), "Cannot be zero address.");
    }

    //  ---------------------------------------
    // |           Private Function           |
    //  ---------------------------------------
    
    /**
     * @dev Verified admin signature for GP pay.
     */ 
    function _verifyAdminSignature(
        address _token,
        uint256 consumedGp,
        uint256 delegatedValue,
        uint256 _endTime,
        bytes memory signature
    ) private view returns (bool, address) {
        bytes32 messageHash = _getMessageHash(_token, msg.sender, consumedGp, delegatedValue, _endTime);
        bytes32 ethSignedMessageHash = _getEthSignedMessageHash(messageHash);
        address recoverOwner = _recoverSigner(ethSignedMessageHash, signature);

        return (isOwner[recoverOwner], recoverOwner) ;
    }

    /**
     * @dev recover signature to signer address.
     */ 
    function _recoverSigner(bytes32 ethSignedMessageHash, bytes memory signature) private pure returns (address) {
        (bytes32 r, bytes32 s, uint8 v) = _splitSignature(signature);
        require(v == 27 || v == 28, "Invalid signature 'v' value");
        return ecrecover(ethSignedMessageHash, v, r, s);
    }

    /**
     * @dev Split signature to r, s, v
     */ 
    function _splitSignature(bytes memory sig) private pure returns (bytes32 r, bytes32 s, uint8 v) {
        require(sig.length == 65, "Invalid signature length");

        assembly {
            r := mload(add(sig, 32))
            s := mload(add(sig, 64))
            v := byte(0, mload(add(sig, 96)))
        }
    }
    /**
     * @dev get message.
     */ 
    function _getMessageHash(
        address _token, 
        address sender, 
        uint256 consumedGp,
        uint256 delegatedValue,
        uint256 _endTime
    ) private view returns (bytes32) {
        return keccak256(
            abi.encodePacked(
                nonce[msg.sender],
                _token,
                sender,
                consumedGp,
                delegatedValue,
                _endTime
            )
        );
    }

    /**
     * @dev get ethereum Message, which follow EIP-191
     */ 
    function _getEthSignedMessageHash(bytes32 messageHash) private pure returns (bytes32) {
        return keccak256(
            abi.encodePacked(
                "\x19Ethereum Signed Message:\n32",
                messageHash
            )
        );
    }

    function _delegateBuy(
        address[] memory _tokens,
        uint256[] memory _delegatedValue,
        uint256[] memory _selfValue,
        bytes memory _inputData
    ) private{
        uint256[] memory preTokenAmount = _getContractBalance( _tokens);
        
        _checkDuplicateTokensAndFillTokenIndex(_tokens);
        if (_indexOfErc20.length == 0){
            uint256 value = _delegatedValue[0] + _selfValue[0];
            aggregator.batchBuyWithETH{value: value }(_inputData);
        }else{
            IAggregator.ERC20Pair[] memory erc20Pairs = new IAggregator.ERC20Pair[](_indexOfErc20.length);
            address[] memory erc20Arr = new address[](_indexOfErc20.length);
            for(uint256 i = 0 ; i < _indexOfErc20.length; i++){
                uint256 _index = _indexOfErc20[i];
                erc20Arr[i] = _tokens[_index];
                erc20Pairs[i] = IAggregator.ERC20Pair(
                    {
                        token: _tokens[_index],
                        amount: (_delegatedValue[_index] + _selfValue[_index])
                    }
                );
            }
            if (_indexOfNative == INIT_INDEX){
                aggregator.batchBuyWithERC20s(
                    erc20Pairs,
                    _inputData,
                    erc20Arr
                );
            }else{
                aggregator.batchBuyWithERC20s{value: (_delegatedValue[_indexOfNative] + _selfValue[_indexOfNative])}(
                    erc20Pairs,
                    _inputData,
                    erc20Arr
                );
            }
        }
        uint256[] memory consumeTokenAmount = _getConsumeTokenAmount(_tokens, preTokenAmount);
        
        emit ConsumeTokens(msg.sender, _tokens, consumeTokenAmount);

        uint256[] memory refundAmount = _getRefundAmount(_tokens, _delegatedValue, _selfValue, consumeTokenAmount);
        _refund(_tokens, refundAmount);
        _clean_storage(_tokens); 
    }

    function _checkBalanceAndSig(
        address _token,
        uint256 _consumedGp,
        uint256 _delegatedValue,
        uint256 _selfValue,
        uint256 _endTime,
        bytes[] memory _adminSignature
        ) private {
            uint256 confirmCount = 0;
            address sender = msg.sender;
            uint256 value = msg.value;
            if (_token != address(0)){
                if(IERC20(_token).allowance(sender, address(this)) < _selfValue){
                    revert AllowanceNotEnough();
                }
                if (IERC20(_token).balanceOf(sender) < _selfValue){
                    revert BalanceNotEnough();
                }
            }else{
                if (value != _selfValue){
                    revert ValueNotMatch();
                }
            }
            for(uint256 i = 0 ; i < _adminSignature.length; i++){
                address[] memory confirmAddr = new address[](delegateConfirmThreshold);
                (bool _isVerified, address _recoverOwner) = _verifyAdminSignature(_token, _consumedGp, _delegatedValue, _endTime, _adminSignature[i]);
                if(!_isVerified){
                    revert AdminNotAllowed();
                }else{
                    _checkVerifiedOwnerDuplicated(confirmAddr, _recoverOwner);
                    confirmAddr[confirmCount] = _recoverOwner;
                }
                confirmCount += 1;  
            }
            if (confirmCount != delegateConfirmThreshold){
                revert SomeSignError();
            }
            
    }

    function _transferERC20(
        address[] memory _tokens,
        uint256[] memory _selfValue
    ) private {
        for(uint256 i = 0 ; i < _tokens.length; i++){
            if((_tokens[i] != address(0)) && (_selfValue[i] != 0)){
                IERC20(_tokens[i]).transferFrom(msg.sender, address(this), _selfValue[i]); 
            }
        }
    }

    //  ---------------------------------------
    // |           Depsoit Function           |
    //  ---------------------------------------
    
    function depsoitNativeToken() external payable{
        emit Deposit(address(0), msg.sender, msg.value);
    }

    function depsoitERC20(
        address _tokenAddress,
        uint256 _value
    ) external payable{ 
        IERC20(_tokenAddress).transferFrom(msg.sender, address(this), _value); 
        emit Deposit(_tokenAddress, msg.sender, _value);
    }

    function _checkDuplicateTokensAndFillTokenIndex (
        address[] memory _tokens
    ) private {
        for(uint256 i = 0 ; i < _tokens.length; i++){
            if (_isDuplicate[_tokens[i]]){
                revert DuplicateToken();
            }
            _isDuplicate[_tokens[i]] = true;
            if (_tokens[i] != address(0)){
                _indexOfErc20.push(i);
            }else{
                _indexOfNative = i;
            }
        }
    }

    function _clean_storage(
        address[] memory _tokens
    ) private {
        for(uint256 i = 0 ; i < _tokens.length; i++){
            _isDuplicate[_tokens[i]] = false;
        }
        delete _indexOfErc20;
        _indexOfNative = INIT_INDEX;
        
    }

    function _getContractBalance (
        address[] memory _tokens
    )private view returns(uint256[] memory) {
        uint256[] memory _tokenAmount = new uint256[](_tokens.length);
        for(uint256 i = 0 ; i < _tokens.length; i ++){
            if (_tokens[i] == address(0)){
                _tokenAmount[i] = address(this).balance;
                continue;
            }
            _tokenAmount[i] = IERC20(_tokens[i]).balanceOf(address(this));
        }

        return _tokenAmount;
    }

    function _getConsumeTokenAmount(address[] memory _tokens, uint256[] memory _preBalance) private view returns (uint256[] memory) {
        uint256[] memory consumeAmount = new uint256[](_tokens.length);
        for(uint256 i = 0 ; i < _tokens.length; i ++){
            if (_tokens[i] == address(0)){
                consumeAmount[i] = _preBalance[i] - address(this).balance;
                continue;
            }
            consumeAmount[i] = _preBalance[i] - IERC20(_tokens[i]).balanceOf(address(this));
        }
        return consumeAmount;
    }

    function _getRefundAmount(
        address[] memory _tokens,
        uint256[] memory _delegatedValue,
        uint256[] memory _selfValue,
        uint256[] memory _consumeValue
    ) private pure returns(uint256[] memory){
        uint256[] memory refunds = new uint256[](_tokens.length);
        for(uint256 i = 0 ; i < _tokens.length; i++){
            if (_delegatedValue[i] < _consumeValue[i] ){
                refunds[i] = _selfValue[i] - (_consumeValue[i] - _delegatedValue[i]);
            }else{
                refunds[i] = _selfValue[i];
            }
        }
        return refunds;
    }

    function _checkVerifiedOwnerDuplicated(
        address[] memory alreadyConfirmed,
        address _toBeCheck
    )private pure {
        for(uint256 i = 0 ; i < alreadyConfirmed.length; i++){
            if (alreadyConfirmed[i] == _toBeCheck){
                revert DuplcatedSigner();
            }
        }
    }

    function _refund(address[] memory _tokens, uint256[] memory _amount) private{
        for(uint256 i = 0 ; i < _tokens.length; i++){
            if (_amount[i] == 0) {
                continue;
            }else{
                if (_tokens[i] != address(0)){
                    IERC20(_tokens[i]).transfer(msg.sender, _amount[i]);
                }else{
                    (bool success, ) = payable(msg.sender).call{value: _amount[i]}("");
                    if (!success){
                        revert RefundFailed();
                    }
                }
            }   
        }
    }

    function _checkAndSwapWrapToken( uint256 _amount) private{
        uint256 selfBalance = wrapNative.balanceOf(address(this));
        if (selfBalance < _amount){
            uint256 toSwapAmount = _amount - selfBalance;
            if (toSwapAmount <= address(this).balance){
                _swap2WETH(toSwapAmount);
            }else{
                revert BalanceNotEnough();
            }
        }
    }

    function _swap2WETH( uint256 _amount ) private {
        wrapNative.deposit{value: _amount}();
    }

    function _withdraw(address _token, address _recipient, uint256 _amount) private {
        if (_recipient == address(0)){
            revert InvalidReceiver();
        }
        if (_token == address(0)){
            (bool success, ) = payable(_recipient).call{value: _amount}("");
            if (!success){
                revert WithdrawError();
            }
        }else{
            IERC20(_token).transfer(_recipient, _amount);
        }
    }


    receive() external payable{}
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.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);
        }
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol

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

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

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

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

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

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

pragma solidity ^0.8.21;

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

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

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

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

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

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

lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

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

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.20;

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

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

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

lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

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

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

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

pragma solidity ^0.8.20;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

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

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

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

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

src/IAggregator.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.15;


interface IAggregator {

    struct ERC20Pair {
        address token;
        uint256 amount;
    }

    struct ERC721Pair {
        address nft;
        uint256 id;
    }
    
    struct ERC1155Pair {
        address nft;
        uint256 id;
        uint256 amount;
    }

    function batchBuyWithETH(bytes calldata tradeBytes) external payable;

    function batchBuyWithERC20s(
        ERC20Pair[] memory erc20Pairs,
        bytes calldata tradeBytes,
        address[] memory dustTokens
    ) external payable;

    function acceptWithERC721(
         ERC721Pair[] calldata erc721Pairs,
        ERC20Pair[] calldata erc20Pairs,
        address[] calldata dustTokens,
        bytes calldata tradeBytes
    ) external payable;

    function acceptWithERC1155(
        ERC1155Pair[] calldata erc1155Pairs,
        ERC20Pair[] calldata erc20Pairs,
        address[] calldata dustTokens,
        bytes calldata tradeBytes
    ) external  payable;
}

src/IWrapNative.sol

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IWrapNative {

    function deposit() external payable;

    function withdraw(uint) external;

    function approve(address, uint) external returns(bool);

    function transfer(address, uint) external returns(bool);

    function transferFrom(address, address, uint) external returns(bool);

    function balanceOf(address) external view returns(uint);

}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@seaport-core/=lib/seaport-core/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "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/",
    "seaport-core/=lib/seaport-core/src/",
    "seaport-types/=lib/seaport-core/lib/seaport-types/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.