ETH Price: $2,516.90 (-1.53%)

Token

Aori Seats (AORISEATS)
 

Overview

Max Total Supply

132 AORISEATS

Holders

59

Market

Volume (24H)

N/A

Min Price (24H)

N/A

Max Price (24H)

N/A
Balance
4 AORISEATS
0xfd9b9039386b1619ce3aef82a5b521b12f8e13ee
Loading...
Loading
Loading...
Loading
Loading...
Loading

Click here to update the token information / general information
# Exchange Pair Price  24H Volume % Volume

Contract Source Code Verified (Exact Match)

Contract Name:
AoriSeats

Compiler Version
v0.8.19+commit.7dd6d404

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 42 : AoriSeats.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity ^0.8.19;

import "./OpenZeppelin/ERC721Enumerable.sol";
import "./OpenZeppelin/IERC20.sol";
import "./OpenZeppelin/Ownable.sol";
import "./OpenZeppelin/ERC2981.sol";
import "./OpenZeppelin/ReentrancyGuardUpgradeable.sol";
import "./CallFactory.sol";
import "./PutFactory.sol";
import "./OrderbookFactory.sol";

/**
    Storage for all Seat NFT management and fee checking
 */
contract AoriSeats is ERC721Enumerable, ERC2981, Ownable, ReentrancyGuard {

     uint256 maxSeats;
     uint256 public currentSeatId;
     uint256 mintFee;
     uint256 tradingFee;
     uint256 public maxSeatScore;
     uint256 public feeMultiplier;
     CallFactory public CALLFACTORY;
     PutFactory public PUTFACTORY;
     address public minter;
     address public seatRoyaltyReceiver;
     uint256 public defaultSeatScore;
     OrderbookFactory public ORDERBOOKFACTORY;
     mapping(address => uint256) pointsTotal;
     mapping(uint256 => uint256) totalVolumeBySeat;

     constructor(
         string memory name_,
         string memory symbol_,
         uint256 maxSeats_,
         uint256 mintFee_,
         uint256 tradingFee_,
         uint256 maxSeatScore_,
         uint256 feeMultiplier_
     ) ERC721(name_, symbol_) {
         maxSeats = maxSeats_;
         mintFee = mintFee_;
         tradingFee = tradingFee_;
         maxSeatScore = maxSeatScore_;
         feeMultiplier = feeMultiplier_;

         _setDefaultRoyalty(owner(), 350);
         setSeatRoyaltyReceiver(owner());
         setDefaultSeatScore(5);
     }

    event FeeSetForSeat (uint256 seatId, address SeatOwner);
    event MaxSeatChange (uint256 NewMaxSeats);
    event MintFeeChange (uint256 NewMintFee);
    event TradingFeeChange (uint256 NewTradingFee);

    /** 
    Admin control functions
    */

    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, ERC2981) returns (bool) {
            return super.supportsInterface(interfaceId);
    }

    function setMinter(address _minter) public onlyOwner {
        minter = _minter;
    }
    
    function setSeatRoyaltyReceiver(address newSeatRoyaltyReceiver) public onlyOwner {
        seatRoyaltyReceiver = newSeatRoyaltyReceiver;
    }

    function setCallFactory(CallFactory newCALLFACTORY) public onlyOwner returns (CallFactory) {
        CALLFACTORY = newCALLFACTORY;
        return CALLFACTORY;
    }

    function setPutFactory(PutFactory newPUTFACTORY) public onlyOwner returns (PutFactory) {
        PUTFACTORY = newPUTFACTORY;
        return PUTFACTORY;
    }
    
    function setOrderbookFactory(OrderbookFactory newORDERBOOKFACTORY) public onlyOwner returns (OrderbookFactory) {
        ORDERBOOKFACTORY = newORDERBOOKFACTORY;
        return ORDERBOOKFACTORY;
    }

    function setBaseURI(string memory baseURI) public onlyOwner {
        _setBaseURI(baseURI);
    }

    function setDefaultSeatScore(uint256 score) public onlyOwner returns(uint256) {
        defaultSeatScore = score;
        return score;
    }

    function mintSeat() external returns (uint256) {
        require(msg.sender == minter);

        uint256 currentSeatIdLocal = currentSeatId;

        if (currentSeatId % 10 == 0) {
            seatScore[currentSeatIdLocal] = 1;
            _mint(seatRoyaltyReceiver, currentSeatIdLocal);
            currentSeatIdLocal++;
        }
        seatScore[currentSeatIdLocal] = defaultSeatScore;
        _mint(minter, currentSeatIdLocal);
        currentSeatId = currentSeatIdLocal + 1; //prepare seat id for future mint calls
        return currentSeatIdLocal; //return the id of the seat we just minted
    }

    /** 
        Combines two seats and adds their scores together
        Enabling the user to retain a higher portion of the fees collected from their seat
    */
    function combineSeats(uint256 seatIdOne, uint256 seatIdTwo) public returns(uint256) {
        require(msg.sender == ownerOf(seatIdOne) && msg.sender == ownerOf(seatIdTwo));
        uint256 newSeatScore = seatScore[seatIdOne] + seatScore[seatIdTwo];
        require(newSeatScore <= maxSeatScore);
        _burn(seatIdOne);
        _burn(seatIdTwo);
        uint256 newSeatId = currentSeatId++;
        _safeMint(msg.sender, newSeatId);
        seatScore[newSeatId] = newSeatScore;
        return seatScore[newSeatId];
    }

    /**
        Mints the user a series of one score seats
     */
    function separateSeats(uint256 seatId) public {
        require(msg.sender == ownerOf(seatId));
        uint256 currentSeatScore = seatScore[seatId];
        seatScore[seatId] = 1; //Reset the original seat
        _burn(seatId); //Burn the original seat
        //Mint the new seats
        for(uint i = 0; i < currentSeatScore; i++) {
            uint mintIndex = currentSeatId++;
            _safeMint(msg.sender, mintIndex);
            seatScore[mintIndex] = 1;
        }
    }

    /** 
        Volume = total notional trading volume through the seat
        For data tracking purposes.
    */
    function addTakerVolume(uint256 volumeToAdd, uint256 seatId, address Orderbook_) public nonReentrant {
        //confirms via Orderbook contract that the msg.sender is a call or put market created by the OPTIONTROLLER
        require(ORDERBOOKFACTORY.checkIsOrder(Orderbook_, msg.sender));
        
        uint256 currentVolume = totalVolumeBySeat[seatId];
        totalVolumeBySeat[seatId] = currentVolume + volumeToAdd;
    }


    /**
        Change the total number of seats
     */
    function setMaxSeats(uint256 newMaxSeats) public onlyOwner returns (uint256) {
        maxSeats = newMaxSeats;
        emit MaxSeatChange(newMaxSeats);
        return maxSeats;
    }
     /**
        Change the number of points for taking bids/asks and minting options
     */
    function setFeeMultiplier(uint256 newFeeMultiplier) public onlyOwner returns (uint256) {
        feeMultiplier = newFeeMultiplier;
        return feeMultiplier;
    }

    /**
        Change the maximum number of seats that can be combined
        Currently if this number exceeds 12 the Orderbook will break
     */
    function setMaxSeatScore(uint256 newMaxScore) public onlyOwner returns(uint256) {
        require(newMaxScore > maxSeatScore);
        maxSeatScore = newMaxScore;
        return maxSeatScore;
    }
    /** 
        Change the mintingfee in BPS
        For example a fee of 100 would be equivalent to a 1% fee (100 / 10_000)
    */
    function setMintFee(uint256 newMintFee) public onlyOwner returns (uint256) {
        mintFee = newMintFee;
        emit MintFeeChange(newMintFee);
        return mintFee;
    }
    /** 
        Change the mintingfee in BPS
        For example a fee of 100 would be equivalent to a 1% fee (100 / 10_000)
    */
    function setTradingFee(uint256 newTradingFee) public onlyOwner returns (uint256) {
        tradingFee = newTradingFee;
        emit TradingFeeChange(newTradingFee);
        return tradingFee;
    }
    /**
        Set an individual seat URI
     */
    function setSeatIdURI(uint256 seatId, string memory _seatURI) public {
        require(msg.sender == owner());
        _setTokenURI(seatId, _seatURI);
    }

    /**
    VIEW FUNCTIONS
     */
    function getOptionMintingFee() public view returns (uint256) {
        return mintFee;
    }
    function getTradingFee() public view returns (uint256) {
        return tradingFee;
    }

    function confirmExists(uint256 seatId) public view returns (bool) {
        return _exists(seatId);
    }

    function getPoints(address user) public view returns (uint256) {
        return pointsTotal[user];
    }

    function getSeatScore(uint256 seatId) public view returns (uint256) {
        return seatScore[seatId];
    }
    
    function getFeeMultiplier() public view returns (uint256) {
        return feeMultiplier;
    }

    function getSeatVolume(uint256 seatId) public view returns (uint256) {
        return totalVolumeBySeat[seatId];
    }
}

File 2 of 42 : AoriCall.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity ^0.8.13;

import "./OpenZeppelin/ERC20.sol";
import "./OpenZeppelin/Ownable.sol";
import "./Chainlink/AggregatorV3Interface.sol";
import "./OpenZeppelin/IERC20.sol";
import "./OpenZeppelin/ReentrancyGuard.sol";
import "./AoriSeats.sol";
import "./OpenZeppelin/SafeERC20.sol";
import "./Margin/MarginManager.sol";

contract AoriCall is ERC20, ReentrancyGuard {
    address public immutable factory;
    address public immutable manager;
    address public oracle; //Must be USD Denominated Chainlink Oracle with 8 decimals
    uint256 public immutable strikeInUSDC;
    uint256 public immutable endingTime;
    uint256 public immutable duration; //duration in blocks
    IERC20 public immutable UNDERLYING;
    uint256 public immutable UNDERLYING_DECIMALS;
    IERC20 public immutable USDC;
    uint256 public immutable USDC_DECIMALS;
    uint256 public settlementPrice;
    uint256 public immutable feeMultiplier;
    uint256 public immutable decimalDiff;
    uint256 immutable tolerance = 2 hours;
    bool public hasEnded = false;
    AoriSeats public immutable AORISEATSADD;
    mapping (address => uint256) public optionSellers;
    uint256 public immutable BPS_DIVISOR = 10000;


    constructor(
        address _manager,
        uint256 _feeMultiplier,
        uint256 _strikeInUSDC,
        uint256 _duration, //in blocks
        IERC20 _UNDERLYING,
        IERC20 _USDC,
        address _oracle,
        AoriSeats _AORISEATSADD,
        string memory name_,
        string memory symbol_
    ) ERC20(name_, symbol_, 18) {
        factory = msg.sender;
        manager = _manager;
        feeMultiplier = _feeMultiplier;
        strikeInUSDC = _strikeInUSDC; 
        duration = _duration; //in seconds
        endingTime = block.timestamp + duration;
        UNDERLYING = _UNDERLYING;
        UNDERLYING_DECIMALS = UNDERLYING.decimals();
        USDC = _USDC;
        USDC_DECIMALS = USDC.decimals();
        decimalDiff = (10**UNDERLYING_DECIMALS) / (10**USDC_DECIMALS); //The underlying decimals must be greater than or equal to USDC's decimals.
        oracle = _oracle;
        AORISEATSADD = _AORISEATSADD;
    }

    event CallMinted(uint256 optionsMinted, address minter);
    event CallBuyerITMSettled(uint256 optionsRedeemed, address settler);
    event CallSellerITMSettled(uint256 optionsRedeemed, address settler);
    event CallSellerOTMSettled(uint256 optionsRedeemed, address settler);
    event SellerRetrievedFunds(uint256 tokensRetrieved, address seller);

    function setOracle(address newOracle) public returns(address) {
        require(msg.sender == AORISEATSADD.owner());
        oracle = newOracle;
        return oracle;
    }
    /**
        Mints a call option equivalent to the quantity of the underlying asset divided by
        the strike price as quoted in USDC. 
        Note that this does NOT sell the option for you.
        You must list the option in an OptionSwap orderbook to actually be paid for selling this option.
        The Receiver will receive the options ERC20's but the option seller will be stored as the msg.sender
     */
    function mintCall(uint256 quantityOfUNDERLYING, address receiver, uint256 seatId) public nonReentrant returns (uint256) {
        //confirming the user has enough of the UNDERLYING
        require(UNDERLYING_DECIMALS == UNDERLYING.decimals(), "Decimal disagreement");
        require(block.timestamp < endingTime, "This option has already matured"); //safety check
        require(UNDERLYING.balanceOf(msg.sender) >= quantityOfUNDERLYING, "Not enough of the underlying");
        require(AORISEATSADD.confirmExists(seatId) && AORISEATSADD.ownerOf(seatId) != address(0x0), "Seat does not exist");

        uint256 mintingFee;
        uint256 refRate;
        uint256 feeToSeat;
        uint256 optionsToMint;
        //Checks seat ownership, and assigns fees and transfers accordingly
        if (receiver == AORISEATSADD.ownerOf(seatId)) {
            //If the owner of the seat IS the caller, fees are 0
            mintingFee = 0;
            refRate = 0;
            feeToSeat = 0;
            optionsToMint = (quantityOfUNDERLYING * (10**6)) / strikeInUSDC;
            //transfer the UNDERLYING
            SafeERC20.safeTransferFrom(UNDERLYING, msg.sender, address(this), quantityOfUNDERLYING);
            _mint(receiver, optionsToMint);
        } else {
            //If the owner of the seat is not the caller, calculate and transfer the fees
            mintingFee = callUNDERLYINGFeeCalculator(quantityOfUNDERLYING, AORISEATSADD.getOptionMintingFee());
            // Calculating the fees to go to the seat owner
            refRate = (AORISEATSADD.getSeatScore(seatId) * 500) + 3500;
            feeToSeat = (refRate * mintingFee) / BPS_DIVISOR; 
            optionsToMint = ((quantityOfUNDERLYING - mintingFee) * (10**6)) / strikeInUSDC;

            //transfer the UNDERLYING and route fees
            SafeERC20.safeTransferFrom(UNDERLYING, msg.sender, address(this), quantityOfUNDERLYING - mintingFee);
            SafeERC20.safeTransferFrom(UNDERLYING, msg.sender, Ownable(factory).owner(), mintingFee - feeToSeat);
            SafeERC20.safeTransferFrom(UNDERLYING, msg.sender, AORISEATSADD.ownerOf(seatId), feeToSeat);
            //mint the user LP tokens
            _mint(receiver, optionsToMint);
        }

        //storing this option seller's information for future settlement
        uint256 currentOptionsSold = optionSellers[msg.sender];
        uint256 newOptionsSold = currentOptionsSold + optionsToMint;
        optionSellers[msg.sender] = newOptionsSold;

        emit CallMinted(optionsToMint, msg.sender);

        return (optionsToMint);
    }

    /**
        Sets the settlement price immediately upon the maturation
        of this option. Anyone can set the settlement into motion.
        Note the settlement price is converted to USDC Scale via getPrice();
     */
    function _setSettlementPrice() internal returns (uint256) {
        require(block.timestamp >= endingTime, "Option has not matured");
        if(hasEnded == false) {
            settlementPrice = uint256(getPrice());
            hasEnded = true;
        }
        return settlementPrice;
    }

    /**
        Gets the option minting fee from AoriSeats and
        Calculates the minting fee in BPS of the underlying token
     */
    function callUNDERLYINGFeeCalculator(uint256 optionsToSettle, uint256 fee) internal view returns (uint256) {
        require(UNDERLYING_DECIMALS == UNDERLYING.decimals());
        uint256 txFee = (optionsToSettle * fee) / BPS_DIVISOR;
        return txFee;
    }

    /**
        Takes the quantity of options the user wishes to settle then
        calculates the quantity of USDC the user must pay the contract
        Note this calculation only occurs for in the money options.
     */
    function scaleToUSDCAtStrike(uint256 optionsToSettle) internal view returns (uint256) {
        uint256 tokenDecimals = 10**UNDERLYING_DECIMALS;
        uint256 scaledVal = (optionsToSettle * strikeInUSDC) / tokenDecimals; //(1e18 * 1e6) / 1e18
        return scaledVal;
    }

    /**
        In the money settlement procedures for an option purchaser.
        The settlement price must exceed the strike price for this function to be callable
        Then the user must transfer USDC according to the following calculation: (USDC * strikeprice) * optionsToSettle;
        Then the user receives the underlying ERC20 at the strike price.
     */
    function buyerSettlementITM(uint256 optionsToSettle) public nonReentrant returns (uint256) {
        _setSettlementPrice();
        require(balanceOf(msg.sender) >= optionsToSettle, "You are attempting to settle more options than you have purhased");
        require(balanceOf(msg.sender) >= 0, "You have not purchased any options");
        require(settlementPrice > strikeInUSDC  && settlementPrice != 0, "Option did not expire ITM");
        require(optionsToSettle <= totalSupply() && optionsToSettle != 0);
        
        //Calculating the profit using a ratio of settlement price
        //minus the strikeInUSDC, then dividing by the settlement price.
        //This gives us the total number of underlying tokens to give the settler.
        uint256 profitPerOption = ((settlementPrice - strikeInUSDC) * 10**6) / settlementPrice; // (1e6 * 1e6) / 1e6
        uint256 UNDERLYINGOwed = (profitPerOption * optionsToSettle) / 10**6; //1e6 * 1e18 / 1e6 
        
        _burn(msg.sender, optionsToSettle);
        SafeERC20.safeTransfer(UNDERLYING, msg.sender, UNDERLYINGOwed); //sending 1e18 scale tokens to user
        emit CallBuyerITMSettled(optionsToSettle, msg.sender);

        return (optionsToSettle);
    }

    /**
        In the money settlement procedures for an option seller.
        The option seller receives USDC equivalent to the strike price * the number of options they sold.
     */
    function sellerSettlementITM() public nonReentrant returns (uint256) {
        _setSettlementPrice();
        uint256 optionsToSettle = optionSellers[msg.sender];
        require(optionsToSettle > 0);
        require(settlementPrice > strikeInUSDC && hasEnded == true, "Option did not settle ITM");

        uint256 UNDERLYINGToReceive = ((strikeInUSDC * 10**6) / settlementPrice) * optionsToSettle; // (1e6*1e6/1e6) * 1e18
        //store the settlement
        optionSellers[msg.sender] = 0;
    
        //settle
        SafeERC20.safeTransfer(UNDERLYING, msg.sender, UNDERLYINGToReceive / 10**6);
        emit CallSellerITMSettled(optionsToSettle, msg.sender);

        return optionsToSettle;
    }   

    /**
        Settlement procedures for an option sold that expired out of the money.
        The seller receives all of their underlying assets back while retaining the premium from selling.
     */
    function sellerSettlementOTM() public nonReentrant returns (uint256) {
        _setSettlementPrice();
        require(optionSellers[msg.sender] > 0 && settlementPrice <= strikeInUSDC, "Option did not settle OTM or you did not sell any");
        uint256 optionsSold = optionSellers[msg.sender];

        //store the settlement
        optionSellers[msg.sender] = 0;

        //settle
        SafeERC20.safeTransfer(UNDERLYING, msg.sender, optionsSold);

        emit CallSellerOTMSettled(optionsSold, msg.sender);

        return optionsSold;
    }

    /**
        Early settlement exclusively for liquidations via the margin manager
     */
    function liquidationSettlement(uint256 optionsToSettle) public nonReentrant returns (uint256) {
        require(msg.sender == MarginManager(manager).vaultAdd(ERC20(address(UNDERLYING))));

        _burn(msg.sender, optionsToSettle);
        optionSellers[manager] -= optionsToSettle;
        uint256 UNDERLYINGToReceive = (optionsToSettle * strikeInUSDC) / 10**UNDERLYING_DECIMALS;
        UNDERLYING.transferFrom(address(this), manager, UNDERLYINGToReceive);
        return UNDERLYINGToReceive;
    }

    /**
     *  VIEW FUNCTIONS
    */

    /** 
        Get the price converted from Chainlink format to USDC
    */
    function getPrice() public view returns (uint256) {
        (, int256 price,  ,uint256 updatedAt,  ) = AggregatorV3Interface(oracle).latestRoundData();
        require(price >= 0, "Negative Prices are not allowed");
        require(block.timestamp <= updatedAt + tolerance, "Price is too stale to be trustworthy"); // also works if updatedAt is 0
        if (price == 0) {
            return strikeInUSDC;
        } else {
            //8 is the decimals() of chainlink oracles
            return (uint256(price) / (10**(8 - USDC_DECIMALS)));
        }
    }
    /** 
        For frontend ease. If a uint then the option is ITM, if 0 then it is OTM. 
    */
    function getITM() public view returns (uint256) {
        if (getPrice() >= strikeInUSDC) {
            return getPrice() - strikeInUSDC;
        } else {
            return 0;
        }
    }

    function getOptionsSold(address seller_) public view returns (uint256) {
        return optionSellers[seller_];
    }
}

File 3 of 42 : AoriPut.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity ^0.8.13;

import "./OpenZeppelin/ERC20.sol";
import "./OpenZeppelin/Ownable.sol";
import "./Chainlink/AggregatorV3Interface.sol";
import "./OpenZeppelin/IERC20.sol";
import "./OpenZeppelin/ReentrancyGuard.sol";
import "./AoriSeats.sol";
import "./Margin/MarginManager.sol";


contract AoriPut is ERC20, ReentrancyGuard {
    address public immutable factory;
    address public immutable manager;
    address public oracle; //Must be USD Denominated Chainlink Oracle with 8 decimals
    uint256 public immutable strikeInUSDC; //This is in 1e6 scale
    uint256 public immutable endingTime;
    uint256 public immutable duration; //duration in blocks
    uint256 public settlementPrice; //price to be set at expiration
    uint256 public immutable feeMultiplier;
    uint256 public immutable decimalDiff;
    uint256 immutable tolerance = 2 hours;
    bool public hasEnded = false;
    IERC20 public immutable USDC;
    IERC20 public immutable UNDERLYING;
    uint256 public immutable USDC_DECIMALS;
    AoriSeats public immutable AORISEATSADD;
    uint256 public immutable BPS_DIVISOR = 10000;

    mapping (address => uint256) optionSellers; 
    

    constructor(
        address _manager,
        uint256 _feeMultiplier,
        uint256 _strikeInUSDC,
        uint256 _duration, //in blocks
        IERC20 _USDC,
        IERC20 _UNDERLYING,
        address _oracle,
        AoriSeats _AORISEATSADD,
        string memory name_,
        string memory symbol_
    ) ERC20(name_, symbol_, 18) {
        factory = msg.sender;
        manager = _manager;
        feeMultiplier = _feeMultiplier;
        strikeInUSDC = _strikeInUSDC; 
        duration = _duration; //in blocks
        USDC = _USDC;
        UNDERLYING = _UNDERLYING;
        USDC_DECIMALS = USDC.decimals();
        endingTime = block.timestamp + duration;
        oracle = _oracle;
        AORISEATSADD = _AORISEATSADD;
        decimalDiff = (10**decimals()) / (10**USDC_DECIMALS);
    }

    event PutMinted(uint256 optionsMinted, address minter);
    event PutBuyerITMSettled(uint256 optionsRedeemed, address settler);
    event PutSellerITMSettled(uint256 optionsRedeemed, address settler);
    event PutSellerOTMSettled(uint256 optionsRedeemed, address settler);
    event SellerRetrievedFunds(uint256 tokensRetrieved, address seller);


    function setOracle(address newOracle) public returns(address) {
        require(msg.sender == AORISEATSADD.owner());
        oracle = newOracle;
        return oracle;
    }

    /**
        Mints a Put option equivalent to the USDC being deposited divided by the strike price.
        Note that this does NOT sell the option for you.
        You must list the option in an OptionSwap orderbook to actually be paid for selling this option.
        The Receiver will receive the options ERC20's but the option seller will be stored as the msg.sender
     */
    function mintPut(uint256 quantityOfUSDC, address receiver, uint256 seatId) public nonReentrant returns (uint256) {
        //confirming the user has enough USDC
        require(block.timestamp < endingTime, "This option has already matured"); //safety check
        require(USDC.balanceOf(msg.sender) >= quantityOfUSDC, "Not enough USDC");
        require(AORISEATSADD.confirmExists(seatId) && AORISEATSADD.ownerOf(seatId) != address(0x0), "Seat does not exist");
        
        uint256 mintingFee;
        uint256 refRate;
        uint256 feeToSeat;
        uint256 optionsToMint;
        uint256 optionsToMintScaled;
        if (receiver == AORISEATSADD.ownerOf(seatId)) {
            //If the owner of the seat IS the caller, fees are 0
            mintingFee = 0;
            feeToSeat = 0;
            optionsToMint = (quantityOfUSDC * 1e6) / strikeInUSDC;
            optionsToMintScaled = optionsToMint * decimalDiff; //convert the USDC to 1e18 scale to mint LP tokens
            //transfer the USDC
            USDC.transferFrom(msg.sender, address(this), quantityOfUSDC);
            _mint(receiver, optionsToMintScaled);
        } else {
            //If the owner of the seat is not the caller, calculate and transfer the fees
            mintingFee = putUSDCFeeCalculator(quantityOfUSDC, AORISEATSADD.getOptionMintingFee());
            refRate = (AORISEATSADD.getSeatScore(seatId) * 500) + 3500;
            feeToSeat = (refRate * mintingFee) / BPS_DIVISOR; 
            optionsToMint = ((quantityOfUSDC - mintingFee) * 10**USDC_DECIMALS) / strikeInUSDC; //(1e6*1e6) / 1e6
            optionsToMintScaled = optionsToMint * decimalDiff;

            //transfer the USDC and route fees
            USDC.transferFrom(msg.sender, address(this), quantityOfUSDC - mintingFee);
            USDC.transferFrom(msg.sender, Ownable(factory).owner(), mintingFee - feeToSeat);
            USDC.transferFrom(msg.sender, AORISEATSADD.ownerOf(seatId), feeToSeat);
            //mint the user LP tokens
            _mint(receiver, optionsToMintScaled);
        }

        //storing this option seller's information for future settlement
        uint256 currentOptionsSold = optionSellers[msg.sender];
        uint256 newOptionsSold = currentOptionsSold + optionsToMintScaled;
        optionSellers[msg.sender] = newOptionsSold;

        emit PutMinted(optionsToMintScaled, msg.sender);

        return (optionsToMintScaled);
    }

    /**
        Sets the settlement price immediately upon the maturation
        of this option. Anyone can set the settlement into motion.
        Note the settlement price is converted to USDC Scale via getPrice();
     */
    function _setSettlementPrice() internal returns (uint256) {
        require(block.timestamp >= endingTime, "Option has not matured");
        if(hasEnded == false) {
            settlementPrice = uint256(getPrice());
            hasEnded = true;
        }
        return settlementPrice;
    }

    /**
        Essentially a MulDiv functio but for calculating BPS conversions
     */
    function putUSDCFeeCalculator(uint256 quantityOfUSDC, uint256 fee) internal pure returns (uint256) {
        uint256 txFee = (quantityOfUSDC * fee) / BPS_DIVISOR;
        return txFee;
    }
     /**
     * IN THE MONEY SETTLEMENT PROCEDURES
     * FOR IN THE MONEY OPTIONS SETTLEMENT
     * 
     */

    //Buyer Settlement ITM
    function buyerSettlementITM(uint256 optionsToSettle) public nonReentrant returns (uint256) {
        _setSettlementPrice();
        require(balanceOf(msg.sender) >= 0, "You have not purchased any options");
        require(balanceOf(msg.sender) >= optionsToSettle, "You are attempting to settle more options than you have purhased");
        require(strikeInUSDC > settlementPrice && settlementPrice != 0, "Option did not expire ITM");
        require(optionsToSettle <= totalSupply() && optionsToSettle != 0);

        uint256 profitPerOption = strikeInUSDC - settlementPrice;
        //Normalize the optionsToSettle to USDC scale then multiply by profit per option to get USDC Owed to the settler.
        uint256 USDCOwed = ((optionsToSettle / decimalDiff) * profitPerOption) / 10**USDC_DECIMALS; //((1e18 / 1e12) * 1e6) / 1e6
        //transfers
        _burn(msg.sender, optionsToSettle);
        USDC.transfer(msg.sender, USDCOwed);

        emit PutBuyerITMSettled(optionsToSettle, msg.sender);
        return (optionsToSettle);
    }


    /**
        Settlement procedures for an option sold that expired in of the money.
        The seller receives a portion of their underlying assets back relative to the
        strike price and settlement price. 
     */

    function sellerSettlementITM() public nonReentrant returns (uint256) {
        _setSettlementPrice();
        uint256 optionsToSettle = optionSellers[msg.sender];
        require(optionsToSettle >= 0);
        require(strikeInUSDC > settlementPrice && hasEnded == true, "Option did not expire OTM");

        //Calculating the USDC to receive ()
        uint256 USDCToReceive = ((optionsToSettle * settlementPrice) / decimalDiff) / 10**USDC_DECIMALS; //((1e18 / 1e12) * 1e6) / 1e6
        //store the settlement
        optionSellers[msg.sender] = 0;
    
        //settle
        USDC.transfer(msg.sender, USDCToReceive);
        
        emit PutSellerITMSettled(optionsToSettle, msg.sender);

        return optionsToSettle;
    }   

    /**
        Settlement procedures for an option sold that expired out of the money.
        The seller receives all of their underlying assets back while retaining the premium from selling.
     */
    function sellerSettlementOTM() public nonReentrant returns (uint256) {
        _setSettlementPrice();
        require(optionSellers[msg.sender] > 0 && settlementPrice >= strikeInUSDC, "Option did not expire OTM");
        uint256 optionsSold = optionSellers[msg.sender];

        //store the settlement
        optionSellers[msg.sender] = 0;

        //settle
        uint256 USDCOwed = ((optionsSold / decimalDiff) * strikeInUSDC) / 10**USDC_DECIMALS; //((1e18 / 1e12) * 1e6) / 1e6
        USDC.transfer(msg.sender, USDCOwed);

        emit PutSellerOTMSettled(optionsSold, msg.sender);

        return optionsSold;
    }

    /**
        Early settlement exclusively for liquidations via the margin manager
     */
    function liquidationSettlement(uint256 optionsToSettle) public nonReentrant returns (uint256) {
        require(msg.sender == MarginManager(manager).vaultAdd(ERC20(address(USDC))));
        
        _burn(msg.sender, optionsToSettle);
        optionSellers[manager] -= optionsToSettle;
        uint256 USDCToReceive = (optionsToSettle * strikeInUSDC) / 10**USDC_DECIMALS;
        USDC.transferFrom(address(this), manager, USDCToReceive);
        return USDCToReceive;
    }

    /**
     *  VIEW FUNCTIONS
    */

    /** 
        Get the price of the underlying converted from Chainlink format to USDC.
    */
    function getPrice() public view returns (uint256) {
        (, int256 price,  ,uint256 updatedAt,  ) = AggregatorV3Interface(oracle).latestRoundData();
        require(price >= 0, "Negative Prices are not allowed");
        require(block.timestamp <= updatedAt + tolerance, "Price is too stale to be trustworthy"); // also works if updatedAt is 0
        if (price == 0) {
            return strikeInUSDC;
        } else {
            //8 is the decimals() of chainlink oracles
            return (uint256(price) / (10**(8 - USDC_DECIMALS)));
        }
    }

    /** 
        For frontend ease. If a uint then the option is ITM, if 0 then it is OTM. 
    */
    function getITM() public view returns (uint256) {
        if (getPrice() <= strikeInUSDC) {
            return strikeInUSDC - getPrice();
        } else {
            return 0;
        }
    }
    
    function getOptionsSold(address seller_) public view returns (uint256) {
        return optionSellers[seller_];
    }
}

File 4 of 42 : Ask.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity ^0.8.13;

import "./OpenZeppelin/IERC20.sol";
import "./AoriSeats.sol";
import "./OpenZeppelin/Ownable.sol";
import "./OpenZeppelin/ReentrancyGuard.sol";
import "./Chainlink/AggregatorV3Interface.sol";

contract Ask is ReentrancyGuard {
    address public immutable factory;
    address public immutable factoryOwner;
    address public immutable maker;
    uint256 public immutable USDCPerOPTION;
    uint256 public immutable OPTIONSize;
    uint256 public immutable fee; // in bps, default is 30 bps
    uint256 public immutable feeMultiplier;
    uint256 public immutable duration;
    uint256 public endingTime;
    AoriSeats public immutable AORISEATSADD;
    bool public hasEnded = false;
    bool public hasBeenFunded = false;
    IERC20 public OPTION;
    IERC20 public USDC; 
    uint256 public OPTIONDecimals = 18;
    uint256 public USDCDecimals = 6;
    uint256 public decimalDiff = (10**OPTIONDecimals) / (10**USDCDecimals);
    uint256 public immutable BPS_DIVISOR = 10000;
    uint256 public USDCFilled;

    event OfferFunded(address maker, uint256 OPTIONSize, uint256 duration);
    event Filled(address buyer, uint256 OPTIONAmount, uint256 AmountFilled, bool hasEnded);
    event OfferCanceled(address maker, uint256 OPTIONAmount);

    constructor(
        IERC20 _OPTION,
        IERC20 _USDC,
        AoriSeats _AORISEATSADD,
        address _maker,
        uint256 _USDCPerOPTION,
        uint256 _fee,
        uint256 _feeMultiplier,
        uint256 _duration, //in blocks
        uint256 _OPTIONSize
    ) {
        factory = msg.sender;
        factoryOwner = Ownable(factory).owner();
        OPTION = _OPTION;
        USDC = _USDC;
        AORISEATSADD = _AORISEATSADD;
        maker = _maker;
        USDCPerOPTION = _USDCPerOPTION;
        fee = _fee;
        feeMultiplier = _feeMultiplier;
        duration = _duration;
        OPTIONSize = _OPTIONSize;
    }
    
    // release trapped funds
    function withdrawTokens(address token) public {
        require(msg.sender == factoryOwner);
        if (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
            payable(factoryOwner).transfer(address(this).balance);
        } else {
            uint256 balance = IERC20(token).balanceOf(address(this));
            safeTransfer(token, factoryOwner, balance);
        }
    }

    /**
        Fund the Ask with Aori option ERC20's
     */
    function fundContract() public nonReentrant {
        require(msg.sender == factory);
        hasBeenFunded = true;
        //officially begin the countdown
        endingTime = block.timestamp + duration;
        emit OfferFunded(maker, OPTIONSize, duration);
    }
    /**
        Partial or complete fill of the offer, with the requirement of trading through a seat
        regardless of whether the seat is owned or not.
        In the case of not owning the seat, a fee is charged in USDC.
     */
    function fill(uint256 amountOfUSDC, uint256 seatId) public nonReentrant {
        require(isFunded(), "no option balance");
        require(msg.sender != maker && msg.sender != factory, "Cannot take one's own order");
        require(!hasEnded, "offer has been previously been cancelled");
        require(block.timestamp <= endingTime, "This offer has expired");
        require(USDC.balanceOf(msg.sender) >= amountOfUSDC, "Not enough USDC");
        require(AORISEATSADD.confirmExists(seatId) && AORISEATSADD.ownerOf(seatId) != address(0x0), "Seat does not exist");
        uint256 USDCAfterFee;
        uint256 OPTIONToReceive;
        uint256 refRate;

        if(msg.sender == AORISEATSADD.ownerOf(seatId)) {
            //Seat holders receive 0 fees for trading
            USDCAfterFee = amountOfUSDC;
            OPTIONToReceive = mulDiv(USDCAfterFee, 10**OPTIONDecimals, USDCPerOPTION); //1eY = (1eX * 1eY) / 1eX
            //transfers To the msg.sender
            USDC.transferFrom(msg.sender, maker, USDCAfterFee);
            //transfer to the Msg.sender
            OPTION.transfer(msg.sender, OPTIONToReceive);
        } else {
            //What the user will receive out of 100 percent in referral fees with a floor of 40
            refRate = (AORISEATSADD.getSeatScore(seatId) * 500) + 3500;
            //This means for Aori seat governance they should not allow more than 12 seats to be combined at once
            uint256 seatScoreFeeInBPS = mulDiv(fee, refRate, BPS_DIVISOR);
            //calculating the fee breakdown 
            uint256 seatTxFee = mulDiv(amountOfUSDC, seatScoreFeeInBPS, BPS_DIVISOR);
            uint256 ownerTxFee = mulDiv(amountOfUSDC, fee - seatScoreFeeInBPS, BPS_DIVISOR);
            //Calcualting the base tokens to transfer after fees
            USDCAfterFee = (amountOfUSDC - (ownerTxFee + seatTxFee));
            //And the amount of the quote currency the msg.sender will receive
            OPTIONToReceive = mulDiv(USDCAfterFee, 10**OPTIONDecimals, USDCPerOPTION); //(1e6 * 1e18) / 1e6 = 1e18
            //Transfers from the msg.sender
            USDC.transferFrom(msg.sender, factoryOwner, ownerTxFee);
            USDC.transferFrom(msg.sender, AORISEATSADD.ownerOf(seatId), seatTxFee);
            USDC.transferFrom(msg.sender, maker, USDCAfterFee);
            //Transfers to the msg.sender
            OPTION.transfer(msg.sender, OPTIONToReceive);
            //Tracking the volume in the NFT
            AORISEATSADD.addTakerVolume(amountOfUSDC, seatId, factory);
        }
        //Storage
        USDCFilled += USDCAfterFee;
        if(OPTION.balanceOf(address(this)) == 0) {
            hasEnded = true;
        }
        emit Filled(msg.sender, USDCAfterFee, amountOfUSDC, hasEnded);
    }
    /**
        Cancel this order and refund all remaining tokens
    */
    function cancel() public nonReentrant {
        require(isFunded(), "no OPTION balance");
        require(msg.sender == maker);
        uint256 balance = OPTION.balanceOf(address(this));
        
        OPTION.transfer(msg.sender, balance);
        hasEnded = true;
        emit OfferCanceled(maker, balance);
    }
    
    //Check if the contract is funded still.
    function isFunded() public view returns (bool) {
        if (OPTION.balanceOf(address(this)) > 0 && hasBeenFunded) {
            return true;
        } else {
            return false;
        }
    }
    //View function to see if this offer still holds one USDC
    function isFundedOverOne() public view returns (bool) {
        if (OPTION.balanceOf(address(this)) > (10 ** OPTION.decimals())) {
            return true;
        } else {
            return false;
        }
    }

    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 z
    ) public pure returns (uint256) {
        return (x * y) / z;
    }

    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transfer(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), "safeTransfer: failed");
    }


    /**
        Additional view functions 
    */
    function getCurrentBalance() public view returns (uint256) {
        if (OPTION.balanceOf(address(this)) >= 1) {
            return OPTION.balanceOf(address(this));
        } else {
            return 0;
        }
    }
   function totalUSDCWanted() public view returns (uint256) {
        return (USDCPerOPTION * OPTIONSize) / 10**OPTIONDecimals;
    }
}

File 5 of 42 : Bid.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity ^0.8.13;

import "./OpenZeppelin/IERC20.sol";
import "./AoriSeats.sol";
import "./OpenZeppelin/Ownable.sol";
import "./OpenZeppelin/ReentrancyGuard.sol";
import "./Chainlink/AggregatorV3Interface.sol";

contract Bid is ReentrancyGuard {
    address public immutable factory;
    address public immutable factoryOwner;
    address public immutable maker;
    uint256 public immutable OPTIONPerUSDC;
    uint256 public immutable USDCSize;
    uint256 public immutable fee; // in bps, default is 30 bps
    uint256 public immutable feeMultiplier;
    uint256 public immutable duration;
    uint256 public endingTime;
    AoriSeats public immutable AORISEATSADD;
    bool public hasEnded = false;
    bool public hasBeenFunded = false;
    IERC20 public USDC;
    IERC20 public OPTION;
    uint256 public USDCDecimals = 6;
    uint256 public OPTIONDecimals = 18;
    uint256 public decimalDiff = (10**OPTIONDecimals) / (10**USDCDecimals);
    uint256 public immutable BPS_DIVISOR = 10000;


    event OfferFunded(address maker, uint256 USDCSize, uint256 duration);
    event Filled(address buyer, uint256 USDCAmount, uint256 AmountFilled, bool hasEnded);
    event OfferCanceled(address maker, uint256 USDCAmount);

    constructor(
        IERC20 _USDC,
        IERC20 _OPTION,
        AoriSeats _AORISEATSADD,
        address _maker,
        uint256 _OPTIONPerUSDC,
        uint256 _fee,
        uint256 _feeMultiplier,
        uint256 _duration, //in blocks
        uint256 _USDCSize
    ) {
        factory = msg.sender;
        factoryOwner = Ownable(factory).owner();
        USDC = _USDC;
        OPTION = _OPTION;
        AORISEATSADD = _AORISEATSADD;
        maker = _maker;
        OPTIONPerUSDC = _OPTIONPerUSDC;
        fee = _fee;
        feeMultiplier = _feeMultiplier;
        duration = _duration;
        USDCSize = _USDCSize;
    }
    

    
    // release trapped funds
    function withdrawTokens(address token) public {
        require(msg.sender == factoryOwner);
        if (token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
            payable(factoryOwner).transfer(address(this).balance);
        } else {
            uint256 balance = IERC20(token).balanceOf(address(this));
            safeTransfer(token, factoryOwner, balance);
        }
    }
    
    /**
        Fund the Ask with Aori option ERC20's
     */
    function fundContract() public nonReentrant {
        require(msg.sender == factory);
        //officially begin the countdown
        endingTime = endingTime + duration;
        hasBeenFunded = true;
        emit OfferFunded(maker, USDCSize, duration);
    }
    /**
        Partial or complete fill of the offer, with the requirement of trading through a seat
        regardless of whether the seat is owned or not.
        In the case of not owning the seat, a fee is charged in USDC.
    */
    function fill(uint256 amountOfOPTION, uint256 seatId) public nonReentrant {
        require(isFunded(), "no usdc balance");
        require(msg.sender != maker && msg.sender != factory, "Cannot take one's own order");
        require(!hasEnded, "offer has been previously been cancelled");
        require(block.timestamp <= endingTime, "This offer has expired");
        require(OPTION.balanceOf(msg.sender) >= amountOfOPTION, "Not enough USDC");
        require(AORISEATSADD.confirmExists(seatId) && AORISEATSADD.ownerOf(seatId) != address(0x0), "Seat does not exist");

        uint256 OPTIONAfterFee;
        uint256 USDCToReceive;
        uint256 refRate;

        if(msg.sender == AORISEATSADD.ownerOf(seatId)) {
            //Seat holders receive 0 fees for trading
            OPTIONAfterFee = amountOfOPTION;
            USDCToReceive = mulDiv(OPTIONAfterFee, 10**USDCDecimals, OPTIONPerUSDC); //1eY = (1eX * 1eY) / 1eX
            //Transfers
            OPTION.transferFrom(msg.sender, maker, OPTIONAfterFee);
            USDC.transfer(msg.sender, USDCToReceive);
        } else {
            //Deducts the fee from the options the taker will receive
            OPTIONAfterFee = amountOfOPTION;            
            USDCToReceive = mulDiv(amountOfOPTION, 10**USDCDecimals, OPTIONPerUSDC); //1eY = (1eX * 1eY) / 1eX
            //What the user will receive out of 100 percent in referral fees with a floor of 40
            refRate = (AORISEATSADD.getSeatScore(seatId) * 500) + 3500;
            //This means for Aori seat governance they should not allow more than 12 seats to be combined at once
            uint256 seatScoreFeeInBPS = mulDiv(fee, refRate, BPS_DIVISOR); //(10 * 4000) / 10000 (min)
            uint256 seatTxFee = mulDiv(USDCToReceive, seatScoreFeeInBPS, BPS_DIVISOR); //(10**6 * 10**6 / 10**4)
            uint256 ownerTxFee = mulDiv(USDCToReceive, fee - seatScoreFeeInBPS, BPS_DIVISOR);
            //Transfers from the msg.sender
            OPTION.transferFrom(msg.sender, maker, OPTIONAfterFee);
            //Fee transfers are all in USDC, so for Bids they're routed here
            //These are to the Factory, the Aori seatholder, then the buyer respectively.
            USDC.transfer(factoryOwner, ownerTxFee);
            USDC.transfer(AORISEATSADD.ownerOf(seatId), seatTxFee);
            USDC.transfer(msg.sender, USDCToReceive - (ownerTxFee + seatTxFee));
            //Tracking the volume in the NFT
            AORISEATSADD.addTakerVolume(USDCToReceive + ownerTxFee + seatTxFee, seatId, factory);
        }
        if(USDC.balanceOf(address(this)) == 0) {
            hasEnded = true;
        }
        emit Filled(msg.sender, OPTIONAfterFee, amountOfOPTION, hasEnded);
    }

    /**
        Cancel this order and refund all remaining tokens
    */
    function cancel() public nonReentrant {
        require(isFunded(), "no USDC balance");
        require(msg.sender == maker);
        uint256 balance = USDC.balanceOf(address(this));
        
        USDC.transfer(msg.sender, balance);
        hasEnded = true;
        emit OfferCanceled(maker, balance);
    }

    //Check if the contract is funded still.
    function isFunded() public view returns (bool) {
        if (USDC.balanceOf(address(this)) > 0 && hasBeenFunded) {
            return true;
        } else {
            return false;
        }
    }
    //View function to see if this offer still holds one USDC
    function isFundedOverOne() public view returns (bool) {
        if (USDC.balanceOf(address(this)) > (10 ** USDC.decimals())) {
            return true;
        } else {
            return false;
        }
    }

    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 z
    ) public pure returns (uint256) {
        return (x * y) / z;
    }

    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        // bytes4(keccak256(bytes('transfer(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), "safeTransfer: failed");
    }

    /**
        Additional view functions 
    */
    function getCurrentBalance() public view returns (uint256) {
        if (USDC.balanceOf(address(this)) >= 1) {
            return USDC.balanceOf(address(this));
        } else {
            return 0;
        }
    }

    function totalUSDCWanted() public view returns (uint256) {
        return (OPTIONPerUSDC * USDCSize) / 10**OPTIONDecimals;
    }
}

File 6 of 42 : CallFactory.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity ^0.8.13;

import "./OpenZeppelin/Ownable.sol";
import "./Interfaces/IAoriSeats.sol";
import "./AoriCall.sol";
import "./AoriSeats.sol";
import "./OpenZeppelin/IERC20.sol";
import "./Margin/MarginManager.sol";

contract CallFactory is Ownable {

    mapping(address => bool) isListed;
    AoriCall[] callMarkets;
    address public keeper;
    uint256 public fee;
    AoriSeats public AORISEATSADD;
    MarginManager public manager;

    constructor(AoriSeats _AORISEATSADD, MarginManager _manager) {
        AORISEATSADD = _AORISEATSADD;
        manager = _manager;
    }

    event AoriCallCreated(
            address AoriCallAdd,
            uint256 strike, 
            uint256 duration, 
            IERC20 underlying, 
            IERC20 usdc,
            address oracle, 
            string name, 
            string symbol
        );

    /**
        Set the keeper of the Optiontroller.
        The keeper controls and deploys all new markets and orderbooks.
    */
    function setKeeper(address newKeeper) external onlyOwner returns(address) {
        keeper = newKeeper;
        return newKeeper;
    }

    function setAORISEATSADD(AoriSeats newAORISEATSADD) external onlyOwner returns(AoriSeats) {
        AORISEATSADD = newAORISEATSADD;
        return AORISEATSADD;
    }
    /**
        Deploys a new call option token at a designated strike and maturation block.
        Additionally deploys an orderbook to pair with the new ERC20 option token.
    */
    function createCallMarket(
            uint256 strikeInUSDC, 
            uint256 duration, 
            IERC20 UNDERLYING, 
            IERC20 USDC,
            address oracle,
            string memory name_, 
            string memory symbol_
            ) public returns (AoriCall) {

        require(msg.sender == keeper);

        AoriCall callMarket = new AoriCall(address(manager), AoriSeats(AORISEATSADD).getFeeMultiplier(), strikeInUSDC, duration, UNDERLYING, USDC, oracle, AoriSeats(AORISEATSADD), name_, symbol_);
        
        isListed[address(callMarket)] = true;
        callMarkets.push(callMarket);

        emit AoriCallCreated(address(callMarket), strikeInUSDC, duration, UNDERLYING, USDC, oracle, name_, symbol_);
        return (callMarket);
    }

    //Checks if an individual Call/Put is listed
    function checkIsListed(address market) external view returns(bool) {
        return isListed[market];
    }
    
    function getAORISEATSADD() external view returns(address) {
        return address(AORISEATSADD);
    }
    
    function getAllCallMarkets() external view returns(AoriCall[] memory) {
        return callMarkets;
    }
}

File 7 of 42 : AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

File 8 of 42 : IAoriSeats.sol
// SPDX-License-Identifier: UNLICENSED
/**
           :=*#%%@@@@@@@%%#*=-.         
        =#@@#+==--=+*@@@@@@@@@@@#-      
      :@@%-           :*@@@@@@@@@@@-    
      @@%                =@@@@@@@@@@    
     .@@%                  +@@@@@@@%    
      #@@*                   -+##*=     
       *@@@+:                           
        :#@@@%=.                        
          :#@@@@%=.                     
            .+@@@@@%+.                  
               =%@@@@@%+:               
                 :#@@@@@@%+.            
                   -%@@@@@@@%=          
            .-+#%@@@@%#@@@@@@@@*:       
         -*%@@@@#=:    .*@@@@@@@@#:     
      .+@@@@@%-          .%@@@@@@@@*    
    .#@@@@@@-              +@@@@@@@@%.  
   +@@@@@@%.                =@@@@@@@@@. 
  #@@@@@@@.                  =@@@@@@@@% 
 #@@@@@@@+                    #@@@@@@@@+
=@@@@@@@@.     %        #.    .@@@@@@@@%
#@@@@@@@@      @*-....:+@.     %@@@@@@@@
@@@@@@@@%      @@@@@@@@@@.     *@@@@@@@@
@@@@@@@@%      @@%#**##@@.     *@@@@@@@#
%@@@@@@@@      @.       %.     #@@@@@@@-
=@@@@@@@@-     =        -      @@@@@@@* 
 %@@@@@@@%                    +@@@@@@#  
 .%@@@@@@@#                  :@@@@@@=   
  .#@@@@@@@#.               -@@@@@#.    
    -%@@@@@@@+            .*@@@@#:      
      -#@@@@@@@*=:    .:=#@@@%+.        
         -*%@@@@@@@@@@@@@%*=. 
              &@@@@@@@@%
 */
pragma solidity 0.8.19;

import "../OpenZeppelin/IERC20.sol";

interface IAoriSeats {

    function setMinter(address _minter) external returns (address);

    function setAORITOKEN(IERC20 newAORITOKEN) external returns (IERC20);

    function setBaseURI(string memory baseURI) external returns(string memory);

    function mintSeat() external returns (uint256);

    function combineSeats(uint256 seatIdOne, uint256 seatIdTwo) external returns(uint256);

    function separateSeats(uint256 seatId) external;

    function addPoints(uint256 pointsToAdd, address userAdd) external;

    function addTakerPoints(uint256 pointsToAdd, address userAdd, address Orderbook_) external;

    function addTakerVolume(uint256 volumeToAdd, uint256 seatId, address Orderbook_) external;

    function claimAORI(address claimer) external;

    function setMaxSeats(uint256 newMaxSeats) external  returns (uint256);
 
    function setFeeMultiplier(uint256 newFeeMultiplier) external  returns (uint256);

    function setMaxSeatScore(uint256 newMaxScore) external  returns(uint256);

    function setMinFee(uint256 newMintFee) external  returns (uint256);

    function getOptionMintingFee() external view returns (uint256);

    function confirmExists(uint256 seatId) external view returns (bool);

    function getTotalPoints(address user) external view returns (uint256);
    
    function getClaimablePoints(address user) external view returns (uint256);

    function getSeatScore(uint256 seatId) external view returns (uint256);

    function getmaxSeatScore() external view returns (uint256);
    
    function getFeeMultiplier() external view returns (uint256);

    function getSeatVolume(uint256 seatId) external view returns (uint256);
}

File 9 of 42 : MarginManager.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity 0.8.19;

import "../OpenZeppelin/Ownable.sol";
import "../Chainlink/AggregatorV3Interface.sol";
import "./PositionRouter.sol";
import "../OpenZeppelin/Ownable.sol";
import "../OpenZeppelin/ReentrancyGuard.sol";
import "./Vault.sol";

contract MarginManager is Ownable, ReentrancyGuard {
    
    // Storage variables
    PositionRouter public positionRouter;
    uint256 public immutable BPS_DIVISOR = 10000;
    uint256 public collateralRatio; //12000 by default, or 120%
    uint256 immutable expScale = 1e18;
    uint256 immutable USDCScale = 10**6;
    
    //Necessary mappings to store user data and open position/option data
    mapping(ERC20 => bool) public whitelistedAssets;
    mapping(ERC20 => Vault) public lpTokens;
    mapping(ERC20 => AggregatorV3Interface) public oracles;
    mapping(bytes32 => Position) public positions;
    //add address => position mapping for frontend

    struct Position {
        address account;
        bool isCall;
        address token;
        address option;
        uint256 strikeInUSDC;
        uint256 optionSize;
        uint256 collateral;
        uint256 entryMarginRate;
        uint256 lastAccrueTime;
        address orderbook;
        uint256 endingTime;
    }

    constructor(
        PositionRouter _positionRouter
    ){
        positionRouter = _positionRouter;
    }

    event PositionCreated(bytes32 key_, address _account, uint256 _optionSize, address _orderbook, bool _isCall);
    event PositionUpdated(bytes32 key_, address _account, uint256 _optionSize, address _orderbook, bool _isCall);

    /**
        Good
     */
    function openShortPosition(
        address account_,
        uint256 collateral,
        address orderbook,
        bool isCall,
        uint256 amountOfUnderlying,
        uint256 seatId
    ) public nonReentrant returns (bytes32){
        require(msg.sender == address(positionRouter));
        bytes32 key;
        Structs.Vars memory localVars;
        address option = address(Orderbook(orderbook).OPTION());
        ERC20 token;
        if(isCall) {
            token = ERC20(address(AoriCall(option).UNDERLYING()));
            //mint options
            localVars.optionsMinted = lpTokens[token].mintOptions(amountOfUnderlying, option, seatId, account_, true);
            //store position data
            key = getPositionKey(account_, localVars.optionsMinted, orderbook, true);
            Position storage position = positions[key];
            position.account = account_;
            position.isCall = true;
            position.option = option;
            position.strikeInUSDC = AoriCall(option).strikeInUSDC();
            position.optionSize = localVars.optionsMinted;
            position.collateral = collateral;
            position.entryMarginRate = positionRouter.getBorrowRate(token); //1e8 per block, 
            position.lastAccrueTime = block.timestamp;
            position.orderbook = orderbook;
            position.endingTime = AoriCall(option).endingTime();
            emit PositionCreated(key, account_, position.optionSize, position.orderbook, true);
        } else if(!isCall) {
            token = ERC20(address(AoriPut(option).USDC()));

            //mint options
            localVars.optionsMinted = lpTokens[token].mintOptions(amountOfUnderlying, option, seatId, account_, false);
            //store position data
            key = getPositionKey(account_, localVars.optionsMinted, orderbook, true);
            Position storage position = positions[key];
            position.account = account_;
            position.isCall = false;
            position.option = option;
            position.strikeInUSDC = AoriPut(option).strikeInUSDC();
            position.optionSize = localVars.optionsMinted;
            position.collateral = collateral;
            position.entryMarginRate = positionRouter.getBorrowRate(token);
            position.lastAccrueTime = block.timestamp;
            position.orderbook = orderbook;
            position.endingTime = AoriPut(option).endingTime();
            emit PositionCreated(key, account_, position.optionSize, position.orderbook, false);
        }
        return key;
    }

    /**
        Good
     */
    function settlePosition(address account, bytes32 key) public nonReentrant {
        Position memory position = positions[key];
        uint256 collateralMinusLoss;
        ERC20 underlying;
        if(position.isCall) {
            AoriCall(position.option).endingTime();
            require(block.timestamp >= AoriCall(position.option).endingTime(), "Option has not reached expiry");
            underlying = ERC20(address(AoriCall(position.option).UNDERLYING()));
            if(AoriCall(position.option).getITM() > 0) {
                lpTokens[underlying].settleITMOption(position.option, true);
                collateralMinusLoss = position.collateral - positionRouter.mulDiv(AoriCall(position.option).settlementPrice() - position.strikeInUSDC, position.optionSize, USDCScale); 
                underlying.approve(account, collateralMinusLoss);
                underlying.transfer(account, collateralMinusLoss);
                underlying.decreaseAllowance(account, underlying.allowance(address(this), account));
                delete positions[key];
                emit PositionUpdated(key, account, position.optionSize, position.orderbook, position.isCall);
            } else {
                lpTokens[underlying].settleOTMOption(position.option, true);
                underlying.approve(account, position.collateral);
                underlying.transfer(account, position.collateral);
                underlying.decreaseAllowance(account, underlying.allowance(address(this), account));
                delete positions[key];
                emit PositionUpdated(key, account, position.optionSize, position.orderbook, position.isCall);
            }
        } else {
            require(block.timestamp >= AoriCall(position.option).endingTime(), "Option has not reached expiry");
            underlying = ERC20(address(AoriPut(position.option).USDC()));
            if(AoriPut(position.option).getITM() > 0) {
                lpTokens[underlying].settleITMOption(position.option, false);
                collateralMinusLoss = position.collateral - positionRouter.mulDiv(position.strikeInUSDC - AoriPut(position.option).settlementPrice(), position.optionSize, expScale);
                doTransferOut(underlying, account, collateralMinusLoss);
                delete positions[key];
                emit PositionUpdated(key, account, position.optionSize, position.orderbook, position.isCall);
            } else {
                lpTokens[underlying].settleOTMOption(position.option, false);
                doTransferOut(underlying, account, collateralMinusLoss);
                delete positions[key];
                emit PositionUpdated(key, account, position.optionSize, position.orderbook, position.isCall);
            }
        }
    }
    /**
        Good
     */
    function addCollateral(bytes32 key, uint256 collateralToAdd) public nonReentrant returns (uint256) {
        Position memory position = positions[key];
        ERC20 underlying;        
        if(position.isCall) {
            underlying = ERC20(address(AoriCall(position.option).UNDERLYING()));
            underlying.transferFrom(msg.sender, address(this), collateralToAdd);
            position.collateral += collateralToAdd;
            emit PositionUpdated(key, position.account, position.optionSize, position.orderbook, true);
        } else {
            underlying = ERC20(address(AoriPut(position.option).UNDERLYING()));
            underlying.transferFrom(msg.sender, address(this), collateralToAdd);
            position.collateral += collateralToAdd;
            emit PositionUpdated(key, position.account, position.optionSize, position.orderbook, true);
        }
        return position.collateral;
    }
    /**
        Good
     */
    function liquidatePosition(bytes32 key, uint256 fairValueOfOption, address liquidator) public returns (uint256) {
        require(positionRouter.isLiquidator(msg.sender));
        Position memory position = positions[key];
        accruePositionInterest(key);
        Structs.Vars memory localVars;
        ERC20 underlying;
        if(position.isCall) {
            underlying = ERC20(address(AoriCall(position.option).UNDERLYING()));
            require(whitelistedAssets[underlying], "Asset it not whitelisted");
            (localVars.collateralVal, localVars.portfolioVal, localVars.isLiquidatable) = positionRouter.isLiquidatable(underlying, fairValueOfOption, position.optionSize, position.collateral, true);
            require(localVars.isLiquidatable, "Portfolio is not liquidatable");

            localVars.profit = localVars.collateralVal - localVars.portfolioVal;
            localVars.profitInUnderlying = positionRouter.mulDiv(localVars.profit, 10**underlying.decimals(), positionRouter.getPrice(oracles[underlying]));
            uint256 fairValueInUnderlying = positionRouter.mulDiv(fairValueOfOption, position.optionSize, positionRouter.getPrice(oracles[underlying]));
            localVars.collateralToLiquidator = fairValueInUnderlying + positionRouter.mulDiv(localVars.profitInUnderlying, positionRouter.liquidatorFee(), BPS_DIVISOR);
            //Liquidator sells us options
            doTransferOut(ERC20(position.option), address(lpTokens[underlying]), position.optionSize);
            lpTokens[underlying].closeHedgedPosition(position.option, true, position.optionSize);
            //transfer the profit to the liquidator
            doTransferOut(underlying, liquidator, localVars.collateralToLiquidator);
            //and profit to the vault
            doTransferOut(underlying, address(lpTokens[underlying]), position.collateral - localVars.collateralToLiquidator);
            //storage
            delete positions[key];
            emit PositionUpdated(key, position.account, position.optionSize, position.orderbook, true);
        } else {
            underlying = ERC20(address(AoriPut(position.option).USDC()));
            require(whitelistedAssets[underlying], "Asset it not whitelisted");
            (localVars.collateralVal, localVars.portfolioVal, localVars.isLiquidatable) = positionRouter.isLiquidatable(underlying, fairValueOfOption, position.optionSize, position.collateral, false);
            require(localVars.isLiquidatable, "Portfolio is not liquidatable");
            //Calculate the fees
            localVars.profit = localVars.collateralVal - localVars.portfolioVal;
            localVars.profitInUnderlying = positionRouter.mulDiv(localVars.profit, 10**USDCScale, positionRouter.getPrice(oracles[underlying]));
            localVars.collateralToLiquidator = fairValueOfOption + positionRouter.mulDiv(localVars.profitInUnderlying, positionRouter.liquidatorFee(), BPS_DIVISOR);
            //Liquidator sells the vault the options
            doTransferOut(AoriPut(position.option), address(lpTokens[underlying]), position.optionSize);
            lpTokens[underlying].closeHedgedPosition(position.option, true, position.optionSize);
            //transfer the profit to the liquidator
            doTransferOut(underlying, liquidator, localVars.collateralToLiquidator);
            //and profit to the vault
            doTransferOut(underlying, address(lpTokens[underlying]), position.collateral - localVars.collateralToLiquidator);
            
            AoriPut(position.option).liquidationSettlement(position.optionSize);
            //storage
            delete positions[key];
            emit PositionUpdated(key, position.account, position.optionSize, position.orderbook, false);
        }
    }
    /**
        Good
     */
    function accruePositionInterest(bytes32 key) public returns (bool) {
        Position memory position = positions[key];
        ERC20 underlying;
        //irm calc
        AoriCall call;
        AoriPut put;
        uint256 interestOwed;
        require(block.timestamp - position.lastAccrueTime > 0, "cannot accrue position interest at the moment of deployment");
        
        if(position.isCall) {
            call = AoriCall(position.option);
            underlying = ERC20(address(call.UNDERLYING()));
            uint256 interestFactor = ((positionRouter.getBorrowRate(underlying) + position.entryMarginRate) / 2) * (block.timestamp - position.lastAccrueTime);
            interestOwed = positionRouter.mulDiv(interestFactor, position.optionSize, expScale);
            doTransferOut(underlying, address(lpTokens[underlying]), interestOwed);
        } else {
            put = AoriPut(position.option);
            underlying = ERC20(address(put.UNDERLYING()));
            uint256 interestFactor = ((positionRouter.getBorrowRate(underlying) + position.entryMarginRate) / 2) * (block.timestamp - position.lastAccrueTime);
            uint256 USDCUnderlying = positionRouter.mulDiv(position.optionSize, position.strikeInUSDC, expScale);
            interestOwed = positionRouter.mulDiv(interestFactor, USDCUnderlying, expScale);
            doTransferOut(underlying, address(lpTokens[underlying]), interestOwed);
        }
        if(position.collateral > interestOwed) {
            position.collateral -= interestOwed;
            position.lastAccrueTime = block.timestamp;
            lpTokens[underlying].repaid(interestOwed);
            return true;
        } else {
            return false;
        }
    }
    /**
        Good
     */
    function whitelistAsset(ERC20 token, AggregatorV3Interface oracle) public onlyOwner nonReentrant returns(ERC20) {
        whitelistedAssets[token] = true;
        Vault lpToken = new Vault(token, string.concat("Aori Vault for",string(token.name())), string.concat("a",string(token.name())), MarginManager(address(this)));
        lpTokens[token] = lpToken;
        oracles[token] = oracle;
        return token;
    }

    function getPosition(address _account, uint256 _optionSize, address _orderbook, bool _isCall) public view returns (address, bool, address, uint256, uint256, uint256, uint256, uint256, address, uint256) {
        bytes32 key = getPositionKey(_account, _optionSize, _orderbook, _isCall);
        Position memory position = positions[key];
        return (
            position.account,
            position.isCall,
            position.option,
            position.strikeInUSDC,
            position.optionSize,
            position.collateral,
            position.entryMarginRate,
            position.lastAccrueTime,
            position.orderbook,
            position.endingTime
        );
    }

    function getPositionWithKey(bytes32 key) public view returns (address, bool, address, uint256, uint256, uint256, uint256, uint256, address, uint256) {
        Position memory position = positions[key];
        return (
            position.account,
            position.isCall,
            position.option,
            position.strikeInUSDC,
            position.optionSize,
            position.collateral,
            position.entryMarginRate,
            position.lastAccrueTime,
            position.orderbook,
            position.endingTime
        );
    }

    function getPositionKey(address _account, uint256 _optionSize, address _orderbook, bool _isCall) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(
            _account,
            _optionSize,
            _orderbook,
            _isCall
        ));
    }

    function vaultAdd(ERC20 token) public view returns (address) {
        require(whitelistedAssets[token], "Unsupported market");
        return address(lpTokens[token]);
    }

    function doTransferOut(ERC20 token, address receiver, uint256 amount) internal returns (bool) {
        token.approve(receiver, amount);
        token.transfer(receiver, amount);
        token.decreaseAllowance(receiver, token.allowance(address(this), receiver));
    }
}

File 10 of 42 : PositionRouter.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity 0.8.19;

import "../OpenZeppelin/Ownable.sol";
import "./MarginManager.sol";
import "../OpenZeppelin/ERC20.sol";
import "./Vault.sol";
import "./Structs.sol";
import "../AoriCall.sol";
import "../AoriPut.sol";
import "../Orderbook.sol";
import "../CallFactory.sol";
import "../PutFactory.sol";

contract PositionRouter is Ownable {

    address public callFactory;
    address public putFactory;
    MarginManager public manager;
    uint256 immutable tolerance = 2 hours;
    uint256 public immutable BPS_DIVISOR = 10000;
    uint256 immutable expScale = 1e18;
    uint256 immutable USDCScale = 1e6;
    mapping(address => bool) public isLiquidator;
    mapping(address => bool) public keeper;
    uint256 public liquidatorFee; //In BPS, 2500
    uint256 public liquidationRatio; //in bps over 10000, default 20000
    uint256 public initialMarginRatio; //20% of underlying, so 2000 base.
    uint256 public liquidatorSeatId; //seat held by this address
    mapping(ERC20 => IRM) public interestRateModels;

    mapping(bytes32 => Structs.OpenPositionRequest) public openPositionRequests;
    bytes32[] public openPositionRequestKeys;
    uint256 indexPosition;

    struct IRM { //All in 1e4 scale
        uint256 baseRate;
        uint256 kinkUtil;
        uint256 rateBeforeUtil;
        uint256 rateAfterUtil;
    }

    event RequestCreated(bytes32 key, address account, uint256 index);
    event OrderApproved(bytes32 key, address account, uint256 index);
    event OrderDenied(uint256 index);

    function initialize(
            address callFactory_, 
            address putFactory_, 
            MarginManager manager_, 
            uint256 liquidatorFee_, 
            uint256 liquidationRatio_, 
            uint256 initialMarginRatio_, 
            uint256 liquidatorSeatId_,
            address keeper_
        ) public onlyOwner {
        callFactory = callFactory_;
        putFactory = putFactory_;
        manager = manager_;
        liquidatorFee = liquidatorFee_;
        liquidationRatio = liquidationRatio_;
        initialMarginRatio = initialMarginRatio_;
        setLiquidatorSeatId(liquidatorSeatId_);
        setKeeper(keeper_);
    }
    

    function setLiquidator(address liquidator) public onlyOwner {
        isLiquidator[liquidator] = true;
    }
    function setKeeper(address _keeper) public onlyOwner {
        keeper[_keeper] = true;
    }
    function setLiquidatorFee(uint256 newFee) public onlyOwner returns(uint256) {
        liquidatorFee = newFee;
        return newFee;
    }
    function setLiquidatorSeatId(uint256 newLiquidatorSeatId) public onlyOwner returns(uint256) {
        liquidatorSeatId = newLiquidatorSeatId;
        return liquidatorSeatId;
    }
    function setLiquidatonThreshold(uint256 newThreshold) public onlyOwner returns(uint256) {
        liquidationRatio = newThreshold;
        return newThreshold;
    }
    function setInitialMarginRatio(uint256 newInitialMarginRatio) public onlyOwner returns(uint256) {
        initialMarginRatio = newInitialMarginRatio;
        return initialMarginRatio;
    }

    function openShortPositionRequest(
            address _account,
            address option,
            uint256 collateral,
            address orderbook,
            bool isCall,
            uint256 amountOfUnderlying,
            uint256 seatId
            ) 
        public returns (uint256) {
        require(amountOfUnderlying > 0, "Must request some borrow");
        address token;
        bytes32 requestKey;
        uint256 optionsToMint;
        uint256 currentIndex;
        if(isCall) {
            token = address(AoriCall(option).UNDERLYING());
            require(CallFactory(callFactory).checkIsListed(option), "Not a valid call market");
            require(AoriCall(option).endingTime() != 0, "Invalid maturity");

            optionsToMint = mulDiv(amountOfUnderlying, USDCScale, AoriCall(option).strikeInUSDC());
            ERC20(token).transferFrom(msg.sender, address(this), collateral);
            
            currentIndex = indexPosition;
            requestKey = getRequestKey(_account, indexPosition);
            indexPosition++;

            Structs.OpenPositionRequest storage positionRequest = openPositionRequests[requestKey];
            positionRequest.account = _account;
            positionRequest.collateral = collateral;
            positionRequest.seatId = seatId;
            positionRequest.orderbook = orderbook;
            positionRequest.isCall = true;
            positionRequest.amountOfUnderlying = amountOfUnderlying;
            positionRequest.endingTime = AoriCall(option).endingTime();

            openPositionRequestKeys.push(requestKey);
            emit RequestCreated(requestKey, _account, currentIndex);
            return currentIndex;
        } else {
            token = address(AoriPut(option).USDC());
            require(PutFactory(putFactory).checkIsListed(option), "Not a valid put market");
            require(AoriPut(option).endingTime() != 0, "Invalid maturity");

            optionsToMint = 10**(12) * mulDiv(amountOfUnderlying, USDCScale, AoriPut(option).strikeInUSDC());            
            ERC20(token).transferFrom(msg.sender, address(this), collateral);

            currentIndex = indexPosition;
            requestKey = getRequestKey(_account, currentIndex);
            indexPosition++;

            Structs.OpenPositionRequest storage positionRequest = openPositionRequests[requestKey];
            positionRequest.account = _account;
            positionRequest.collateral = collateral;
            positionRequest.seatId = seatId;
            positionRequest.orderbook = orderbook;
            positionRequest.isCall = false;
            positionRequest.amountOfUnderlying = amountOfUnderlying;
            positionRequest.endingTime = AoriPut(option).endingTime();
        
            openPositionRequestKeys.push(requestKey);
            emit RequestCreated(requestKey, _account, currentIndex);
            return currentIndex;
        }
        
    }

    function executeOpenPosition(uint256 indexToExecute) public returns (bytes32) {
        require(keeper[msg.sender]);
        bytes32 key = openPositionRequestKeys[indexToExecute];
        Structs.OpenPositionRequest memory positionRequest = openPositionRequests[key];
        ERC20 underlying;
        if(positionRequest.isCall) {
            underlying = AoriCall(address(Orderbook(positionRequest.orderbook).UNDERLYING(true)));
            underlying.approve(address(manager), positionRequest.collateral);
        } else if (!positionRequest.isCall){
            underlying = ERC20(address(Orderbook(positionRequest.orderbook).USDC()));
            underlying.approve(address(manager), positionRequest.collateral);
        }
        underlying.transfer(address(manager), positionRequest.collateral);
        bytes32 keyToEmit = manager.openShortPosition(
            positionRequest.account, 
            positionRequest.collateral, 
            positionRequest.orderbook, 
            positionRequest.isCall, 
            positionRequest.amountOfUnderlying, 
            positionRequest.seatId
        );

        emit OrderApproved(keyToEmit, positionRequest.account, indexToExecute);
        delete openPositionRequestKeys[indexToExecute];
        return keyToEmit;
    }

    function rejectIncreasePosition(uint256 indexToReject) public {
        require(keeper[msg.sender]);
        emit OrderDenied(indexToReject);
        delete openPositionRequestKeys[indexToReject];
    }

    /**
        Get the interest rate based on an inputted util
        @notice util is inputted in BPS
     */
    function getBorrowRate(ERC20 token) public view returns (uint256) {
        require(manager.whitelistedAssets(token),  "Unsupported vault");
        Vault vault = manager.lpTokens(token);
        uint256 util = mulDiv(vault.totalBorrows(), expScale, token.balanceOf(address(vault)) + vault.totalBorrows()); //1e18
        IRM memory irm = interestRateModels[token];
        if (util <= irm.kinkUtil) {
            return irm.baseRate + mulDiv(util, irm.rateBeforeUtil, expScale); //1e18 + 1e18 * 1e18 / 1e18
        } else {
            //1e18 * 1e18 / 1e18 + (1e18 - 1e18) * 1e18 / 1e18
            uint256 prePlusPost = mulDiv(irm.kinkUtil, irm.rateBeforeUtil, expScale) + mulDiv((util - irm.kinkUtil), irm.rateAfterUtil, expScale);
            return (prePlusPost + irm.baseRate);
        }
    }

    function isLiquidatable(ERC20 token, uint256 fairValueOfOption, uint256 optionSize, uint256 collateral, bool isCall) public view returns(uint256, uint256, bool) {
        uint256 collateralVal;
        uint256 positionVal;
        uint256 liquidationThreshold;
        if(isCall) {
            collateralVal = mulDiv(getPrice(manager.oracles(token)), collateral, 10**token.decimals());
            positionVal = mulDiv(fairValueOfOption, optionSize, expScale);
            liquidationThreshold = mulDiv(positionVal, liquidationRatio, BPS_DIVISOR);
            if(liquidationThreshold >= collateralVal) {
                return (collateralVal, positionVal, true);
            } else {
                return (collateralVal, positionVal, false);
            }
        } else {
            collateralVal = mulDiv(getPrice(manager.oracles(token)), optionSize, expScale);
            positionVal = mulDiv(fairValueOfOption, optionSize, expScale);
            liquidationThreshold = mulDiv(positionVal, liquidationRatio, BPS_DIVISOR);
            if(liquidationThreshold >= collateralVal) {
                return (collateralVal, positionVal, true);
            } else {
                return (collateralVal, positionVal, false);
            }
        }
    }

    function getInitialMargin(ERC20 token, uint256 fairValueInUSDCScale, uint256 optionSize, bool isCall) public view returns(uint256) {
        uint256 positionVal;
        if(isCall) {
            positionVal = mulDiv(fairValueInUSDCScale, optionSize, expScale); //1e6 * 1e18 / 1e18
            return mulDiv(positionVal, expScale, getPrice(manager.oracles(token))) + mulDiv(optionSize, initialMarginRatio, BPS_DIVISOR); 
        } else {
            // .2 underlying plus fair val
            positionVal = fairValueInUSDCScale + mulDiv(getPrice(manager.oracles(token)), initialMarginRatio, BPS_DIVISOR);
            return mulDiv(positionVal, optionSize, expScale);
        }
    }
 

    function updateIRM(ERC20 token, uint256 _baseRate, uint256 _kinkUtil, uint256 _rateBeforeUtil, uint256 _rateAfterUtil) public onlyOwner returns (IRM memory) {
        IRM memory irm;
        irm.baseRate = _baseRate;
        irm.kinkUtil = _kinkUtil;
        irm.rateBeforeUtil = _rateBeforeUtil;
        irm.rateAfterUtil = _rateAfterUtil;
        interestRateModels[token] = irm;
        return interestRateModels[token];
    }

    /** 
        Get the price converted from Chainlink format to USDC
    */
    function getPrice(AggregatorV3Interface oracle) public view returns (uint256) {
        (, int256 price,  ,uint256 updatedAt,  ) = oracle.latestRoundData();
        require(price >= 0, "Negative Prices are not allowed");
        require(block.timestamp <= updatedAt + tolerance, "Price is too stale to be trustworthy"); // also works if updatedAt is 0
        if (price == 0) {
            return 0;
        } else {
            //8 is the decimals() of chainlink oracles, return USDC scale
            return (uint256(price) / (10**2));
        }
    }

    function getPosition(address _account, uint256 _index) public view returns (address, uint256, uint256, address, bool, uint256, uint256) {
        bytes32 key = getRequestKey(_account, _index);
        Structs.OpenPositionRequest memory positionRequest = openPositionRequests[key];
        return (
            positionRequest.account,
            positionRequest.collateral,
            positionRequest.seatId,
            positionRequest.orderbook,
            positionRequest.isCall,
            positionRequest.amountOfUnderlying,
            positionRequest.endingTime
        );
    }

    function getRequestKey(address _account, uint256 _index) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(_account, _index));
    }

    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 z
    ) public pure returns (uint256) {
        return (x * y) / z;
    }
}

File 11 of 42 : Structs.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;
import "../OpenZeppelin/ERC20.sol";

library Structs {
    struct OpenPositionRequest {
        address account;
        uint256 collateral;
        address orderbook;
        bool isCall;
        uint256 amountOfUnderlying;
        uint256 seatId;
        uint256 endingTime;
    }
    
    struct Vars {
        uint256 optionsMinted;
        uint256 collateralVal;
        uint256 portfolioVal;
        uint256 collateralToLiquidator;
        uint256 profit;
        uint256 profitInUnderlying;
        bool isLiquidatable;
    }
    
    struct settleVars {
        uint256 tokenBalBefore;
        uint256 tokenDiff;
        uint256 optionsSold;
    }
}

File 12 of 42 : Vault.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity 0.8.19;

import "../OpenZeppelin/Ownable.sol";
import "../OpenZeppelin/ERC20.sol";
import "../Chainlink/AggregatorV3Interface.sol";
import "./MarginManager.sol";
import "../AoriCall.sol";
import "../AoriPut.sol";
import "../OpenZeppelin/Ownable.sol";
import "../OpenZeppelin/ReentrancyGuard.sol";
import "../OpenZeppelin/ERC4626.sol";
import "./Structs.sol";

contract Vault is Ownable, ReentrancyGuard, ERC4626 {

    ERC20 token;
    MarginManager manager;
    mapping(address => bool) public isSettled;
    uint256 USDCScale = 10**6;

    // struct settleVars {
    //     uint256 tokenBalBefore;
    //     uint256 tokenDiff;
    //     uint256 optionsSold;
    // }
    
    constructor(ERC20 asset, string memory name, string memory symbol, MarginManager manager_
    )  ERC4626(asset, name, symbol) {
        manager = manager_;
        token = ERC20(asset);
    }

    function depositAssets(uint256 assets, address receiver) public nonReentrant {
        deposit(assets, receiver);
    }

    function withdrawAssets(uint256 assets, address receiver) public nonReentrant {
        withdraw(assets, receiver, receiver);
    }

    // mintOptions(amountOfUnderlying, option, seatId, _account, true);
    function mintOptions(uint256 amountOfUnderlying, address option, uint256 seatId, address account, bool isCall) public nonReentrant returns (uint256) {
        require(msg.sender == address(manager));
        totalBorrows += amountOfUnderlying;
        uint256 optionsMinted;
        if(isCall) {
            AoriCall(option).UNDERLYING().approve(option, amountOfUnderlying);
            optionsMinted = AoriCall(option).mintCall(amountOfUnderlying, account, seatId);
            return optionsMinted;
        } else {
            AoriPut(option).USDC().approve(option, amountOfUnderlying);
            optionsMinted = AoriPut(option).mintPut(amountOfUnderlying, account, seatId);
            return optionsMinted;
        }
    }

    function settleITMOption(address option, bool isCall) public nonReentrant returns (uint256) {
        Structs.settleVars memory vars;
        if(isSettled[option]) {
            return 0;
        } else {
            require(AoriCall(option).endingTime() <= block.timestamp || AoriPut(option).endingTime() <= block.timestamp, "Option has not expired");
            vars.tokenBalBefore = token.balanceOf(address(this));
            if(isCall) {
                vars.optionsSold = AoriCall(option).getOptionsSold(address(this));
                AoriCall(option).sellerSettlementITM();
                isSettled[option] = true;
            } else {                
                vars.optionsSold = AoriPut(option).getOptionsSold(address(this));
                AoriPut(option).sellerSettlementITM();
                isSettled[option] = true;
            }
            vars.tokenDiff = token.balanceOf(address(this)) - vars.tokenBalBefore;
            totalBorrows -= vars.tokenDiff;
            return vars.tokenDiff;
        }
    }

    function settleOTMOption(address option, bool isCall) public nonReentrant returns (uint256) {
        Structs.settleVars memory vars;
        if(isSettled[option]) {
            return 0;
        } else {
            if(isCall) {
                vars.tokenBalBefore = token.balanceOf(address(this));            
                AoriCall(option).sellerSettlementOTM();
                isSettled[option] = true;
            } else {
                vars.tokenBalBefore = token.balanceOf(address(this));
                AoriPut(option).sellerSettlementOTM();
                isSettled[option] = true;
            }
            vars.tokenDiff = token.balanceOf(address(this)) - vars.tokenBalBefore;
            totalBorrows -= vars.tokenDiff;
            return vars.tokenDiff;
        }
    }

    function closeHedgedPosition(address option, bool isCall, uint256 optionsToSettle) public {
        require(msg.sender == address(manager));
        if(isCall) {
            AoriCall(option).liquidationSettlement(optionsToSettle);
        } else {
            AoriPut(option).liquidationSettlement(optionsToSettle);
        }
    }

    function repaid(uint256 assets) public returns (uint256) {
        require(msg.sender == address(manager));
        totalBorrows -= assets;
        return assets;    
    }
}

File 13 of 42 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * 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.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @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`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
        }
    }
}

File 14 of 42 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * 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.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @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`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
        }
    }
}

File 15 of 42 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

File 16 of 42 : ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./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);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

File 17 of 42 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./IERC20Metadata.sol";
import "./Context.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}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * 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 ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_, uint8 decimals_) {
        _name = name_;
        _symbol = symbol_;
        _decimals = decimals_;
    }

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

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        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 override(IERC20, IERC20Metadata) returns (uint8) {
        return _decimals;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

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

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

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

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` 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 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * 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 `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `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.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` 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.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

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

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

File 18 of 42 : ERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/common/ERC2981.sol)

pragma solidity ^0.8.0;

import "./IERC2981.sol";
import "./ERC165.sol";

/**
 * @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
 *
 * Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
 * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
 *
 * Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
 * fee is specified in basis points by default.
 *
 * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
 * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
 * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
 *
 * _Available since v4.5._
 */
abstract contract ERC2981 is IERC2981, ERC165 {
    struct RoyaltyInfo {
        address receiver;
        uint96 royaltyFraction;
    }

    RoyaltyInfo private _defaultRoyaltyInfo;
    mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
        return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @inheritdoc IERC2981
     */
    function royaltyInfo(uint256 tokenId, uint256 salePrice) public view virtual override returns (address, uint256) {
        RoyaltyInfo memory royalty = _tokenRoyaltyInfo[tokenId];

        if (royalty.receiver == address(0)) {
            royalty = _defaultRoyaltyInfo;
        }

        uint256 royaltyAmount = (salePrice * royalty.royaltyFraction) / _feeDenominator();

        return (royalty.receiver, royaltyAmount);
    }

    /**
     * @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
     * fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
     * override.
     */
    function _feeDenominator() internal pure virtual returns (uint96) {
        return 10000;
    }

    /**
     * @dev Sets the royalty information that all ids in this contract will default to.
     *
     * Requirements:
     *
     * - `receiver` cannot be the zero address.
     * - `feeNumerator` cannot be greater than the fee denominator.
     */
    function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
        require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
        require(receiver != address(0), "ERC2981: invalid receiver");

        _defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
    }

    /**
     * @dev Removes default royalty information.
     */
    function _deleteDefaultRoyalty() internal virtual {
        delete _defaultRoyaltyInfo;
    }

    /**
     * @dev Sets the royalty information for a specific token id, overriding the global default.
     *
     * Requirements:
     *
     * - `receiver` cannot be the zero address.
     * - `feeNumerator` cannot be greater than the fee denominator.
     */
    function _setTokenRoyalty(uint256 tokenId, address receiver, uint96 feeNumerator) internal virtual {
        require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
        require(receiver != address(0), "ERC2981: Invalid parameters");

        _tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
    }

    /**
     * @dev Resets royalty information for the token id back to the global default.
     */
    function _resetTokenRoyalty(uint256 tokenId) internal virtual {
        delete _tokenRoyaltyInfo[tokenId];
    }
}

File 19 of 42 : ERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (token/ERC20/extensions/ERC4626.sol)

pragma solidity ^0.8.0;

import "./ERC20.sol";
import "./SafeERC20.sol";
import "./IERC4626.sol";
import "./Math.sol";

/**
 * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
 *
 * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
 * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
 * the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
 * contract and not the "assets" token which is an independent contract.
 *
 * [CAUTION]
 * ====
 * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
 * with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
 * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
 * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
 * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
 * verifying the amount received is as expected, using a wrapper that performs these checks such as
 * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
 *
 * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
 * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
 * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
 * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
 * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
 * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
 * expensive than it is profitable. More details about the underlying math can be found
 * xref:erc4626.adoc#inflation-attack[here].
 *
 * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
 * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
 * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
 * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
 * `_convertToShares` and `_convertToAssets` functions.
 *
 * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
 * ====
 *
 * _Available since v4.7._
 */
abstract contract ERC4626 is ERC20, IERC4626 {
    using Math for uint256;

    IERC20 private immutable _asset;
    uint8 private immutable _underlyingDecimals;
    uint256 public totalBorrows;

    /**
     * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
     */
    constructor(IERC20 asset_, string memory _name, string memory _symbol) ERC20(_name, _symbol, 18){
        (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
        _underlyingDecimals = success ? assetDecimals : 18;
        _asset = asset_;
    }

    /**
     * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
     */
    function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
        (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
            abi.encodeWithSelector(IERC20Metadata.decimals.selector)
        );
        if (success && encodedDecimals.length >= 32) {
            uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
            if (returnedDecimals <= type(uint8).max) {
                return (true, uint8(returnedDecimals));
            }
        }
        return (false, 0);
    }

    /**
     * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
     * "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
     * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
     *
     * See {IERC20Metadata-decimals}.
     */
    function decimals() public view virtual override(IERC20Metadata, IERC20, ERC20) returns (uint8) {
        return _underlyingDecimals + _decimalsOffset();
    }

    /** @dev See {IERC4626-asset}. */
    function asset() public view virtual override returns (address) {
        return address(_asset);
    }

    /** @dev See {IERC4626-totalAssets}. */
    function totalAssets() public view virtual override returns (uint256) {
        return _asset.balanceOf(address(this)) + totalBorrows;
    }

    /** @dev See {IERC4626-convertToShares}. */
    function convertToShares(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-convertToAssets}. */
    function convertToAssets(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-maxDeposit}. */
    function maxDeposit(address) public view virtual override returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxMint}. */
    function maxMint(address) public view virtual override returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxWithdraw}. */
    function maxWithdraw(address owner) public view virtual override returns (uint256) {
        return _convertToAssets(balanceOf(owner), Math.Rounding.Down);
    }

    /** @dev See {IERC4626-maxRedeem}. */
    function maxRedeem(address owner) public view virtual override returns (uint256) {
        return balanceOf(owner);
    }

    /** @dev See {IERC4626-previewDeposit}. */
    function previewDeposit(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-previewMint}. */
    function previewMint(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Up);
    }

    /** @dev See {IERC4626-previewWithdraw}. */
    function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Up);
    }

    /** @dev See {IERC4626-previewRedeem}. */
    function previewRedeem(uint256 shares) public view virtual override returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Down);
    }

    /** @dev See {IERC4626-deposit}. */
    function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {
        require(assets <= maxDeposit(receiver), "ERC4626: deposit more than max");

        uint256 shares = previewDeposit(assets);
        _deposit(_msgSender(), receiver, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-mint}.
     *
     * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
     * In this case, the shares will be minted without requiring any assets to be deposited.
     */
    function mint(uint256 shares, address receiver) public virtual override returns (uint256) {
        require(shares <= maxMint(receiver), "ERC4626: mint more than max");

        uint256 assets = previewMint(shares);
        _deposit(_msgSender(), receiver, assets, shares);

        return assets;
    }

    /** @dev See {IERC4626-withdraw}. */
    function withdraw(uint256 assets, address receiver, address owner) public virtual override returns (uint256) {
        require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max");

        uint256 shares = previewWithdraw(assets);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-redeem}. */
    function redeem(uint256 shares, address receiver, address owner) public virtual override returns (uint256) {
        require(shares <= maxRedeem(owner), "ERC4626: redeem more than max");

        uint256 assets = previewRedeem(shares);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return assets;
    }

    /**
     * @dev Internal conversion function (from assets to shares) with support for rounding direction.
     */
    function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
        return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
    }

    /**
     * @dev Internal conversion function (from shares to assets) with support for rounding direction.
     */
    function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
        return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
    }

    /**
     * @dev Deposit/mint common workflow.
     */
    function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
        // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
        // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
        // assets are transferred and before the shares are minted, which is a valid state.
        // slither-disable-next-line reentrancy-no-eth
        SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
        _mint(receiver, shares);

        emit Deposit(caller, receiver, assets, shares);
    }

    /**
     * @dev Withdraw/redeem common workflow.
     */
    function _withdraw(
        address caller,
        address receiver,
        address owner,
        uint256 assets,
        uint256 shares
    ) internal virtual {
        if (caller != owner) {
            _spendAllowance(owner, caller, shares);
        }

        // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
        // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
        // shares are burned and after the assets are transferred, which is a valid state.
        _burn(owner, shares);
        SafeERC20.safeTransfer(_asset, receiver, assets);

        emit Withdraw(caller, receiver, owner, assets, shares);
    }

    function _decimalsOffset() internal view virtual returns (uint8) {
        return 0;
    }
}

File 20 of 42 : ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./Address.sol";
import "./Context.sol";
import "./Strings.sol";
import "./ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    //Base URI
    string private _baseURI;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    // Optional mapping for token URIs
    mapping (uint256 => string) private _tokenURIs;

    //Mapping of tokenId to seatScore;
    mapping(uint256 => uint256) seatScore;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory _tokenURI = _tokenURIs[tokenId];
        string memory base = baseURI();

        // If there is no base URI, return the token URI.
        if (bytes(base).length == 0) {
            return _tokenURI;
        }
        // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
        if (bytes(_tokenURI).length > 0) {
            return string(abi.encodePacked(base, _tokenURI));
        }
        // If there is a baseURI but no tokenURI, concatenate the seatScore to the baseURI.
        string memory seatURI = string.concat(seatScore[tokenId].toString(), ".json");
        return string(abi.encodePacked(base, seatURI));
    }

    /**
    * @dev Returns the base URI set via {_setBaseURI}. This will be
    * automatically added as a prefix in {tokenURI} to each token's URI, or
    * to the token ID if no specific URI is set for that token ID.
    */
    function baseURI() public view virtual returns (string memory) {
        return _baseURI;
    }


    function _setBaseURI(string memory baseURI_) internal virtual {
        _baseURI = baseURI_;
    }


    /**
     * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
        require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
        _tokenURIs[tokenId] = _tokenURI;
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner or approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _safeTransfer(from, to, tokenId, data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _ownerOf(tokenId) != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId, 1);

        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");

        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }

        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId, 1);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId, 1);

        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721.ownerOf(tokenId);

        // Clear approvals
        delete _tokenApprovals[tokenId];

                // Clear metadata (if any)
        if (bytes(_tokenURIs[tokenId]).length != 0) {
            delete _tokenURIs[tokenId];
        }

        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId, 1);

        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");

        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];

        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId, 1);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 /* firstTokenId */,
        uint256 batchSize
    ) internal virtual {
        if (batchSize > 1) {
            if (from != address(0)) {
                _balances[from] -= batchSize;
            }
            if (to != address(0)) {
                _balances[to] += batchSize;
            }
        }
    }

    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}
}

File 21 of 42 : ERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/extensions/ERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "./ERC721.sol";
import "./IERC721Enumerable.sol";

/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account.
 */
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
    // Mapping from owner to list of owned token IDs
    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;

    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;

    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;

    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
        return _ownedTokens[owner][index];
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
        return _allTokens[index];
    }

    /**
     * @dev See {ERC721-_beforeTokenTransfer}.
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, firstTokenId, batchSize);

        if (batchSize > 1) {
            // Will only trigger during construction. Batch transferring (minting) is not available afterwards.
            revert("ERC721Enumerable: consecutive transfers not supported");
        }

        uint256 tokenId = firstTokenId;

        if (from == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
}

File 22 of 42 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @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);
}

File 23 of 42 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount
    ) external returns (bool);

    function decimals() external view returns (uint8);

}

File 24 of 42 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
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);
}

File 25 of 42 : IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @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.
 */
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].
     */
    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);
}

File 26 of 42 : IERC2981.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Interface for the NFT Royalty Standard.
 *
 * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
 * support for royalty payments across all NFT marketplaces and ecosystem participants.
 *
 * _Available since v4.5._
 */
interface IERC2981 is IERC165 {
    /**
     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
     */
    function royaltyInfo(
        uint256 tokenId,
        uint256 salePrice
    ) external view returns (address receiver, uint256 royaltyAmount);
}

File 27 of 42 : IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * _Available since v4.7._
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

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

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

File 28 of 42 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

File 29 of 42 : IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

File 30 of 42 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

File 31 of 42 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @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);
}

File 32 of 42 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "./AddressUpgradeable.sol";

/**
 * @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]
 * ```
 * 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 Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 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. Equivalent to `reinitializer(1)`.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _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.
     *
     * `initializer` is equivalent to `reinitializer(1)`, so 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.
     *
     * 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.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _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() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @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.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized < type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }
}

File 33 of 42 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

File 34 of 42 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "./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.
 *
 * By default, the owner account will be the one that deploys the contract. 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;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing 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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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);
    }
}

File 35 of 42 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract 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;

    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
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

File 36 of 42 : ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;
import "./Initializable.sol";

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

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

    uint256 private _status;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _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() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

        _;

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 37 of 42 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./IERC20Permit.sol";
import "./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;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @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, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 38 of 42 : SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

File 39 of 42 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./Math.sol";
import "./SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

File 40 of 42 : Orderbook.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity ^0.8.13;

import "./OpenZeppelin/Ownable.sol";
import "./AoriSeats.sol";
import "./Bid.sol";
import "./Ask.sol";
import "./AoriCall.sol";

contract Orderbook is Ownable {
    address public ORDERBOOKFACTORY;
    AoriSeats public immutable AORISEATSADD;

    IERC20 public immutable OPTION;
    IERC20 public immutable USDC;
    uint256 public immutable fee_; //In BPS
    uint256 public duration;
    uint256 public endingTime;
    Ask[] public asks;
    Bid[] public bids;
    mapping(address => bool) isAsk;
    mapping(address => bool) isBid;

    constructor(
        uint256 _fee,
        IERC20 _OPTION,
        IERC20 _USDC,
        AoriSeats _AORISEATSADD,
        uint256 _duration
    ) {
        ORDERBOOKFACTORY = msg.sender;
        duration = _duration;
        endingTime = block.timestamp + duration;
        AORISEATSADD = _AORISEATSADD;
        OPTION = _OPTION;
        USDC = _USDC;
        fee_ = _fee;
    }

    event AskCreated(address ask, uint256 , uint256 duration, uint256 OPTIONSize);
    event BidCreated(address bid, uint256 , uint256 duration, uint256 _USDCSize);
    /**
        Deploys an Ask.sol with the following parameters.    
     */
    function createAsk(uint256 _USDCPerOPTION, uint256 _duration, uint256 _OPTIONSize) public returns (Ask) {
        Ask ask = new Ask(OPTION, USDC, AORISEATSADD, msg.sender, _USDCPerOPTION, fee_, AoriSeats(AORISEATSADD).getFeeMultiplier() , _duration, _OPTIONSize);
        asks.push(ask);
        //transfer before storing the results
        OPTION.transferFrom(msg.sender, address(ask), _OPTIONSize);
        //storage
        isAsk[address(ask)] = true;
        ask.fundContract();
        emit AskCreated(address(ask), _USDCPerOPTION, _duration, _OPTIONSize);
        return ask;
    }
    /**
        Deploys an Bid.sol with the following parameters.    
     */
    function createBid(uint256 _OPTIONPerUSDC, uint256 _duration, uint256 _USDCSize) public returns (Bid) {
        Bid bid = new Bid(USDC, OPTION, AORISEATSADD, msg.sender, _OPTIONPerUSDC, fee_, AoriSeats(AORISEATSADD).getFeeMultiplier() , _duration, _USDCSize);
        bids.push(bid);
        //transfer before storing the results
        USDC.transferFrom(msg.sender, address(bid), _USDCSize);
        //storage
        isBid[address(bid)] = true;
        bid.fundContract();
        emit BidCreated(address(bid), _OPTIONPerUSDC, _duration, _USDCSize);
        return bid;
    }

    /**
        Accessory view functions to get data about active bids and asks of this orderbook
     */

    function getActiveAsks() external view returns (Ask[] memory) {
        Ask[] memory activeAsks = new Ask[](asks.length);
        uint256 count;
        for (uint256 i; i < asks.length; i++) {
            Ask ask = Ask(asks[i]);
            if (ask.isFunded() && !ask.hasEnded() && address(ask) != address(0)) {
                activeAsks[count++] = ask;
            }
        }

        return activeAsks;
    }
    
    function getActiveBids() external view returns (Bid[] memory) {
        Bid[] memory activeBids = new Bid[](bids.length);
        uint256 count;
        for (uint256 i; i < bids.length; i++) {
            Bid bid = Bid(bids[i]);
            if (bid.isFunded() && !bid.hasEnded() && address(bid) != address(0)) {
                activeBids[count++] = bid;
            }
        }

        return activeBids;
    }

    function getIsAsk(address ask) external view returns (bool) {
        return isAsk[ask];
    }
    
    function getIsBid(address bid) external view returns (bool) {
        return isBid[bid];
    }

    function UNDERLYING(bool isCall) external view returns (address) {
        if(isCall) {
            return address(AoriCall(address(OPTION)).UNDERLYING());
        } else {
            return address(USDC);
        }
    }
}

File 41 of 42 : OrderbookFactory.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity ^0.8.19;

import "./OpenZeppelin/Ownable.sol";
import "./AoriSeats.sol";
import "./OpenZeppelin/IERC20.sol";
import "./Orderbook.sol";

contract OrderbookFactory is Ownable {

    mapping(address => bool) isListedOrderbook;
    Orderbook[] public orderbookAdds;
    address public keeper;
    AoriSeats public AORISEATSADD;
    
    constructor(AoriSeats _AORISEATSADD) {
        AORISEATSADD = _AORISEATSADD;
    }

    event AoriOrderbookCreated(
        address AoriCallMarketAdd,
        uint256 fee,
        IERC20 underlyingAsset
    );

    /**
        Set the keeper of the Optiontroller.
        The keeper controls and deploys all new markets and orderbooks.
    */
    function setKeeper(address newKeeper) external onlyOwner returns(address) {
        keeper = newKeeper;
        return keeper;
    }
    
    function setAORISEATSADD(AoriSeats newAORISEATSADD) external onlyOwner returns(AoriSeats) {
        AORISEATSADD = newAORISEATSADD;
        return AORISEATSADD;
    }
    /**
        Gets the trading fee for the protocol.
     */
    function getTradingFee() internal view returns(uint256) {
        return AORISEATSADD.getTradingFee();
    }
    
    /**
        Deploys a new call option token at a designated strike and maturation block.
        Additionally deploys an orderbook to pair with the new ERC20 option token.
    */
    function createOrderbook(
            IERC20 OPTION_,
            IERC20 USDC,
            uint256 _duration
            ) public returns (Orderbook) {

        require(msg.sender == keeper);

        Orderbook orderbook =  new Orderbook(getTradingFee(), OPTION_, USDC, AORISEATSADD, _duration); 
        
        isListedOrderbook[address(orderbook)] = true;
        orderbookAdds.push(orderbook);

        emit AoriOrderbookCreated(address(orderbook), getTradingFee(), OPTION_);
        return (orderbook);
    }

    //Checks if an individual Orderbook is listed
    function checkIsListedOrderbook(address Orderbook_) public view returns(bool) {
        return isListedOrderbook[Orderbook_];
    }
    //Confirms for points that the Orderbook is a listed orderbook, THEN that the order is a listed order.
    function checkIsOrder(address Orderbook_, address order_) public view returns(bool) {
        require(checkIsListedOrderbook(Orderbook_), "Orderbook is not listed"); 
        require(Orderbook(Orderbook_).getIsBid(order_) == true || Orderbook(Orderbook_).getIsAsk(order_) == true, "Is not a confirmed order");

        return true;
    }

    function withdrawFees(IERC20 token, uint256 amount_) external onlyOwner returns(uint256) {
            IERC20(token).transfer(owner(), amount_);
            return amount_;
    }
    
    function getAllOrderbooks() external view returns(Orderbook[] memory) {
        return orderbookAdds;
    }
}

File 42 of 42 : PutFactory.sol
// SPDX-License-Identifier: UNLICENSED
/**                           
        /@#(@@@@@              
       @@      @@@             
        @@                      
        .@@@#                  
        ##@@@@@@,              
      @@@      /@@@&            
    .@@@  @   @  @@@@           
    @@@@  @@@@@  @@@@           
    @@@@  @   @  @@@/           
     @@@@       @@@             
       (@@@@#@@@      
    THE AORI PROTOCOL                           
 */
pragma solidity 0.8.19;

import "./OpenZeppelin/Ownable.sol";
import "./AoriSeats.sol";
import "./AoriPut.sol";
import "./OpenZeppelin/IERC20.sol";
import "./Margin/MarginManager.sol";

contract PutFactory is Ownable {

    mapping(address => bool) isListed;
    AoriPut[] putMarkets;
    address public keeper;
    uint256 public fee;
    AoriSeats public AORISEATSADD;
    MarginManager public manager;
    
    constructor(AoriSeats _AORISEATSADD, MarginManager _manager) {
        AORISEATSADD = _AORISEATSADD;
        manager = _manager;
    }

    event AoriPutCreated(
            IERC20 AoriPutAdd,
            uint256 strike, 
            uint256 duration, 
            IERC20 USDC,
            address oracle, 
            string name, 
            string symbol
        );

    /**
        Set the keeper of the Optiontroller.
        The keeper controls and deploys all new markets and orderbooks.
    */
    function setKeeper(address newKeeper) public onlyOwner returns(address) {
        keeper = newKeeper;
        return newKeeper;
    }

    function setAORISEATSADD(AoriSeats newAORISEATSADD) external onlyOwner returns(AoriSeats) {
        AORISEATSADD = newAORISEATSADD;
        return AORISEATSADD;
    }

    /**
        Deploys a new put option token at a designated strike and maturation block.
        Additionally deploys an orderbook to pair with the new ERC20 option token.
    */
    
    function createPutMarket(
            uint256 strikeInUSDC, 
            uint256 duration, 
            IERC20 USDC,
            IERC20 UNDERLYING,
            address oracle,
            string memory name_, 
            string memory symbol_
            ) public returns (AoriPut) {

        require(msg.sender == keeper);

        AoriPut putMarket = new AoriPut(address(manager), AoriSeats(AORISEATSADD).getFeeMultiplier(), strikeInUSDC, duration, USDC, UNDERLYING, oracle, AoriSeats(AORISEATSADD), name_, symbol_);

        isListed[address(putMarket)] = true;
        putMarkets.push(putMarket);

        emit AoriPutCreated(IERC20(address(putMarket)), strikeInUSDC, duration, USDC, oracle, name_, symbol_);
        return (putMarket);
    }

    //Checks if an individual Call/Put is listed
    function checkIsListed(address market) public view returns(bool) {
        return isListed[market];
    }
    
    function getAORISEATSADD() external view returns(AoriSeats) {
        return AORISEATSADD;
    }
    
    function getAllPutMarkets() external view returns(AoriPut[] memory) {
        return putMarkets;
    }
}

Settings
{
  "remappings": [
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "london",
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"uint256","name":"maxSeats_","type":"uint256"},{"internalType":"uint256","name":"mintFee_","type":"uint256"},{"internalType":"uint256","name":"tradingFee_","type":"uint256"},{"internalType":"uint256","name":"maxSeatScore_","type":"uint256"},{"internalType":"uint256","name":"feeMultiplier_","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"seatId","type":"uint256"},{"indexed":false,"internalType":"address","name":"SeatOwner","type":"address"}],"name":"FeeSetForSeat","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"NewMaxSeats","type":"uint256"}],"name":"MaxSeatChange","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"NewMintFee","type":"uint256"}],"name":"MintFeeChange","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":false,"internalType":"uint256","name":"NewTradingFee","type":"uint256"}],"name":"TradingFeeChange","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"CALLFACTORY","outputs":[{"internalType":"contract CallFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ORDERBOOKFACTORY","outputs":[{"internalType":"contract OrderbookFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PUTFACTORY","outputs":[{"internalType":"contract PutFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"volumeToAdd","type":"uint256"},{"internalType":"uint256","name":"seatId","type":"uint256"},{"internalType":"address","name":"Orderbook_","type":"address"}],"name":"addTakerVolume","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"seatIdOne","type":"uint256"},{"internalType":"uint256","name":"seatIdTwo","type":"uint256"}],"name":"combineSeats","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"seatId","type":"uint256"}],"name":"confirmExists","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentSeatId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"defaultSeatScore","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getFeeMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOptionMintingFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"getPoints","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"seatId","type":"uint256"}],"name":"getSeatScore","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"seatId","type":"uint256"}],"name":"getSeatVolume","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTradingFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxSeatScore","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"mintSeat","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"minter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"salePrice","type":"uint256"}],"name":"royaltyInfo","outputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"seatRoyaltyReceiver","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"seatId","type":"uint256"}],"name":"separateSeats","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"baseURI","type":"string"}],"name":"setBaseURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract CallFactory","name":"newCALLFACTORY","type":"address"}],"name":"setCallFactory","outputs":[{"internalType":"contract CallFactory","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"score","type":"uint256"}],"name":"setDefaultSeatScore","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newFeeMultiplier","type":"uint256"}],"name":"setFeeMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMaxScore","type":"uint256"}],"name":"setMaxSeatScore","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMaxSeats","type":"uint256"}],"name":"setMaxSeats","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newMintFee","type":"uint256"}],"name":"setMintFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_minter","type":"address"}],"name":"setMinter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract OrderbookFactory","name":"newORDERBOOKFACTORY","type":"address"}],"name":"setOrderbookFactory","outputs":[{"internalType":"contract OrderbookFactory","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract PutFactory","name":"newPUTFACTORY","type":"address"}],"name":"setPutFactory","outputs":[{"internalType":"contract PutFactory","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"seatId","type":"uint256"},{"internalType":"string","name":"_seatURI","type":"string"}],"name":"setSeatIdURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newSeatRoyaltyReceiver","type":"address"}],"name":"setSeatRoyaltyReceiver","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newTradingFee","type":"uint256"}],"name":"setTradingFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenOfOwnerByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60806040523480156200001157600080fd5b5060405162003033380380620030338339810160408190526200003491620003a4565b86866000620000448382620004cc565b506001620000538282620004cc565b505050620000706200006a620000e560201b60201c565b620000e9565b600160105560118590556013849055601483905560158290556016819055620000ae620000a5600f546001600160a01b031690565b61015e6200013b565b620000cb620000c5600f546001600160a01b031690565b62000240565b620000d760056200026c565b505050505050505062000598565b3390565b600f80546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6127106001600160601b0382161115620001af5760405162461bcd60e51b815260206004820152602a60248201527f455243323938313a20726f79616c7479206665652077696c6c206578636565646044820152692073616c65507269636560b01b60648201526084015b60405180910390fd5b6001600160a01b038216620002075760405162461bcd60e51b815260206004820152601960248201527f455243323938313a20696e76616c6964207265636569766572000000000000006044820152606401620001a6565b604080518082019091526001600160a01b039092168083526001600160601b039091166020909201829052600160a01b90910217600d55565b6200024a62000281565b601a80546001600160a01b0319166001600160a01b0392909216919091179055565b60006200027862000281565b50601b81905590565b600f546001600160a01b03163314620002dd5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401620001a6565b565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126200030757600080fd5b81516001600160401b0380821115620003245762000324620002df565b604051601f8301601f19908116603f011681019082821181831017156200034f576200034f620002df565b816040528381526020925086838588010111156200036c57600080fd5b600091505b8382101562000390578582018301518183018401529082019062000371565b600093810190920192909252949350505050565b600080600080600080600060e0888a031215620003c057600080fd5b87516001600160401b0380821115620003d857600080fd5b620003e68b838c01620002f5565b985060208a0151915080821115620003fd57600080fd5b506200040c8a828b01620002f5565b60408a015160608b015160808c015160a08d015160c0909d01519b9e939d50919b909a919950975095509350505050565b600181811c908216806200045257607f821691505b6020821081036200047357634e487b7160e01b600052602260045260246000fd5b50919050565b601f821115620004c757600081815260208120601f850160051c81016020861015620004a25750805b601f850160051c820191505b81811015620004c357828155600101620004ae565b5050505b505050565b81516001600160401b03811115620004e857620004e8620002df565b6200050081620004f984546200043d565b8462000479565b602080601f8311600181146200053857600084156200051f5750858301515b600019600386901b1c1916600185901b178555620004c3565b600085815260208120601f198616915b82811015620005695788860151825594840194600190910190840162000548565b5085821015620005885787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b612a8b80620005a86000396000f3fe608060405234801561001057600080fd5b50600436106103415760003560e01c80637abcabed116101b8578063c42eb79811610104578063e8899815116100a2578063ee204abb1161007c578063ee204abb14610717578063f2fde38b14610740578063f86d347414610753578063fca3b5aa1461076657600080fd5b8063e8899815146106a8578063e985e9c5146106c8578063eddd0d9c1461070457600080fd5b8063cd771f5c116100de578063cd771f5c14610670578063cdad0f4014610679578063db59637f1461068c578063e5a70ef71461069f57600080fd5b8063c42eb79814610641578063c87b56dd1461064a578063cb5d57bd1461065d57600080fd5b8063a22cb46511610171578063b667f5d61161014b578063b667f5d6146105ff578063b7742d7e14610612578063b88d4fde14610625578063c0de4d841461063857600080fd5b8063a22cb465146105c6578063b072f81c146105d9578063b0d54bcf146105ec57600080fd5b80637abcabed146105775780638611af171461058a5780638da5cb5b1461059257806395d89b41146105a3578063985f3e78146105ab57806398b89df0146105b357600080fd5b806329b597051161029257806351ae4361116102305780636c0360eb1161020a5780636c0360eb1461053457806370a082311461053c578063715018a61461054f578063768e1f921461055757600080fd5b806351ae4361146104fb57806355f804b31461050e5780636352211e1461052157600080fd5b80632f745c591161026c5780632f745c59146104af5780633d1eef2d146104c257806342842e0e146104d55780634f6ccce7146104e857600080fd5b806329b59705146104625780632a55205a1461046a5780632aa931561461049c57600080fd5b8063081812fc116102ff57806319c427fe116102d957806319c427fe146104215780631bd8db03146104345780631e6a311d1461043c57806323b872dd1461044f57600080fd5b8063081812fc146103e7578063095ea7b3146103fa57806318160ddd1461040f57600080fd5b8062d30a9d1461034657806301b7266e1461037657806301ffc9a71461038957806303496598146103ac57806306fdde03146103bf57806307546172146103d4575b600080fd5b6103596103543660046122cc565b610779565b6040516001600160a01b0390911681526020015b60405180910390f35b601754610359906001600160a01b031681565b61039c610397366004612306565b6107a6565b604051901515815260200161036d565b6103596103ba3660046122cc565b6107b7565b6103c76107e4565b60405161036d9190612373565b601954610359906001600160a01b031681565b6103596103f5366004612386565b610876565b61040d61040836600461239f565b61089d565b005b600b545b60405190815260200161036d565b61041361042f366004612386565b6109b7565b601454610413565b61041361044a366004612386565b6109ca565b61040d61045d3660046123cb565b6109dd565b601354610413565b61047d61047836600461240c565b610a0e565b604080516001600160a01b03909316835260208301919091520161036d565b61040d6104aa366004612386565b610aba565b6104136104bd36600461239f565b610b4e565b61040d6104d03660046124da565b610be4565b61040d6104e33660046123cb565b610c09565b6104136104f6366004612386565b610c24565b61039c610509366004612386565b610cb7565b61040d61051c366004612521565b610cc2565b61035961052f366004612386565b610cd6565b6103c7610d36565b61041361054a3660046122cc565b610d45565b61040d610dcb565b610413610565366004612386565b6000908152601e602052604090205490565b610413610585366004612386565b610ddf565b601654610413565b600f546001600160a01b0316610359565b6103c7610e00565b610413610e0f565b601c54610359906001600160a01b031681565b61040d6105d4366004612564565b610eaf565b61040d6105e736600461259d565b610eba565b6104136105fa366004612386565b610f72565b61040d61060d3660046122cc565b610fbc565b6103596106203660046122cc565b610fe6565b61040d6106333660046125d6565b611013565b610413601b5481565b61041360155481565b6103c7610658366004612386565b61104b565b601a54610359906001600160a01b031681565b61041360125481565b61041361068736600461240c565b611206565b601854610359906001600160a01b031681565b61041360165481565b6104136106b6366004612386565b60009081526008602052604090205490565b61039c6106d6366004612656565b6001600160a01b03918216600090815260066020908152604080832093909416825291909152205460ff1690565b610413610712366004612386565b6112d0565b6104136107253660046122cc565b6001600160a01b03166000908152601d602052604090205490565b61040d61074e3660046122cc565b61131a565b610413610761366004612386565b611390565b61040d6107743660046122cc565b6113da565b6000610783611404565b50601780546001600160a01b0319166001600160a01b0392909216918217905590565b60006107b18261145e565b92915050565b60006107c1611404565b50601880546001600160a01b0319166001600160a01b0392909216918217905590565b6060600080546107f390612684565b80601f016020809104026020016040519081016040528092919081815260200182805461081f90612684565b801561086c5780601f106108415761010080835404028352916020019161086c565b820191906000526020600020905b81548152906001019060200180831161084f57829003601f168201915b5050505050905090565b600061088182611483565b506000908152600560205260409020546001600160a01b031690565b60006108a882610cd6565b9050806001600160a01b0316836001600160a01b03160361091a5760405162461bcd60e51b815260206004820152602160248201527f4552433732313a20617070726f76616c20746f2063757272656e74206f776e656044820152603960f91b60648201526084015b60405180910390fd5b336001600160a01b0382161480610936575061093681336106d6565b6109a85760405162461bcd60e51b815260206004820152603d60248201527f4552433732313a20617070726f76652063616c6c6572206973206e6f7420746f60448201527f6b656e206f776e6572206f7220617070726f76656420666f7220616c6c0000006064820152608401610911565b6109b283836114d3565b505050565b60006109c1611404565b50601b81905590565b60006109d4611404565b50601681905590565b6109e73382611541565b610a035760405162461bcd60e51b8152600401610911906126be565b6109b28383836115c0565b6000828152600e602090815260408083208151808301909252546001600160a01b038116808352600160a01b9091046001600160601b0316928201929092528291610a83575060408051808201909152600d546001600160a01b0381168252600160a01b90046001600160601b031660208201525b602081015160009061271090610aa2906001600160601b031687612721565b610aac919061274e565b915196919550909350505050565b610ac381610cd6565b6001600160a01b0316336001600160a01b031614610ae057600080fd5b600081815260086020526040902080546001909155610afe82611731565b60005b818110156109b2576012805460009182610b1a83612762565b919050559050610b2a3382611811565b60009081526008602052604090206001905580610b4681612762565b915050610b01565b6000610b5983610d45565b8210610bbb5760405162461bcd60e51b815260206004820152602b60248201527f455243373231456e756d657261626c653a206f776e657220696e646578206f7560448201526a74206f6620626f756e647360a81b6064820152608401610911565b506001600160a01b03919091166000908152600960209081526040808320938352929052205490565b600f546001600160a01b03163314610bfb57600080fd5b610c05828261182b565b5050565b6109b283838360405180602001604052806000815250611013565b6000610c2f600b5490565b8210610c925760405162461bcd60e51b815260206004820152602c60248201527f455243373231456e756d657261626c653a20676c6f62616c20696e646578206f60448201526b7574206f6620626f756e647360a01b6064820152608401610911565b600b8281548110610ca557610ca561277b565b90600052602060002001549050919050565b60006107b1826118ad565b610cca611404565b610cd3816118ca565b50565b6000818152600360205260408120546001600160a01b0316806107b15760405162461bcd60e51b8152602060048201526018602482015277115490cdcc8c4e881a5b9d985b1a59081d1bdad95b88125160421b6044820152606401610911565b6060600280546107f390612684565b60006001600160a01b038216610daf5760405162461bcd60e51b815260206004820152602960248201527f4552433732313a2061646472657373207a65726f206973206e6f7420612076616044820152683634b21037bbb732b960b91b6064820152608401610911565b506001600160a01b031660009081526004602052604090205490565b610dd3611404565b610ddd60006118d6565b565b6000610de9611404565b6015548211610df757600080fd5b50601581905590565b6060600180546107f390612684565b6019546000906001600160a01b03163314610e2957600080fd5b601254610e37600a82612791565b600003610e7457600081815260086020526040902060019055601a54610e66906001600160a01b031682611928565b80610e7081612762565b9150505b601b54600082815260086020526040902055601954610e9c906001600160a01b031682611928565b610ea78160016127a5565b601255919050565b610c05338383611aa3565b610ec2611b71565b601c5460405163b023f46560e01b81526001600160a01b0383811660048301523360248301529091169063b023f46590604401602060405180830381865afa158015610f12573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f3691906127b8565b610f3f57600080fd5b6000828152601e6020526040902054610f5884826127a5565b6000848152601e6020526040902055506109b26001601055565b6000610f7c611404565b60148290556040518281527f1256ee5fcd29fc275d69307385fb52648f778ec92863b6e6561dbec2c203b3559060200160405180910390a1505060145490565b610fc4611404565b601a80546001600160a01b0319166001600160a01b0392909216919091179055565b6000610ff0611404565b50601c80546001600160a01b0319166001600160a01b0392909216918217905590565b61101d3383611541565b6110395760405162461bcd60e51b8152600401610911906126be565b61104584848484611bca565b50505050565b6060611056826118ad565b6110ba5760405162461bcd60e51b815260206004820152602f60248201527f4552433732314d657461646174613a2055524920717565727920666f72206e6f60448201526e3732bc34b9ba32b73a103a37b5b2b760891b6064820152608401610911565b600082815260076020526040812080546110d390612684565b80601f01602080910402602001604051908101604052809291908181526020018280546110ff90612684565b801561114c5780601f106111215761010080835404028352916020019161114c565b820191906000526020600020905b81548152906001019060200180831161112f57829003601f168201915b50505050509050600061115d610d36565b9050805160000361116f575092915050565b8151156111a15780826040516020016111899291906127d5565b60405160208183030381529060405292505050919050565b6000848152600860205260408120546111b990611bfd565b6040516020016111c99190612804565b604051602081830303815290604052905081816040516020016111ed9291906127d5565b6040516020818303038152906040529350505050919050565b600061121183610cd6565b6001600160a01b0316336001600160a01b031614801561124a575061123582610cd6565b6001600160a01b0316336001600160a01b0316145b61125357600080fd5b600082815260086020526040808220548583529082205461127491906127a5565b905060155481111561128557600080fd5b61128e84611731565b61129783611731565b60128054600091826112a883612762565b9190505590506112b83382611811565b60009081526008602052604090208190559392505050565b60006112da611404565b60138290556040518281527fe53f488988ae8d3c9852741e3213110b4ab061ecf25e0fdda464ac8d4a344af29060200160405180910390a1505060135490565b611322611404565b6001600160a01b0381166113875760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610911565b610cd3816118d6565b600061139a611404565b60118290556040518281527fce2bcec5c99c1195507764747bbd85f710459048e7964dba13c65a3c47d909df9060200160405180910390a1505060115490565b6113e2611404565b601980546001600160a01b0319166001600160a01b0392909216919091179055565b600f546001600160a01b03163314610ddd5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610911565b60006001600160e01b0319821663152a902d60e11b14806107b157506107b182611c90565b61148c816118ad565b610cd35760405162461bcd60e51b8152602060048201526018602482015277115490cdcc8c4e881a5b9d985b1a59081d1bdad95b88125160421b6044820152606401610911565b600081815260056020526040902080546001600160a01b0319166001600160a01b038416908117909155819061150882610cd6565b6001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45050565b60008061154d83610cd6565b9050806001600160a01b0316846001600160a01b0316148061159457506001600160a01b0380821660009081526006602090815260408083209388168352929052205460ff165b806115b85750836001600160a01b03166115ad84610876565b6001600160a01b0316145b949350505050565b826001600160a01b03166115d382610cd6565b6001600160a01b0316146115f95760405162461bcd60e51b81526004016109119061282d565b6001600160a01b03821661165b5760405162461bcd60e51b8152602060048201526024808201527f4552433732313a207472616e7366657220746f20746865207a65726f206164646044820152637265737360e01b6064820152608401610911565b6116688383836001611cb5565b826001600160a01b031661167b82610cd6565b6001600160a01b0316146116a15760405162461bcd60e51b81526004016109119061282d565b600081815260056020908152604080832080546001600160a01b03199081169091556001600160a01b0387811680865260048552838620805460001901905590871680865283862080546001019055868652600390945282852080549092168417909155905184937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b600061173c82610cd6565b905061174c816000846001611cb5565b61175582610cd6565b600083815260056020908152604080832080546001600160a01b03191690556007909152902080549192509061178a90612684565b1590506117a85760008281526007602052604081206117a891612269565b6001600160a01b03811660008181526004602090815260408083208054600019019055858352600390915280822080546001600160a01b0319169055518492907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908390a45050565b610c05828260405180602001604052806000815250611df5565b611834826118ad565b6118955760405162461bcd60e51b815260206004820152602c60248201527f4552433732314d657461646174613a2055524920736574206f66206e6f6e657860448201526b34b9ba32b73a103a37b5b2b760a11b6064820152608401610911565b60008281526007602052604090206109b282826128c0565b6000908152600360205260409020546001600160a01b0316151590565b6002610c0582826128c0565b600f80546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6001600160a01b03821661197e5760405162461bcd60e51b815260206004820181905260248201527f4552433732313a206d696e7420746f20746865207a65726f20616464726573736044820152606401610911565b611987816118ad565b156119d45760405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e746564000000006044820152606401610911565b6119e2600083836001611cb5565b6119eb816118ad565b15611a385760405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e746564000000006044820152606401610911565b6001600160a01b038216600081815260046020908152604080832080546001019055848352600390915280822080546001600160a01b0319168417905551839291907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b816001600160a01b0316836001600160a01b031603611b045760405162461bcd60e51b815260206004820152601960248201527f4552433732313a20617070726f766520746f2063616c6c6572000000000000006044820152606401610911565b6001600160a01b03838116600081815260066020908152604080832094871680845294825291829020805460ff191686151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a3505050565b600260105403611bc35760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610911565b6002601055565b611bd58484846115c0565b611be184848484611e28565b6110455760405162461bcd60e51b815260040161091190612980565b60606000611c0a83611f29565b600101905060008167ffffffffffffffff811115611c2a57611c2a61242e565b6040519080825280601f01601f191660200182016040528015611c54576020820181803683370190505b5090508181016020015b600019016f181899199a1a9b1b9c1cb0b131b232b360811b600a86061a8153600a8504945084611c5e57509392505050565b60006001600160e01b0319821663780e9d6360e01b14806107b157506107b182612001565b611cc184848484612051565b6001811115611d305760405162461bcd60e51b815260206004820152603560248201527f455243373231456e756d657261626c653a20636f6e7365637574697665207472604482015274185b9cd9995c9cc81b9bdd081cdd5c1c1bdc9d1959605a1b6064820152608401610911565b816001600160a01b038516611d8c57611d8781600b80546000838152600c60205260408120829055600182018355919091527f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db90155565b611daf565b836001600160a01b0316856001600160a01b031614611daf57611daf85826120d9565b6001600160a01b038416611dcb57611dc681612176565b611dee565b846001600160a01b0316846001600160a01b031614611dee57611dee8482612225565b5050505050565b611dff8383611928565b611e0c6000848484611e28565b6109b25760405162461bcd60e51b815260040161091190612980565b60006001600160a01b0384163b15611f1e57604051630a85bd0160e11b81526001600160a01b0385169063150b7a0290611e6c9033908990889088906004016129d2565b6020604051808303816000875af1925050508015611ea7575060408051601f3d908101601f19168201909252611ea491810190612a0f565b60015b611f04573d808015611ed5576040519150601f19603f3d011682016040523d82523d6000602084013e611eda565b606091505b508051600003611efc5760405162461bcd60e51b815260040161091190612980565b805181602001fd5b6001600160e01b031916630a85bd0160e11b1490506115b8565b506001949350505050565b60008072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b8310611f685772184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b830492506040015b6d04ee2d6d415b85acef81000000008310611f94576d04ee2d6d415b85acef8100000000830492506020015b662386f26fc100008310611fb257662386f26fc10000830492506010015b6305f5e1008310611fca576305f5e100830492506008015b6127108310611fde57612710830492506004015b60648310611ff0576064830492506002015b600a83106107b15760010192915050565b60006001600160e01b031982166380ac58cd60e01b148061203257506001600160e01b03198216635b5e139f60e01b145b806107b157506301ffc9a760e01b6001600160e01b03198316146107b1565b6001811115611045576001600160a01b03841615612097576001600160a01b03841660009081526004602052604081208054839290612091908490612a2c565b90915550505b6001600160a01b03831615611045576001600160a01b038316600090815260046020526040812080548392906120ce9084906127a5565b909155505050505050565b600060016120e684610d45565b6120f09190612a2c565b6000838152600a6020526040902054909150808214612143576001600160a01b03841660009081526009602090815260408083208584528252808320548484528184208190558352600a90915290208190555b506000918252600a602090815260408084208490556001600160a01b039094168352600981528383209183525290812055565b600b5460009061218890600190612a2c565b6000838152600c6020526040812054600b80549394509092849081106121b0576121b061277b565b9060005260206000200154905080600b83815481106121d1576121d161277b565b6000918252602080832090910192909255828152600c9091526040808220849055858252812055600b80548061220957612209612a3f565b6001900381819060005260206000200160009055905550505050565b600061223083610d45565b6001600160a01b0390931660009081526009602090815260408083208684528252808320859055938252600a9052919091209190915550565b50805461227590612684565b6000825580601f10612285575050565b601f016020900490600052602060002090810190610cd391905b808211156122b3576000815560010161229f565b5090565b6001600160a01b0381168114610cd357600080fd5b6000602082840312156122de57600080fd5b81356122e9816122b7565b9392505050565b6001600160e01b031981168114610cd357600080fd5b60006020828403121561231857600080fd5b81356122e9816122f0565b60005b8381101561233e578181015183820152602001612326565b50506000910152565b6000815180845261235f816020860160208601612323565b601f01601f19169290920160200192915050565b6020815260006122e96020830184612347565b60006020828403121561239857600080fd5b5035919050565b600080604083850312156123b257600080fd5b82356123bd816122b7565b946020939093013593505050565b6000806000606084860312156123e057600080fd5b83356123eb816122b7565b925060208401356123fb816122b7565b929592945050506040919091013590565b6000806040838503121561241f57600080fd5b50508035926020909101359150565b634e487b7160e01b600052604160045260246000fd5b600067ffffffffffffffff8084111561245f5761245f61242e565b604051601f8501601f19908116603f011681019082821181831017156124875761248761242e565b816040528093508581528686860111156124a057600080fd5b858560208301376000602087830101525050509392505050565b600082601f8301126124cb57600080fd5b6122e983833560208501612444565b600080604083850312156124ed57600080fd5b82359150602083013567ffffffffffffffff81111561250b57600080fd5b612517858286016124ba565b9150509250929050565b60006020828403121561253357600080fd5b813567ffffffffffffffff81111561254a57600080fd5b6115b8848285016124ba565b8015158114610cd357600080fd5b6000806040838503121561257757600080fd5b8235612582816122b7565b9150602083013561259281612556565b809150509250929050565b6000806000606084860312156125b257600080fd5b833592506020840135915060408401356125cb816122b7565b809150509250925092565b600080600080608085870312156125ec57600080fd5b84356125f7816122b7565b93506020850135612607816122b7565b925060408501359150606085013567ffffffffffffffff81111561262a57600080fd5b8501601f8101871361263b57600080fd5b61264a87823560208401612444565b91505092959194509250565b6000806040838503121561266957600080fd5b8235612674816122b7565b91506020830135612592816122b7565b600181811c9082168061269857607f821691505b6020821081036126b857634e487b7160e01b600052602260045260246000fd5b50919050565b6020808252602d908201527f4552433732313a2063616c6c6572206973206e6f7420746f6b656e206f776e6560408201526c1c881bdc88185c1c1c9bdd9959609a1b606082015260800190565b634e487b7160e01b600052601160045260246000fd5b80820281158282048414176107b1576107b161270b565b634e487b7160e01b600052601260045260246000fd5b60008261275d5761275d612738565b500490565b6000600182016127745761277461270b565b5060010190565b634e487b7160e01b600052603260045260246000fd5b6000826127a0576127a0612738565b500690565b808201808211156107b1576107b161270b565b6000602082840312156127ca57600080fd5b81516122e981612556565b600083516127e7818460208801612323565b8351908301906127fb818360208801612323565b01949350505050565b60008251612816818460208701612323565b64173539b7b760d91b920191825250600501919050565b60208082526025908201527f4552433732313a207472616e736665722066726f6d20696e636f72726563742060408201526437bbb732b960d91b606082015260800190565b601f8211156109b257600081815260208120601f850160051c810160208610156128995750805b601f850160051c820191505b818110156128b8578281556001016128a5565b505050505050565b815167ffffffffffffffff8111156128da576128da61242e565b6128ee816128e88454612684565b84612872565b602080601f831160018114612923576000841561290b5750858301515b600019600386901b1c1916600185901b1785556128b8565b600085815260208120601f198616915b8281101561295257888601518255948401946001909101908401612933565b50858210156129705787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60208082526032908201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560408201527131b2b4bb32b91034b6b83632b6b2b73a32b960711b606082015260800190565b6001600160a01b0385811682528416602082015260408101839052608060608201819052600090612a0590830184612347565b9695505050505050565b600060208284031215612a2157600080fd5b81516122e9816122f0565b818103818111156107b1576107b161270b565b634e487b7160e01b600052603160045260246000fdfea2646970667358221220564d99fc0eab28e985c0dc0a62ecb2f950589d852f2d885cc5148ae9e33173c664736f6c6343000813003300000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000000000000000019000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000a416f7269205365617473000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009414f524953454154530000000000000000000000000000000000000000000000

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106103415760003560e01c80637abcabed116101b8578063c42eb79811610104578063e8899815116100a2578063ee204abb1161007c578063ee204abb14610717578063f2fde38b14610740578063f86d347414610753578063fca3b5aa1461076657600080fd5b8063e8899815146106a8578063e985e9c5146106c8578063eddd0d9c1461070457600080fd5b8063cd771f5c116100de578063cd771f5c14610670578063cdad0f4014610679578063db59637f1461068c578063e5a70ef71461069f57600080fd5b8063c42eb79814610641578063c87b56dd1461064a578063cb5d57bd1461065d57600080fd5b8063a22cb46511610171578063b667f5d61161014b578063b667f5d6146105ff578063b7742d7e14610612578063b88d4fde14610625578063c0de4d841461063857600080fd5b8063a22cb465146105c6578063b072f81c146105d9578063b0d54bcf146105ec57600080fd5b80637abcabed146105775780638611af171461058a5780638da5cb5b1461059257806395d89b41146105a3578063985f3e78146105ab57806398b89df0146105b357600080fd5b806329b597051161029257806351ae4361116102305780636c0360eb1161020a5780636c0360eb1461053457806370a082311461053c578063715018a61461054f578063768e1f921461055757600080fd5b806351ae4361146104fb57806355f804b31461050e5780636352211e1461052157600080fd5b80632f745c591161026c5780632f745c59146104af5780633d1eef2d146104c257806342842e0e146104d55780634f6ccce7146104e857600080fd5b806329b59705146104625780632a55205a1461046a5780632aa931561461049c57600080fd5b8063081812fc116102ff57806319c427fe116102d957806319c427fe146104215780631bd8db03146104345780631e6a311d1461043c57806323b872dd1461044f57600080fd5b8063081812fc146103e7578063095ea7b3146103fa57806318160ddd1461040f57600080fd5b8062d30a9d1461034657806301b7266e1461037657806301ffc9a71461038957806303496598146103ac57806306fdde03146103bf57806307546172146103d4575b600080fd5b6103596103543660046122cc565b610779565b6040516001600160a01b0390911681526020015b60405180910390f35b601754610359906001600160a01b031681565b61039c610397366004612306565b6107a6565b604051901515815260200161036d565b6103596103ba3660046122cc565b6107b7565b6103c76107e4565b60405161036d9190612373565b601954610359906001600160a01b031681565b6103596103f5366004612386565b610876565b61040d61040836600461239f565b61089d565b005b600b545b60405190815260200161036d565b61041361042f366004612386565b6109b7565b601454610413565b61041361044a366004612386565b6109ca565b61040d61045d3660046123cb565b6109dd565b601354610413565b61047d61047836600461240c565b610a0e565b604080516001600160a01b03909316835260208301919091520161036d565b61040d6104aa366004612386565b610aba565b6104136104bd36600461239f565b610b4e565b61040d6104d03660046124da565b610be4565b61040d6104e33660046123cb565b610c09565b6104136104f6366004612386565b610c24565b61039c610509366004612386565b610cb7565b61040d61051c366004612521565b610cc2565b61035961052f366004612386565b610cd6565b6103c7610d36565b61041361054a3660046122cc565b610d45565b61040d610dcb565b610413610565366004612386565b6000908152601e602052604090205490565b610413610585366004612386565b610ddf565b601654610413565b600f546001600160a01b0316610359565b6103c7610e00565b610413610e0f565b601c54610359906001600160a01b031681565b61040d6105d4366004612564565b610eaf565b61040d6105e736600461259d565b610eba565b6104136105fa366004612386565b610f72565b61040d61060d3660046122cc565b610fbc565b6103596106203660046122cc565b610fe6565b61040d6106333660046125d6565b611013565b610413601b5481565b61041360155481565b6103c7610658366004612386565b61104b565b601a54610359906001600160a01b031681565b61041360125481565b61041361068736600461240c565b611206565b601854610359906001600160a01b031681565b61041360165481565b6104136106b6366004612386565b60009081526008602052604090205490565b61039c6106d6366004612656565b6001600160a01b03918216600090815260066020908152604080832093909416825291909152205460ff1690565b610413610712366004612386565b6112d0565b6104136107253660046122cc565b6001600160a01b03166000908152601d602052604090205490565b61040d61074e3660046122cc565b61131a565b610413610761366004612386565b611390565b61040d6107743660046122cc565b6113da565b6000610783611404565b50601780546001600160a01b0319166001600160a01b0392909216918217905590565b60006107b18261145e565b92915050565b60006107c1611404565b50601880546001600160a01b0319166001600160a01b0392909216918217905590565b6060600080546107f390612684565b80601f016020809104026020016040519081016040528092919081815260200182805461081f90612684565b801561086c5780601f106108415761010080835404028352916020019161086c565b820191906000526020600020905b81548152906001019060200180831161084f57829003601f168201915b5050505050905090565b600061088182611483565b506000908152600560205260409020546001600160a01b031690565b60006108a882610cd6565b9050806001600160a01b0316836001600160a01b03160361091a5760405162461bcd60e51b815260206004820152602160248201527f4552433732313a20617070726f76616c20746f2063757272656e74206f776e656044820152603960f91b60648201526084015b60405180910390fd5b336001600160a01b0382161480610936575061093681336106d6565b6109a85760405162461bcd60e51b815260206004820152603d60248201527f4552433732313a20617070726f76652063616c6c6572206973206e6f7420746f60448201527f6b656e206f776e6572206f7220617070726f76656420666f7220616c6c0000006064820152608401610911565b6109b283836114d3565b505050565b60006109c1611404565b50601b81905590565b60006109d4611404565b50601681905590565b6109e73382611541565b610a035760405162461bcd60e51b8152600401610911906126be565b6109b28383836115c0565b6000828152600e602090815260408083208151808301909252546001600160a01b038116808352600160a01b9091046001600160601b0316928201929092528291610a83575060408051808201909152600d546001600160a01b0381168252600160a01b90046001600160601b031660208201525b602081015160009061271090610aa2906001600160601b031687612721565b610aac919061274e565b915196919550909350505050565b610ac381610cd6565b6001600160a01b0316336001600160a01b031614610ae057600080fd5b600081815260086020526040902080546001909155610afe82611731565b60005b818110156109b2576012805460009182610b1a83612762565b919050559050610b2a3382611811565b60009081526008602052604090206001905580610b4681612762565b915050610b01565b6000610b5983610d45565b8210610bbb5760405162461bcd60e51b815260206004820152602b60248201527f455243373231456e756d657261626c653a206f776e657220696e646578206f7560448201526a74206f6620626f756e647360a81b6064820152608401610911565b506001600160a01b03919091166000908152600960209081526040808320938352929052205490565b600f546001600160a01b03163314610bfb57600080fd5b610c05828261182b565b5050565b6109b283838360405180602001604052806000815250611013565b6000610c2f600b5490565b8210610c925760405162461bcd60e51b815260206004820152602c60248201527f455243373231456e756d657261626c653a20676c6f62616c20696e646578206f60448201526b7574206f6620626f756e647360a01b6064820152608401610911565b600b8281548110610ca557610ca561277b565b90600052602060002001549050919050565b60006107b1826118ad565b610cca611404565b610cd3816118ca565b50565b6000818152600360205260408120546001600160a01b0316806107b15760405162461bcd60e51b8152602060048201526018602482015277115490cdcc8c4e881a5b9d985b1a59081d1bdad95b88125160421b6044820152606401610911565b6060600280546107f390612684565b60006001600160a01b038216610daf5760405162461bcd60e51b815260206004820152602960248201527f4552433732313a2061646472657373207a65726f206973206e6f7420612076616044820152683634b21037bbb732b960b91b6064820152608401610911565b506001600160a01b031660009081526004602052604090205490565b610dd3611404565b610ddd60006118d6565b565b6000610de9611404565b6015548211610df757600080fd5b50601581905590565b6060600180546107f390612684565b6019546000906001600160a01b03163314610e2957600080fd5b601254610e37600a82612791565b600003610e7457600081815260086020526040902060019055601a54610e66906001600160a01b031682611928565b80610e7081612762565b9150505b601b54600082815260086020526040902055601954610e9c906001600160a01b031682611928565b610ea78160016127a5565b601255919050565b610c05338383611aa3565b610ec2611b71565b601c5460405163b023f46560e01b81526001600160a01b0383811660048301523360248301529091169063b023f46590604401602060405180830381865afa158015610f12573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f3691906127b8565b610f3f57600080fd5b6000828152601e6020526040902054610f5884826127a5565b6000848152601e6020526040902055506109b26001601055565b6000610f7c611404565b60148290556040518281527f1256ee5fcd29fc275d69307385fb52648f778ec92863b6e6561dbec2c203b3559060200160405180910390a1505060145490565b610fc4611404565b601a80546001600160a01b0319166001600160a01b0392909216919091179055565b6000610ff0611404565b50601c80546001600160a01b0319166001600160a01b0392909216918217905590565b61101d3383611541565b6110395760405162461bcd60e51b8152600401610911906126be565b61104584848484611bca565b50505050565b6060611056826118ad565b6110ba5760405162461bcd60e51b815260206004820152602f60248201527f4552433732314d657461646174613a2055524920717565727920666f72206e6f60448201526e3732bc34b9ba32b73a103a37b5b2b760891b6064820152608401610911565b600082815260076020526040812080546110d390612684565b80601f01602080910402602001604051908101604052809291908181526020018280546110ff90612684565b801561114c5780601f106111215761010080835404028352916020019161114c565b820191906000526020600020905b81548152906001019060200180831161112f57829003601f168201915b50505050509050600061115d610d36565b9050805160000361116f575092915050565b8151156111a15780826040516020016111899291906127d5565b60405160208183030381529060405292505050919050565b6000848152600860205260408120546111b990611bfd565b6040516020016111c99190612804565b604051602081830303815290604052905081816040516020016111ed9291906127d5565b6040516020818303038152906040529350505050919050565b600061121183610cd6565b6001600160a01b0316336001600160a01b031614801561124a575061123582610cd6565b6001600160a01b0316336001600160a01b0316145b61125357600080fd5b600082815260086020526040808220548583529082205461127491906127a5565b905060155481111561128557600080fd5b61128e84611731565b61129783611731565b60128054600091826112a883612762565b9190505590506112b83382611811565b60009081526008602052604090208190559392505050565b60006112da611404565b60138290556040518281527fe53f488988ae8d3c9852741e3213110b4ab061ecf25e0fdda464ac8d4a344af29060200160405180910390a1505060135490565b611322611404565b6001600160a01b0381166113875760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608401610911565b610cd3816118d6565b600061139a611404565b60118290556040518281527fce2bcec5c99c1195507764747bbd85f710459048e7964dba13c65a3c47d909df9060200160405180910390a1505060115490565b6113e2611404565b601980546001600160a01b0319166001600160a01b0392909216919091179055565b600f546001600160a01b03163314610ddd5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610911565b60006001600160e01b0319821663152a902d60e11b14806107b157506107b182611c90565b61148c816118ad565b610cd35760405162461bcd60e51b8152602060048201526018602482015277115490cdcc8c4e881a5b9d985b1a59081d1bdad95b88125160421b6044820152606401610911565b600081815260056020526040902080546001600160a01b0319166001600160a01b038416908117909155819061150882610cd6565b6001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45050565b60008061154d83610cd6565b9050806001600160a01b0316846001600160a01b0316148061159457506001600160a01b0380821660009081526006602090815260408083209388168352929052205460ff165b806115b85750836001600160a01b03166115ad84610876565b6001600160a01b0316145b949350505050565b826001600160a01b03166115d382610cd6565b6001600160a01b0316146115f95760405162461bcd60e51b81526004016109119061282d565b6001600160a01b03821661165b5760405162461bcd60e51b8152602060048201526024808201527f4552433732313a207472616e7366657220746f20746865207a65726f206164646044820152637265737360e01b6064820152608401610911565b6116688383836001611cb5565b826001600160a01b031661167b82610cd6565b6001600160a01b0316146116a15760405162461bcd60e51b81526004016109119061282d565b600081815260056020908152604080832080546001600160a01b03199081169091556001600160a01b0387811680865260048552838620805460001901905590871680865283862080546001019055868652600390945282852080549092168417909155905184937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b600061173c82610cd6565b905061174c816000846001611cb5565b61175582610cd6565b600083815260056020908152604080832080546001600160a01b03191690556007909152902080549192509061178a90612684565b1590506117a85760008281526007602052604081206117a891612269565b6001600160a01b03811660008181526004602090815260408083208054600019019055858352600390915280822080546001600160a01b0319169055518492907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908390a45050565b610c05828260405180602001604052806000815250611df5565b611834826118ad565b6118955760405162461bcd60e51b815260206004820152602c60248201527f4552433732314d657461646174613a2055524920736574206f66206e6f6e657860448201526b34b9ba32b73a103a37b5b2b760a11b6064820152608401610911565b60008281526007602052604090206109b282826128c0565b6000908152600360205260409020546001600160a01b0316151590565b6002610c0582826128c0565b600f80546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6001600160a01b03821661197e5760405162461bcd60e51b815260206004820181905260248201527f4552433732313a206d696e7420746f20746865207a65726f20616464726573736044820152606401610911565b611987816118ad565b156119d45760405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e746564000000006044820152606401610911565b6119e2600083836001611cb5565b6119eb816118ad565b15611a385760405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e746564000000006044820152606401610911565b6001600160a01b038216600081815260046020908152604080832080546001019055848352600390915280822080546001600160a01b0319168417905551839291907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b816001600160a01b0316836001600160a01b031603611b045760405162461bcd60e51b815260206004820152601960248201527f4552433732313a20617070726f766520746f2063616c6c6572000000000000006044820152606401610911565b6001600160a01b03838116600081815260066020908152604080832094871680845294825291829020805460ff191686151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a3505050565b600260105403611bc35760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610911565b6002601055565b611bd58484846115c0565b611be184848484611e28565b6110455760405162461bcd60e51b815260040161091190612980565b60606000611c0a83611f29565b600101905060008167ffffffffffffffff811115611c2a57611c2a61242e565b6040519080825280601f01601f191660200182016040528015611c54576020820181803683370190505b5090508181016020015b600019016f181899199a1a9b1b9c1cb0b131b232b360811b600a86061a8153600a8504945084611c5e57509392505050565b60006001600160e01b0319821663780e9d6360e01b14806107b157506107b182612001565b611cc184848484612051565b6001811115611d305760405162461bcd60e51b815260206004820152603560248201527f455243373231456e756d657261626c653a20636f6e7365637574697665207472604482015274185b9cd9995c9cc81b9bdd081cdd5c1c1bdc9d1959605a1b6064820152608401610911565b816001600160a01b038516611d8c57611d8781600b80546000838152600c60205260408120829055600182018355919091527f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db90155565b611daf565b836001600160a01b0316856001600160a01b031614611daf57611daf85826120d9565b6001600160a01b038416611dcb57611dc681612176565b611dee565b846001600160a01b0316846001600160a01b031614611dee57611dee8482612225565b5050505050565b611dff8383611928565b611e0c6000848484611e28565b6109b25760405162461bcd60e51b815260040161091190612980565b60006001600160a01b0384163b15611f1e57604051630a85bd0160e11b81526001600160a01b0385169063150b7a0290611e6c9033908990889088906004016129d2565b6020604051808303816000875af1925050508015611ea7575060408051601f3d908101601f19168201909252611ea491810190612a0f565b60015b611f04573d808015611ed5576040519150601f19603f3d011682016040523d82523d6000602084013e611eda565b606091505b508051600003611efc5760405162461bcd60e51b815260040161091190612980565b805181602001fd5b6001600160e01b031916630a85bd0160e11b1490506115b8565b506001949350505050565b60008072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b8310611f685772184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b830492506040015b6d04ee2d6d415b85acef81000000008310611f94576d04ee2d6d415b85acef8100000000830492506020015b662386f26fc100008310611fb257662386f26fc10000830492506010015b6305f5e1008310611fca576305f5e100830492506008015b6127108310611fde57612710830492506004015b60648310611ff0576064830492506002015b600a83106107b15760010192915050565b60006001600160e01b031982166380ac58cd60e01b148061203257506001600160e01b03198216635b5e139f60e01b145b806107b157506301ffc9a760e01b6001600160e01b03198316146107b1565b6001811115611045576001600160a01b03841615612097576001600160a01b03841660009081526004602052604081208054839290612091908490612a2c565b90915550505b6001600160a01b03831615611045576001600160a01b038316600090815260046020526040812080548392906120ce9084906127a5565b909155505050505050565b600060016120e684610d45565b6120f09190612a2c565b6000838152600a6020526040902054909150808214612143576001600160a01b03841660009081526009602090815260408083208584528252808320548484528184208190558352600a90915290208190555b506000918252600a602090815260408084208490556001600160a01b039094168352600981528383209183525290812055565b600b5460009061218890600190612a2c565b6000838152600c6020526040812054600b80549394509092849081106121b0576121b061277b565b9060005260206000200154905080600b83815481106121d1576121d161277b565b6000918252602080832090910192909255828152600c9091526040808220849055858252812055600b80548061220957612209612a3f565b6001900381819060005260206000200160009055905550505050565b600061223083610d45565b6001600160a01b0390931660009081526009602090815260408083208684528252808320859055938252600a9052919091209190915550565b50805461227590612684565b6000825580601f10612285575050565b601f016020900490600052602060002090810190610cd391905b808211156122b3576000815560010161229f565b5090565b6001600160a01b0381168114610cd357600080fd5b6000602082840312156122de57600080fd5b81356122e9816122b7565b9392505050565b6001600160e01b031981168114610cd357600080fd5b60006020828403121561231857600080fd5b81356122e9816122f0565b60005b8381101561233e578181015183820152602001612326565b50506000910152565b6000815180845261235f816020860160208601612323565b601f01601f19169290920160200192915050565b6020815260006122e96020830184612347565b60006020828403121561239857600080fd5b5035919050565b600080604083850312156123b257600080fd5b82356123bd816122b7565b946020939093013593505050565b6000806000606084860312156123e057600080fd5b83356123eb816122b7565b925060208401356123fb816122b7565b929592945050506040919091013590565b6000806040838503121561241f57600080fd5b50508035926020909101359150565b634e487b7160e01b600052604160045260246000fd5b600067ffffffffffffffff8084111561245f5761245f61242e565b604051601f8501601f19908116603f011681019082821181831017156124875761248761242e565b816040528093508581528686860111156124a057600080fd5b858560208301376000602087830101525050509392505050565b600082601f8301126124cb57600080fd5b6122e983833560208501612444565b600080604083850312156124ed57600080fd5b82359150602083013567ffffffffffffffff81111561250b57600080fd5b612517858286016124ba565b9150509250929050565b60006020828403121561253357600080fd5b813567ffffffffffffffff81111561254a57600080fd5b6115b8848285016124ba565b8015158114610cd357600080fd5b6000806040838503121561257757600080fd5b8235612582816122b7565b9150602083013561259281612556565b809150509250929050565b6000806000606084860312156125b257600080fd5b833592506020840135915060408401356125cb816122b7565b809150509250925092565b600080600080608085870312156125ec57600080fd5b84356125f7816122b7565b93506020850135612607816122b7565b925060408501359150606085013567ffffffffffffffff81111561262a57600080fd5b8501601f8101871361263b57600080fd5b61264a87823560208401612444565b91505092959194509250565b6000806040838503121561266957600080fd5b8235612674816122b7565b91506020830135612592816122b7565b600181811c9082168061269857607f821691505b6020821081036126b857634e487b7160e01b600052602260045260246000fd5b50919050565b6020808252602d908201527f4552433732313a2063616c6c6572206973206e6f7420746f6b656e206f776e6560408201526c1c881bdc88185c1c1c9bdd9959609a1b606082015260800190565b634e487b7160e01b600052601160045260246000fd5b80820281158282048414176107b1576107b161270b565b634e487b7160e01b600052601260045260246000fd5b60008261275d5761275d612738565b500490565b6000600182016127745761277461270b565b5060010190565b634e487b7160e01b600052603260045260246000fd5b6000826127a0576127a0612738565b500690565b808201808211156107b1576107b161270b565b6000602082840312156127ca57600080fd5b81516122e981612556565b600083516127e7818460208801612323565b8351908301906127fb818360208801612323565b01949350505050565b60008251612816818460208701612323565b64173539b7b760d91b920191825250600501919050565b60208082526025908201527f4552433732313a207472616e736665722066726f6d20696e636f72726563742060408201526437bbb732b960d91b606082015260800190565b601f8211156109b257600081815260208120601f850160051c810160208610156128995750805b601f850160051c820191505b818110156128b8578281556001016128a5565b505050505050565b815167ffffffffffffffff8111156128da576128da61242e565b6128ee816128e88454612684565b84612872565b602080601f831160018114612923576000841561290b5750858301515b600019600386901b1c1916600185901b1785556128b8565b600085815260208120601f198616915b8281101561295257888601518255948401946001909101908401612933565b50858210156129705787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b60208082526032908201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560408201527131b2b4bb32b91034b6b83632b6b2b73a32b960711b606082015260800190565b6001600160a01b0385811682528416602082015260408101839052608060608201819052600090612a0590830184612347565b9695505050505050565b600060208284031215612a2157600080fd5b81516122e9816122f0565b818103818111156107b1576107b161270b565b634e487b7160e01b600052603160045260246000fdfea2646970667358221220564d99fc0eab28e985c0dc0a62ecb2f950589d852f2d885cc5148ae9e33173c664736f6c63430008130033

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

00000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001f40000000000000000000000000000000000000000000000000000000000000019000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000a416f7269205365617473000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009414f524953454154530000000000000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : name_ (string): Aori Seats
Arg [1] : symbol_ (string): AORISEATS
Arg [2] : maxSeats_ (uint256): 500
Arg [3] : mintFee_ (uint256): 25
Arg [4] : tradingFee_ (uint256): 10
Arg [5] : maxSeatScore_ (uint256): 5
Arg [6] : feeMultiplier_ (uint256): 1

-----Encoded View---------------
11 Constructor Arguments found :
Arg [0] : 00000000000000000000000000000000000000000000000000000000000000e0
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000120
Arg [2] : 00000000000000000000000000000000000000000000000000000000000001f4
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000019
Arg [4] : 000000000000000000000000000000000000000000000000000000000000000a
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000005
Arg [6] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [7] : 000000000000000000000000000000000000000000000000000000000000000a
Arg [8] : 416f726920536561747300000000000000000000000000000000000000000000
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000009
Arg [10] : 414f524953454154530000000000000000000000000000000000000000000000


Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.