ETH Price: $2,279.32 (-5.95%)

Transaction Decoder

Block:
21180660 at Nov-13-2024 06:48:11 PM +UTC
Transaction Fee:
0.025563941875450265 ETH $58.27
Gas Used:
289,037 Gas / 88.445222845 Gwei

Emitted Events:

603 X7DAO.Transfer( from=[Sender] 0xb66050e3eb239e9955aa897dd981e70621b4455f, to=X7DAOLiquidityHubV2, value=5970000000000000000000 )
604 X7DAO.Approval( owner=X7DAOLiquidityHubV2, spender=[Receiver] XchangeRouterV3, value=5970000000000000000000 )
605 X7DAO.Approval( owner=X7DAOLiquidityHubV2, spender=[Receiver] XchangeRouterV3, value=0 )
606 X7DAO.Transfer( from=X7DAOLiquidityHubV2, to=XchangePair, value=5970000000000000000000 )
607 WETH9.Transfer( src=XchangePair, dst=[Receiver] XchangeRouterV3, wad=4148846565499085 )
608 XchangePair.Sync( reserve0=14883969923841405728463984, reserve1=10360174097864920546 )
609 XchangePair.Swap( sender=[Receiver] XchangeRouterV3, amount0In=5970000000000000000000, amount1In=0, amount0Out=0, amount1Out=4148846565499085, to=[Receiver] XchangeRouterV3 )
610 WETH9.Withdrawal( src=[Receiver] XchangeRouterV3, wad=4148846565499085 )
611 X7DAO.Transfer( from=[Sender] 0xb66050e3eb239e9955aa897dd981e70621b4455f, to=XchangePair, value=193030000000000000000000 )
612 WETH9.Transfer( src=XchangePair, dst=[Receiver] XchangeRouterV3, wad=132378846823508353 )
613 XchangePair.Sync( reserve0=15076999923841405728463984, reserve1=10227795251041412193 )
614 XchangePair.Swap( sender=[Receiver] XchangeRouterV3, amount0In=193030000000000000000000, amount1In=0, amount0Out=0, amount1Out=132378846823508353, to=[Receiver] XchangeRouterV3 )
615 WETH9.Withdrawal( src=[Receiver] XchangeRouterV3, wad=132378846823508353 )

Account State Difference:

  Address   Before After State Difference Code
0x6913Bb5E...d3aB14130 0.685779847404985746 Eth0.689928693970484831 Eth0.004148846565499085
0x7105E64b...3b2eF2dA0
(beaverbuild)
21.57917610443634932 Eth21.580285463231709751 Eth0.001109358795360431
0xB66050E3...621B4455f
0.249331270939030245 Eth
Nonce: 217
0.356146175887088333 Eth
Nonce: 218
0.106814904948058088
0xb8dE6270...3dC7cF700
0xC02aaA39...83C756Cc2 2,854,419.383882887553741549 Eth2,854,419.247355194164734111 Eth0.136527693389007438

Execution Trace

XchangeRouterV3.multicall( deadline=1731524866, data=[eRrJRwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAqI8/GFNAOYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYz40L4SdR4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAoAAAAAAAAAAAAAAAALZgUOPrI56ZVaqJfdmB5wYhtEVfAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGc0+QIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAHEF5kv2fso66bEj8OXKK4Oy7y2gAAAAAAAAAAAAAAAAwCqqObIj/o0KDlxPJ+rZCDx1bMI=] ) => ( [] )
  • XchangeRouterV3.swapExactTokensForETHSupportingFeeOnTransferTokens( amountIn=199000000000000000000000, amountOutMin=111737666203186462, path=[0x7105E64bF67ECA3Ae9b123F0e5Ca2b83b2eF2dA0, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2], to=0xB66050E3eb239e9955AA897dd981e70621B4455f, deadline=1731524866 )
    • X7DAO.transferFrom( from=0xB66050E3eb239e9955AA897dd981e70621B4455f, to=0xb8dE6270640092463988B6860d68CA63dC7cF700, amount=199000000000000000000000 ) => ( True )
      • X7DAODiscountAuthority.discountRatio( swapper=0xB66050E3eb239e9955AA897dd981e70621B4455f ) => ( numerator=1, denominator=1 )
        • X7LiquidityMaxi.balanceOf( owner=0xB66050E3eb239e9955AA897dd981e70621B4455f ) => ( 0 )
        • X7EcosystemMaxi.balanceOf( owner=0xB66050E3eb239e9955AA897dd981e70621B4455f ) => ( 0 )
        • X7DAOLiquidityHubV2.processFees( tokenAddress=0x7105E64bF67ECA3Ae9b123F0e5Ca2b83b2eF2dA0 )
          • X7DAO.balanceOf( account=0x6913Bb5E6b85De1C47f0bc5C8ed3409d3aB14130 ) => ( 5970000000000000000000 )
          • X7DAO.balanceOf( account=0x6913Bb5E6b85De1C47f0bc5C8ed3409d3aB14130 ) => ( 5970000000000000000000 )
          • XchangeRouterV3.CALL( )
          • X7DAO.approve( spender=0x6b5422D584943BC8Cd0E10e239d624c6fE90fbB8, amount=5970000000000000000000 ) => ( True )
          • XchangeRouterV3.swapExactTokensForETHSupportingFeeOnTransferTokens( amountIn=5970000000000000000000, amountOutMin=0, path=[0x7105E64bF67ECA3Ae9b123F0e5Ca2b83b2eF2dA0, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2], to=0x6913Bb5E6b85De1C47f0bc5C8ed3409d3aB14130, deadline=1731523691 )
            • X7DAO.transferFrom( from=0x6913Bb5E6b85De1C47f0bc5C8ed3409d3aB14130, to=0xb8dE6270640092463988B6860d68CA63dC7cF700, amount=5970000000000000000000 ) => ( True )
            • XchangePair.STATICCALL( )
            • X7DAO.balanceOf( account=0xb8dE6270640092463988B6860d68CA63dC7cF700 ) => ( 14883969923841405728463984 )
            • XchangePair.swap( amount0Out=0, amount1Out=4148846565499085, to=0x6b5422D584943BC8Cd0E10e239d624c6fE90fbB8, data=0x )
              • WETH9.transfer( dst=0x6b5422D584943BC8Cd0E10e239d624c6fE90fbB8, wad=4148846565499085 ) => ( True )
              • X7DAO.balanceOf( account=0xb8dE6270640092463988B6860d68CA63dC7cF700 ) => ( 14883969923841405728463984 )
              • WETH9.balanceOf( 0xb8dE6270640092463988B6860d68CA63dC7cF700 ) => ( 10360174097864920546 )
              • WETH9.balanceOf( 0x6b5422D584943BC8Cd0E10e239d624c6fE90fbB8 ) => ( 4148846565499085 )
              • WETH9.withdraw( wad=4148846565499085 )
                • ETH 0.004148846565499085 XchangeRouterV3.CALL( )
                • ETH 0.004148846565499085 X7DAOLiquidityHubV2.CALL( )
                • XchangePair.STATICCALL( )
                • X7DAO.balanceOf( account=0xb8dE6270640092463988B6860d68CA63dC7cF700 ) => ( 15076999923841405728463984 )
                • XchangePair.swap( amount0Out=0, amount1Out=132378846823508353, to=0x6b5422D584943BC8Cd0E10e239d624c6fE90fbB8, data=0x )
                  • WETH9.transfer( dst=0x6b5422D584943BC8Cd0E10e239d624c6fE90fbB8, wad=132378846823508353 ) => ( True )
                  • X7DAO.balanceOf( account=0xb8dE6270640092463988B6860d68CA63dC7cF700 ) => ( 15076999923841405728463984 )
                  • WETH9.balanceOf( 0xb8dE6270640092463988B6860d68CA63dC7cF700 ) => ( 10227795251041412193 )
                  • WETH9.balanceOf( 0x6b5422D584943BC8Cd0E10e239d624c6fE90fbB8 ) => ( 132378846823508353 )
                  • WETH9.withdraw( wad=132378846823508353 )
                    • ETH 0.132378846823508353 XchangeRouterV3.CALL( )
                    • ETH 0.132378846823508353 0xb66050e3eb239e9955aa897dd981e70621b4455f.CALL( )
                      File 1 of 8: XchangeRouterV3
                      // SPDX-License-Identifier: GPL-3.0
                      pragma solidity =0.8.25;
                      /*
                       /$$   /$$ /$$$$$$$$       /$$$$$$$$ /$$
                      | $$  / $$|_____ $$/      | $$_____/|__/
                      |  $$/ $$/     /$$/       | $$       /$$ /$$$$$$$   /$$$$$$  /$$$$$$$   /$$$$$$$  /$$$$$$
                       \\  $$$$/     /$$/        | $$$$$   | $$| $$__  $$ |____  $$| $$__  $$ /$$_____/ /$$__  $$
                        >$$  $$    /$$/         | $$__/   | $$| $$  \\ $$  /$$$$$$$| $$  \\ $$| $$      | $$$$$$$$
                       /$$/\\  $$  /$$/          | $$      | $$| $$  | $$ /$$__  $$| $$  | $$| $$      | $$_____/
                      | $$  \\ $$ /$$/           | $$      | $$| $$  | $$|  $$$$$$$| $$  | $$|  $$$$$$$|  $$$$$$$
                      |__/  |__/|__/            |__/      |__/|__/  |__/ \\_______/|__/  |__/ \\_______/ \\_______/
                      Contract: Uniswapv2 Fork - XchangeRouterV3
                      In addition to the standard Uniswap V2 Router, this contract includes functionality to remove liquidity in a failsafe manner to permit liquidation of fee liquidity in all cases.
                      XchangeRouterV2 contains a bugfix compared to XchangeRouter related to calculations of amount in.
                      XchangeRouterV3 includes the multicall functionality.
                      The authority to call that function is assigned via the Xchange Factory.
                      This contract will NOT be renounced, however it has no functions which affect the contract. The contract is "owned" solely as a formality.
                      */
                      abstract contract Ownable {
                          address private _owner;
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                          constructor(address owner_) {
                              _transferOwnership(owner_);
                          }
                          modifier onlyOwner() {
                              _checkOwner();
                              _;
                          }
                          function owner() public view virtual returns (address) {
                              return _owner;
                          }
                          function _checkOwner() internal view virtual {
                              require(owner() == msg.sender, "Ownable: caller is not the owner");
                          }
                          function renounceOwnership() public virtual onlyOwner {
                              _transferOwnership(address(0));
                          }
                          function transferOwnership(address newOwner) public virtual onlyOwner {
                              require(newOwner != address(0), "Ownable: new owner is the zero address");
                              _transferOwnership(newOwner);
                          }
                          function _transferOwnership(address newOwner) internal virtual {
                              address oldOwner = _owner;
                              _owner = newOwner;
                              emit OwnershipTransferred(oldOwner, newOwner);
                          }
                      }
                      interface IMulticall {
                          function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
                      }
                      interface IMulticallExtended is IMulticall {
                          function multicall(uint256 deadline, bytes[] calldata data) external payable returns (bytes[] memory results);
                          function multicall(
                              bytes32 previousBlockhash,
                              bytes[] calldata data
                          ) external payable returns (bytes[] memory results);
                      }
                      interface IPeripheryPayments {
                          function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
                          function refundETH() external payable;
                          function sweepToken(address token, uint256 amountMinimum, address recipient) external payable;
                      }
                      interface IPeripheryPaymentsExtended is IPeripheryPayments {
                          function unwrapWETH9(uint256 amountMinimum) external payable;
                          function wrapETH(uint256 value) external payable;
                          function sweepToken(address token, uint256 amountMinimum) external payable;
                          function pull(address token, uint256 value) external payable;
                      }
                      interface IXchangeFactory {
                          function isFailsafeLiquidator(address) external view returns (bool);
                          function getPair(address tokenA, address tokenB) external view returns (address pair);
                          function createPair(address tokenA, address tokenB) external returns (address pair);
                      }
                      interface IXchangePair {
                          function transferFrom(address from, address to, uint value) external returns (bool);
                          function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                          function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                          function mint(address to) external returns (uint liquidity);
                          function burn(address to) external returns (uint amount0, uint amount1);
                          function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                          function mustBurn(address to, uint256 gasAmount) external returns (uint256 amount0, uint256 amount1);
                      }
                      interface IXchangeRouter {
                          function factory() external view returns (address);
                          function WETH() external view returns (address);
                          function addLiquidity(
                              address tokenA,
                              address tokenB,
                              uint amountADesired,
                              uint amountBDesired,
                              uint amountAMin,
                              uint amountBMin,
                              address to,
                              uint deadline
                          ) external returns (uint amountA, uint amountB, uint liquidity);
                          function addLiquidityETH(
                              address token,
                              uint amountTokenDesired,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline
                          ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
                          function removeLiquidity(
                              address tokenA,
                              address tokenB,
                              uint liquidity,
                              uint amountAMin,
                              uint amountBMin,
                              address to,
                              uint deadline
                          ) external returns (uint amountA, uint amountB);
                          function mustRemoveLiquidity(
                              address tokenA,
                              address tokenB,
                              uint liquidity,
                              uint amountAMin,
                              uint amountBMin,
                              address to,
                              uint deadline,
                              uint gasAmount
                          ) external returns (uint amountA, uint amountB);
                          function removeLiquidityETH(
                              address token,
                              uint liquidity,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline
                          ) external returns (uint amountToken, uint amountETH);
                          function removeLiquidityWithPermit(
                              address tokenA,
                              address tokenB,
                              uint liquidity,
                              uint amountAMin,
                              uint amountBMin,
                              address to,
                              uint deadline,
                              bool approveMax,
                              uint8 v,
                              bytes32 r,
                              bytes32 s
                          ) external returns (uint amountA, uint amountB);
                          function removeLiquidityETHWithPermit(
                              address token,
                              uint liquidity,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline,
                              bool approveMax,
                              uint8 v,
                              bytes32 r,
                              bytes32 s
                          ) external returns (uint amountToken, uint amountETH);
                          function swapExactTokensForTokens(
                              uint amountIn,
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external returns (uint[] memory amounts);
                          function swapTokensForExactTokens(
                              uint amountOut,
                              uint amountInMax,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external returns (uint[] memory amounts);
                          function swapExactETHForTokens(
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external payable returns (uint[] memory amounts);
                          function swapTokensForExactETH(
                              uint amountOut,
                              uint amountInMax,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external returns (uint[] memory amounts);
                          function swapExactTokensForETH(
                              uint amountIn,
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external returns (uint[] memory amounts);
                          function swapETHForExactTokens(
                              uint amountOut,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external payable returns (uint[] memory amounts);
                          function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
                          function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
                          function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
                          function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
                          function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
                          function removeLiquidityETHSupportingFeeOnTransferTokens(
                              address token,
                              uint liquidity,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline
                          ) external returns (uint amountETH);
                          function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
                              address token,
                              uint liquidity,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline,
                              bool approveMax,
                              uint8 v,
                              bytes32 r,
                              bytes32 s
                          ) external returns (uint amountETH);
                          function swapExactTokensForTokensSupportingFeeOnTransferTokens(
                              uint amountIn,
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external;
                          function swapExactETHForTokensSupportingFeeOnTransferTokens(
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external payable;
                          function swapExactTokensForETHSupportingFeeOnTransferTokens(
                              uint amountIn,
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external;
                      }
                      interface IERC20 {
                          function balanceOf(address owner) external view returns (uint);
                          function transfer(address to, uint256 value) external returns (bool);
                          function approve(address spender, uint256 value) external returns (bool);
                      }
                      interface IWETH {
                          function deposit() external payable;
                          function transfer(address to, uint value) external returns (bool);
                          function withdraw(uint) external;
                      }
                      interface IWETH9 is IERC20 {
                          function deposit() external payable;
                          function withdraw(uint256) external;
                      }
                      interface IPeripheryImmutableState {
                          function factory() external view returns (address);
                          function WETH9() external view returns (address);
                      }
                      interface IXchangeDiscountAuthority {
                          function fee(address) external view returns (uint256);
                      }
                      abstract contract Multicall is IMulticall {
                          /// @inheritdoc IMulticall
                          function multicall(bytes[] calldata data) public payable override returns (bytes[] memory results) {
                              results = new bytes[](data.length);
                              for (uint256 i = 0; i < data.length; i++) {
                                  (bool success, bytes memory result) = address(this).delegatecall(data[i]);
                                  if (!success) {
                                      if (result.length < 68) revert();
                                      assembly {
                                          result := add(result, 0x04)
                                      }
                                      revert(abi.decode(result, (string)));
                                  }
                                  results[i] = result;
                              }
                          }
                      }
                      abstract contract BlockTimestamp {
                          function _blockTimestamp() internal view virtual returns (uint256) {
                              return block.timestamp;
                          }
                      }
                      abstract contract PeripheryValidation is BlockTimestamp {
                          modifier checkDeadline(uint256 deadline) {
                              require(_blockTimestamp() <= deadline, "Transaction too old");
                              _;
                          }
                      }
                      abstract contract PeripheryValidationExtended is PeripheryValidation {
                          modifier checkPreviousBlockhash(bytes32 previousBlockhash) {
                              require(blockhash(block.number - 1) == previousBlockhash, "Blockhash");
                              _;
                          }
                      }
                      abstract contract MulticallExtended is IMulticallExtended, Multicall, PeripheryValidationExtended {
                          function multicall(
                              uint256 deadline,
                              bytes[] calldata data
                          ) external payable override checkDeadline(deadline) returns (bytes[] memory) {
                              return multicall(data);
                          }
                          function multicall(
                              bytes32 previousBlockhash,
                              bytes[] calldata data
                          ) external payable override checkPreviousBlockhash(previousBlockhash) returns (bytes[] memory) {
                              return multicall(data);
                          }
                      }
                      abstract contract PeripheryImmutableState is IPeripheryImmutableState {
                          address public immutable override factory;
                          address public immutable override WETH9;
                          constructor(address _factory, address _WETH9) {
                              factory = _factory;
                              WETH9 = _WETH9;
                          }
                      }
                      abstract contract PeripheryPayments is IPeripheryPayments, PeripheryImmutableState {
                          receive() external payable {
                              require(msg.sender == WETH9, "Not WETH9");
                          }
                          function unwrapWETH9(uint256 amountMinimum, address recipient) public payable override {
                              uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));
                              require(balanceWETH9 >= amountMinimum, "Insufficient WETH9");
                              if (balanceWETH9 > 0) {
                                  IWETH9(WETH9).withdraw(balanceWETH9);
                                  TransferHelper.safeTransferETH(recipient, balanceWETH9);
                              }
                          }
                          function sweepToken(address token, uint256 amountMinimum, address recipient) public payable override {
                              uint256 balanceToken = IERC20(token).balanceOf(address(this));
                              require(balanceToken >= amountMinimum, "Insufficient token");
                              if (balanceToken > 0) {
                                  TransferHelper.safeTransfer(token, recipient, balanceToken);
                              }
                          }
                          function refundETH() external payable override {
                              if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance);
                          }
                          function pay(address token, address payer, address recipient, uint256 value) internal {
                              if (token == WETH9 && address(this).balance >= value) {
                                  // pay with WETH9
                                  IWETH9(WETH9).deposit{ value: value }(); // wrap only what is needed to pay
                                  IWETH9(WETH9).transfer(recipient, value);
                              } else if (payer == address(this)) {
                                  // pay with tokens already in the contract (for the exact input multihop case)
                                  TransferHelper.safeTransfer(token, recipient, value);
                              } else {
                                  // pull payment
                                  TransferHelper.safeTransferFrom(token, payer, recipient, value);
                              }
                          }
                      }
                      contract XchangeRouterV3 is IXchangeRouter, Ownable, MulticallExtended {
                          address public immutable override factory;
                          address public immutable override WETH;
                          modifier ensure(uint deadline) {
                              require(deadline >= block.timestamp, "Xchange: EXPIRED");
                              _;
                          }
                          constructor(address _factory, address _WETH, address _owner) Ownable(_owner) {
                              factory = _factory;
                              WETH = _WETH;
                          }
                          receive() external payable {
                              require(msg.sender == WETH);
                              // only accept ETH via fallback from the WETH contract
                          }
                          function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
                              return XchangeLibrary.quote(amountA, reserveA, reserveB);
                          }
                          function getAmountOut(
                              uint amountIn,
                              uint reserveIn,
                              uint reserveOut
                          ) public pure virtual override returns (uint amountOut) {
                              return XchangeLibrary.getAmountOut(amountIn, reserveIn, reserveOut, 20);
                          }
                          function getAmountIn(
                              uint amountOut,
                              uint reserveIn,
                              uint reserveOut
                          ) public pure virtual override returns (uint amountIn) {
                              return XchangeLibrary.getAmountIn(amountOut, reserveIn, reserveOut, 20);
                          }
                          function getAmountsOut(
                              uint amountIn,
                              address[] memory path
                          ) public view virtual override returns (uint[] memory amounts) {
                              return XchangeLibrary.getAmountsOut(factory, amountIn, 20, path);
                          }
                          function getAmountsIn(
                              uint amountOut,
                              address[] memory path
                          ) public view virtual override returns (uint[] memory amounts) {
                              return XchangeLibrary.getAmountsIn(factory, amountOut, 20, path);
                          }
                          function addLiquidity(
                              address tokenA,
                              address tokenB,
                              uint amountADesired,
                              uint amountBDesired,
                              uint amountAMin,
                              uint amountBMin,
                              address to,
                              uint deadline
                          ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
                              (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
                              address pair = XchangeLibrary.pairFor(factory, tokenA, tokenB);
                              TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
                              TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
                              liquidity = IXchangePair(pair).mint(to);
                          }
                          function addLiquidityETH(
                              address token,
                              uint amountTokenDesired,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline
                          ) external payable virtual override ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
                              (amountToken, amountETH) = _addLiquidity(
                                  token,
                                  WETH,
                                  amountTokenDesired,
                                  msg.value,
                                  amountTokenMin,
                                  amountETHMin
                              );
                              address pair = XchangeLibrary.pairFor(factory, token, WETH);
                              TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
                              IWETH(WETH).deposit{ value: amountETH }();
                              assert(IWETH(WETH).transfer(pair, amountETH));
                              liquidity = IXchangePair(pair).mint(to);
                              // refund dust eth, if any
                              if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
                          }
                          // **** REMOVE LIQUIDITY ****
                          function removeLiquidity(
                              address tokenA,
                              address tokenB,
                              uint liquidity,
                              uint amountAMin,
                              uint amountBMin,
                              address to,
                              uint deadline
                          ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
                              address pair = XchangeLibrary.pairFor(factory, tokenA, tokenB);
                              IXchangePair(pair).transferFrom(msg.sender, pair, liquidity);
                              // send liquidity to pair
                              (uint amount0, uint amount1) = IXchangePair(pair).burn(to);
                              (address token0, ) = XchangeLibrary.sortTokens(tokenA, tokenB);
                              (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
                              require(amountA >= amountAMin, "Xchange: INSUFFICIENT_A_AMOUNT");
                              require(amountB >= amountBMin, "Xchange: INSUFFICIENT_B_AMOUNT");
                          }
                          function mustRemoveLiquidity(
                              address tokenA,
                              address tokenB,
                              uint liquidity,
                              uint amountAMin,
                              uint amountBMin,
                              address to,
                              uint deadline,
                              uint gasAmount
                          ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
                              require(IXchangeFactory(factory).isFailsafeLiquidator(msg.sender));
                              address pair = XchangeLibrary.pairFor(factory, tokenA, tokenB);
                              // send liquidity to pair
                              IXchangePair(pair).transferFrom(msg.sender, pair, liquidity);
                              // call the modified "mustBurn" function to ensure no token behavior can
                              // prevent this call from succeeding
                              (uint amount0, uint amount1) = IXchangePair(pair).mustBurn(to, gasAmount);
                              (address token0, ) = XchangeLibrary.sortTokens(tokenA, tokenB);
                              (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
                              require(amountA >= amountAMin, "Xchange: INSUFFICIENT_A_AMOUNT");
                              require(amountB >= amountBMin, "Xchange: INSUFFICIENT_B_AMOUNT");
                          }
                          function removeLiquidityETH(
                              address token,
                              uint liquidity,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline
                          ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
                              (amountToken, amountETH) = removeLiquidity(
                                  token,
                                  WETH,
                                  liquidity,
                                  amountTokenMin,
                                  amountETHMin,
                                  address(this),
                                  deadline
                              );
                              TransferHelper.safeTransfer(token, to, amountToken);
                              IWETH(WETH).withdraw(amountETH);
                              TransferHelper.safeTransferETH(to, amountETH);
                          }
                          function removeLiquidityWithPermit(
                              address tokenA,
                              address tokenB,
                              uint liquidity,
                              uint amountAMin,
                              uint amountBMin,
                              address to,
                              uint deadline,
                              bool approveMax,
                              uint8 v,
                              bytes32 r,
                              bytes32 s
                          ) external virtual override returns (uint amountA, uint amountB) {
                              address pair = XchangeLibrary.pairFor(factory, tokenA, tokenB);
                              uint value = approveMax ? type(uint256).max : liquidity;
                              IXchangePair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
                              (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
                          }
                          function removeLiquidityETHWithPermit(
                              address token,
                              uint liquidity,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline,
                              bool approveMax,
                              uint8 v,
                              bytes32 r,
                              bytes32 s
                          ) external virtual override returns (uint amountToken, uint amountETH) {
                              address pair = XchangeLibrary.pairFor(factory, token, WETH);
                              uint value = approveMax ? type(uint256).max : liquidity;
                              IXchangePair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
                              (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
                          }
                          // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
                          function removeLiquidityETHSupportingFeeOnTransferTokens(
                              address token,
                              uint liquidity,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline
                          ) public virtual override ensure(deadline) returns (uint amountETH) {
                              (, amountETH) = removeLiquidity(token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline);
                              TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
                              IWETH(WETH).withdraw(amountETH);
                              TransferHelper.safeTransferETH(to, amountETH);
                          }
                          function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
                              address token,
                              uint liquidity,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline,
                              bool approveMax,
                              uint8 v,
                              bytes32 r,
                              bytes32 s
                          ) external virtual override returns (uint amountETH) {
                              address pair = XchangeLibrary.pairFor(factory, token, WETH);
                              uint value = approveMax ? type(uint256).max : liquidity;
                              IXchangePair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
                              amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
                                  token,
                                  liquidity,
                                  amountTokenMin,
                                  amountETHMin,
                                  to,
                                  deadline
                              );
                          }
                          function swapExactTokensForTokens(
                              uint amountIn,
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external virtual override ensure(deadline) returns (uint[] memory amounts) {
                              amounts = XchangeLibrary.getAmountsOut(factory, amountIn, 20, path);
                              require(amounts[amounts.length - 1] >= amountOutMin, "Xchange: INSUFFICIENT_OUTPUT_AMOUNT");
                              TransferHelper.safeTransferFrom(
                                  path[0],
                                  msg.sender,
                                  XchangeLibrary.pairFor(factory, path[0], path[1]),
                                  amounts[0]
                              );
                              _swap(amounts, path, to);
                          }
                          function swapTokensForExactTokens(
                              uint amountOut,
                              uint amountInMax,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external virtual override ensure(deadline) returns (uint[] memory amounts) {
                              amounts = XchangeLibrary.getAmountsIn(factory, amountOut, 20, path);
                              require(amounts[0] <= amountInMax, "Xchange: EXCESSIVE_INPUT_AMOUNT");
                              TransferHelper.safeTransferFrom(
                                  path[0],
                                  msg.sender,
                                  XchangeLibrary.pairFor(factory, path[0], path[1]),
                                  amounts[0]
                              );
                              _swap(amounts, path, to);
                          }
                          function swapExactETHForTokens(
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external payable virtual override ensure(deadline) returns (uint[] memory amounts) {
                              require(path[0] == WETH, "Xchange: INVALID_PATH");
                              amounts = XchangeLibrary.getAmountsOut(factory, msg.value, 20, path);
                              require(amounts[amounts.length - 1] >= amountOutMin, "Xchange: INSUFFICIENT_OUTPUT_AMOUNT");
                              IWETH(WETH).deposit{ value: amounts[0] }();
                              assert(IWETH(WETH).transfer(XchangeLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
                              _swap(amounts, path, to);
                          }
                          function swapTokensForExactETH(
                              uint amountOut,
                              uint amountInMax,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external virtual override ensure(deadline) returns (uint[] memory amounts) {
                              require(path[path.length - 1] == WETH, "Xchange: INVALID_PATH");
                              amounts = XchangeLibrary.getAmountsIn(factory, amountOut, 20, path);
                              require(amounts[0] <= amountInMax, "Xchange: EXCESSIVE_INPUT_AMOUNT");
                              TransferHelper.safeTransferFrom(
                                  path[0],
                                  msg.sender,
                                  XchangeLibrary.pairFor(factory, path[0], path[1]),
                                  amounts[0]
                              );
                              _swap(amounts, path, address(this));
                              IWETH(WETH).withdraw(amounts[amounts.length - 1]);
                              TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
                          }
                          function swapExactTokensForETH(
                              uint amountIn,
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external virtual override ensure(deadline) returns (uint[] memory amounts) {
                              require(path[path.length - 1] == WETH, "Xchange: INVALID_PATH");
                              amounts = XchangeLibrary.getAmountsOut(factory, amountIn, 20, path);
                              require(amounts[amounts.length - 1] >= amountOutMin, "Xchange: INSUFFICIENT_OUTPUT_AMOUNT");
                              TransferHelper.safeTransferFrom(
                                  path[0],
                                  msg.sender,
                                  XchangeLibrary.pairFor(factory, path[0], path[1]),
                                  amounts[0]
                              );
                              _swap(amounts, path, address(this));
                              IWETH(WETH).withdraw(amounts[amounts.length - 1]);
                              TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
                          }
                          function swapETHForExactTokens(
                              uint amountOut,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external payable virtual override ensure(deadline) returns (uint[] memory amounts) {
                              require(path[0] == WETH, "Xchange: INVALID_PATH");
                              amounts = XchangeLibrary.getAmountsIn(factory, amountOut, 20, path);
                              require(amounts[0] <= msg.value, "Xchange: EXCESSIVE_INPUT_AMOUNT");
                              IWETH(WETH).deposit{ value: amounts[0] }();
                              assert(IWETH(WETH).transfer(XchangeLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
                              _swap(amounts, path, to);
                              // refund dust eth, if any
                              if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
                          }
                          function swapExactTokensForTokensSupportingFeeOnTransferTokens(
                              uint amountIn,
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external virtual override ensure(deadline) {
                              TransferHelper.safeTransferFrom(
                                  path[0],
                                  msg.sender,
                                  XchangeLibrary.pairFor(factory, path[0], path[1]),
                                  amountIn
                              );
                              uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
                              _swapSupportingFeeOnTransferTokens(path, to);
                              require(
                                  IERC20(path[path.length - 1]).balanceOf(to) - balanceBefore >= amountOutMin,
                                  "Xchange: INSUFFICIENT_OUTPUT_AMOUNT"
                              );
                          }
                          function swapExactETHForTokensSupportingFeeOnTransferTokens(
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external payable virtual override ensure(deadline) {
                              require(path[0] == WETH, "Xchange: INVALID_PATH");
                              uint amountIn = msg.value;
                              IWETH(WETH).deposit{ value: amountIn }();
                              assert(IWETH(WETH).transfer(XchangeLibrary.pairFor(factory, path[0], path[1]), amountIn));
                              uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
                              _swapSupportingFeeOnTransferTokens(path, to);
                              require(
                                  IERC20(path[path.length - 1]).balanceOf(to) - balanceBefore >= amountOutMin,
                                  "Xchange: INSUFFICIENT_OUTPUT_AMOUNT"
                              );
                          }
                          function swapExactTokensForETHSupportingFeeOnTransferTokens(
                              uint amountIn,
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external virtual override ensure(deadline) {
                              require(path[path.length - 1] == WETH, "Xchange: INVALID_PATH");
                              TransferHelper.safeTransferFrom(
                                  path[0],
                                  msg.sender,
                                  XchangeLibrary.pairFor(factory, path[0], path[1]),
                                  amountIn
                              );
                              _swapSupportingFeeOnTransferTokens(path, address(this));
                              uint amountOut = IERC20(WETH).balanceOf(address(this));
                              require(amountOut >= amountOutMin, "Xchange: INSUFFICIENT_OUTPUT_AMOUNT");
                              IWETH(WETH).withdraw(amountOut);
                              TransferHelper.safeTransferETH(to, amountOut);
                          }
                          // **** ADD LIQUIDITY ****
                          function _addLiquidity(
                              address tokenA,
                              address tokenB,
                              uint amountADesired,
                              uint amountBDesired,
                              uint amountAMin,
                              uint amountBMin
                          ) internal virtual returns (uint amountA, uint amountB) {
                              // create the pair if it doesn't exist yet
                              if (IXchangeFactory(factory).getPair(tokenA, tokenB) == address(0)) {
                                  IXchangeFactory(factory).createPair(tokenA, tokenB);
                              }
                              (uint reserveA, uint reserveB) = XchangeLibrary.getReserves(factory, tokenA, tokenB);
                              if (reserveA == 0 && reserveB == 0) {
                                  (amountA, amountB) = (amountADesired, amountBDesired);
                              } else {
                                  uint amountBOptimal = XchangeLibrary.quote(amountADesired, reserveA, reserveB);
                                  if (amountBOptimal <= amountBDesired) {
                                      require(amountBOptimal >= amountBMin, "Xchange: INSUFFICIENT_B_AMOUNT");
                                      (amountA, amountB) = (amountADesired, amountBOptimal);
                                  } else {
                                      uint amountAOptimal = XchangeLibrary.quote(amountBDesired, reserveB, reserveA);
                                      assert(amountAOptimal <= amountADesired);
                                      require(amountAOptimal >= amountAMin, "Xchange: INSUFFICIENT_A_AMOUNT");
                                      (amountA, amountB) = (amountAOptimal, amountBDesired);
                                  }
                              }
                          }
                          // **** SWAP ****
                          // requires the initial amount to have already been sent to the first pair
                          function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
                              for (uint i; i < path.length - 1; i++) {
                                  (address input, address output) = (path[i], path[i + 1]);
                                  (address token0, ) = XchangeLibrary.sortTokens(input, output);
                                  uint amountOut = amounts[i + 1];
                                  (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
                                  address to = i < path.length - 2 ? XchangeLibrary.pairFor(factory, output, path[i + 2]) : _to;
                                  IXchangePair(XchangeLibrary.pairFor(factory, input, output)).swap(amount0Out, amount1Out, to, new bytes(0));
                              }
                          }
                          // **** SWAP (supporting fee-on-transfer tokens) ****
                          // requires the initial amount to have already been sent to the first pair
                          function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
                              for (uint i; i < path.length - 1; i++) {
                                  (address input, address output) = (path[i], path[i + 1]);
                                  (address token0, ) = XchangeLibrary.sortTokens(input, output);
                                  IXchangePair pair = IXchangePair(XchangeLibrary.pairFor(factory, input, output));
                                  uint amountInput;
                                  uint amountOutput;
                                  {
                                      // scope to avoid stack too deep errors
                                      (uint reserve0, uint reserve1, ) = pair.getReserves();
                                      (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
                                      amountInput = IERC20(input).balanceOf(address(pair)) - reserveInput;
                                      amountOutput = XchangeLibrary.getAmountOut(amountInput, reserveInput, reserveOutput, 20);
                                  }
                                  (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
                                  address to = i < path.length - 2 ? XchangeLibrary.pairFor(factory, output, path[i + 2]) : _to;
                                  pair.swap(amount0Out, amount1Out, to, new bytes(0));
                              }
                          }
                      }
                      library XchangeLibrary {
                          // returns sorted token addresses, used to handle return values from pairs sorted in this order
                          function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
                              require(tokenA != tokenB, "XchangeLibrary: IDENTICAL_ADDRESSES");
                              (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                              require(token0 != address(0), "XchangeLibrary: ZERO_ADDRESS");
                          }
                          // calculates the CREATE2 address for a pair without making any external calls
                          function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
                              (address token0, address token1) = sortTokens(tokenA, tokenB);
                              pair = address(
                                  uint160(
                                      uint(
                                          keccak256(
                                              abi.encodePacked(
                                                  hex"ff",
                                                  factory,
                                                  keccak256(abi.encodePacked(token0, token1)),
                                                  hex"d75846df8bac2f946ea9ee78caa53b6812e7514197698275b8322d75e1543193" // init code hash
                                              )
                                          )
                                      )
                                  )
                              );
                          }
                          // fetches and sorts the reserves for a pair
                          function getReserves(
                              address factory,
                              address tokenA,
                              address tokenB
                          ) internal view returns (uint reserveA, uint reserveB) {
                              (address token0, ) = sortTokens(tokenA, tokenB);
                              (uint reserve0, uint reserve1, ) = IXchangePair(pairFor(factory, tokenA, tokenB)).getReserves();
                              (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
                          }
                          // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
                          function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
                              require(amountA > 0, "XchangeLibrary: INSUFFICIENT_AMOUNT");
                              require(reserveA > 0 && reserveB > 0, "XchangeLibrary: INSUFFICIENT_LIQUIDITY");
                              amountB = (amountA * reserveB) / reserveA;
                          }
                          // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
                          function getAmountOut(
                              uint amountIn,
                              uint reserveIn,
                              uint reserveOut,
                              uint feeAmount
                          ) internal pure returns (uint amountOut) {
                              require(amountIn > 0, "XchangeLibrary: INSUFFICIENT_INPUT_AMOUNT");
                              require(reserveIn > 0 && reserveOut > 0, "XchangeLibrary: INSUFFICIENT_LIQUIDITY");
                              require(feeAmount <= 20, "XchangeLibrary: EXCESSIVE_FEE");
                              uint amountInWithFee = amountIn * (10000 - feeAmount);
                              uint numerator = amountInWithFee * reserveOut;
                              uint denominator = (reserveIn * 10000) + amountInWithFee;
                              amountOut = numerator / denominator;
                          }
                          // given an output amount of an asset and pair reserves, returns a required input amount of the other asset
                          function getAmountIn(
                              uint amountOut,
                              uint reserveIn,
                              uint reserveOut,
                              uint feeAmount
                          ) internal pure returns (uint amountIn) {
                              require(amountOut > 0, "XchangeLibrary: INSUFFICIENT_OUTPUT_AMOUNT");
                              require(reserveIn > 0 && reserveOut > 0, "XchangeLibrary: INSUFFICIENT_LIQUIDITY");
                              require(feeAmount <= 20, "XchangeLibrary: EXCESSIVE_FEE");
                              uint numerator = reserveIn * amountOut * 10000;
                              uint denominator = (reserveOut - amountOut) * (10000 - feeAmount);
                              amountIn = (numerator / denominator) + 1;
                          }
                          // performs chained getAmountOut calculations on any number of pairs
                          function getAmountsOut(
                              address factory,
                              uint amountIn,
                              uint feeAmount,
                              address[] memory path
                          ) internal view returns (uint[] memory amounts) {
                              require(path.length >= 2, "XchangeLibrary: INVALID_PATH");
                              amounts = new uint[](path.length);
                              amounts[0] = amountIn;
                              for (uint i; i < path.length - 1; i++) {
                                  (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
                                  amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, feeAmount);
                              }
                          }
                          // performs chained getAmountIn calculations on any number of pairs
                          function getAmountsIn(
                              address factory,
                              uint amountOut,
                              uint feeAmount,
                              address[] memory path
                          ) internal view returns (uint[] memory amounts) {
                              require(path.length >= 2, "XchangeLibrary: INVALID_PATH");
                              amounts = new uint[](path.length);
                              amounts[amounts.length - 1] = amountOut;
                              for (uint i = path.length - 1; i > 0; i--) {
                                  (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
                                  amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, feeAmount);
                              }
                          }
                      }
                      // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
                      library TransferHelper {
                          function safeTransfer(address token, address to, uint 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))), "TransferHelper: TRANSFER_FAILED");
                          }
                          function safeTransferFrom(address token, address from, address to, uint value) internal {
                              // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
                              (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
                              require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper: TRANSFER_FROM_FAILED");
                          }
                          function safeApprove(address token, address to, uint256 value) internal {
                              (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
                              require(success && (data.length == 0 || abi.decode(data, (bool))), "SA");
                          }
                          function safeTransferETH(address to, uint value) internal {
                              (bool success, ) = to.call{ value: value }(new bytes(0));
                              require(success, "TransferHelper: ETH_TRANSFER_FAILED");
                          }
                      }
                      

                      File 2 of 8: X7DAOLiquidityHubV2
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.15;
                      /*
                       /$$   /$$ /$$$$$$$$       /$$$$$$$$ /$$
                      | $$  / $$|_____ $$/      | $$_____/|__/
                      |  $$/ $$/     /$$/       | $$       /$$ /$$$$$$$   /$$$$$$  /$$$$$$$   /$$$$$$$  /$$$$$$
                       \\  $$$$/     /$$/        | $$$$$   | $$| $$__  $$ |____  $$| $$__  $$ /$$_____/ /$$__  $$
                        >$$  $$    /$$/         | $$__/   | $$| $$  \\ $$  /$$$$$$$| $$  \\ $$| $$      | $$$$$$$$
                       /$$/\\  $$  /$$/          | $$      | $$| $$  | $$ /$$__  $$| $$  | $$| $$      | $$_____/
                      | $$  \\ $$ /$$/           | $$      | $$| $$  | $$|  $$$$$$$| $$  | $$|  $$$$$$$|  $$$$$$$
                      |__/  |__/|__/            |__/      |__/|__/  |__/ \\_______/|__/  |__/ \\_______/ \\_______/
                      Contract: Smart Contract for managing X7DAO fee tokens V2
                      Fixes:
                          1. Ability to manage the release of tokens built up by the contract to not affect user trading with large slippage
                      This contract will NOT be renounced.
                      The following are the only functions that can be called on the contract that affect the contract:
                          function setShares(uint256 distributeShare_, uint256 liquidityShare_, uint256 auxiliaryShare_, uint256 treasuryShare_) external onlyOwner {
                              require(distributeShare + liquidityShare + auxiliaryShare + treasuryShare == 1000);
                              require(distributeShare_ >= minShare && distributeShare_ <= maxShare);
                              require(liquidityShare_ >= minShare && liquidityShare_ <= maxShare);
                              require(auxiliaryShare_ >= minShare && auxiliaryShare_ <= maxShare);
                              require(treasuryShare_ >= minShare && treasuryShare_ <= maxShare);
                              distributeShare = distributeShare_;
                              liquidityShare = liquidityShare_;
                              auxiliaryShare = auxiliaryShare_;
                              treasuryShare = treasuryShare_;
                              emit SharesSet(distributeShare_, liquidityShare_, auxiliaryShare_, treasuryShare_);
                          }
                          function setRouter(address router_) external onlyOwner {
                              require(router_ != address(router));
                              router = IUniswapV2Router(router_);
                              emit RouterSet(router_);
                          }
                          function setOffRampPair(address offRampPairAddress) external onlyOwner {
                              require(offRampPair != offRampPairAddress);
                              offRampPair = offRampPairAddress;
                              emit OffRampPairSet(offRampPairAddress);
                          }
                          function setBalanceThreshold(uint256 threshold) external onlyOwner {
                              require(!balanceThresholdFrozen);
                              balanceThreshold = threshold;
                              emit BalanceThresholdSet(threshold);
                          }
                          function setMaxSlippage(uint256 newMaxSlippageBips) external onlyOwner {
                              require(newMaxSlippageBips > 0 && newMaxSlippageBips <= 1000, "Invalid slippage value"); // Max 10% slippage
                              uint256 oldSlippage = maxSlippageBips;
                              maxSlippageBips = newMaxSlippageBips;
                              emit MaxSlippageUpdated(oldSlippage, newMaxSlippageBips);
                          }
                          function setLiquidityRatioTarget(uint256 liquidityRatioTarget_) external onlyOwner {
                              require(liquidityRatioTarget_ != liquidityRatioTarget);
                              require(liquidityRatioTarget_ >= minLiquidityRatioTarget && liquidityRatioTarget <= maxLiquidityRatioTarget);
                              liquidityRatioTarget = liquidityRatioTarget_;
                              emit LiquidityRatioTargetSet(liquidityRatioTarget_);
                          }
                          function setLiquidityTokenReceiver(address liquidityTokenReceiver_) external onlyOwner {
                              require(
                                  liquidityTokenReceiver_ != address(0)
                                  && liquidityTokenReceiver_ != address(0x000000000000000000000000000000000000dEaD)
                                  && liquidityTokenReceiver != liquidityTokenReceiver_
                              );
                              address oldLiquidityTokenReceiver = liquidityTokenReceiver;
                              liquidityTokenReceiver = liquidityTokenReceiver_;
                              emit LiquidityTokenReceiverSet(oldLiquidityTokenReceiver, liquidityTokenReceiver_);
                          }
                          function setDistributionTarget(address target) external onlyOwner {
                              require(
                                  target != address(0)
                                  && target != address(0x000000000000000000000000000000000000dEaD)
                                  && distributeTarget != payable(target)
                              );
                              require(!distributeTargetFrozen);
                              address oldTarget = address(distributeTarget);
                              distributeTarget = payable(target);
                              emit DistributeTargetSet(oldTarget, distributeTarget);
                          }
                          function setAuxiliaryTarget(address target) external onlyOwner {
                              require(
                                  target != address(0) &&
                                  target != address(0x000000000000000000000000000000000000dEaD)
                                  && auxiliaryTarget != payable(target)
                              );
                              require(!auxiliaryTargetFrozen);
                              address oldTarget = address(auxiliaryTarget);
                              auxiliaryTarget = payable(target);
                              emit AuxiliaryTargetSet(oldTarget, target);
                          }
                          function setTreasuryTarget(address target) external onlyOwner {
                              require(
                                  target != address(0)
                                  && target != address(0x000000000000000000000000000000000000dEaD)
                                  && treasuryTarget != payable(target)
                              );
                              require(!treasuryTargetFrozen);
                              address oldTarget = address(treasuryTarget);
                              treasuryTarget = payable(target);
                              emit TreasuryTargetSet(oldTarget, target);
                          }
                          function freezeTreasuryTarget() external onlyOwner {
                              require(!treasuryTargetFrozen);
                              treasuryTargetFrozen = true;
                              emit TreasuryTargetFrozen();
                          }
                          function freezeDistributeTarget() external onlyOwner {
                              require(!distributeTargetFrozen);
                              distributeTargetFrozen = true;
                              emit DistributeTargetFrozen();
                          }
                          function freezeAuxiliaryTarget() external onlyOwner {
                              require(!auxiliaryTargetFrozen);
                              auxiliaryTargetFrozen = true;
                              emit AuxiliaryTargetFrozen();
                          }
                          function freezeBalanceThreshold() external onlyOwner {
                              require(!balanceThresholdFrozen);
                              balanceThresholdFrozen = true;
                              emit BalanceThresholdFrozen();
                          }
                      These functions will be passed to DAO governance once the ecosystem stabilizes.
                      */
                      abstract contract Ownable {
                          address private _owner;
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                          constructor(address owner_) {
                              _transferOwnership(owner_);
                          }
                          modifier onlyOwner() {
                              _checkOwner();
                              _;
                          }
                          function owner() public view virtual returns (address) {
                              return _owner;
                          }
                          function _checkOwner() internal view virtual {
                              require(owner() == msg.sender, "Ownable: caller is not the owner");
                          }
                          function renounceOwnership() public virtual onlyOwner {
                              _transferOwnership(address(0));
                          }
                          function transferOwnership(address newOwner) public virtual onlyOwner {
                              require(newOwner != address(0), "Ownable: new owner is the zero address");
                              _transferOwnership(newOwner);
                          }
                          function _transferOwnership(address newOwner) internal virtual {
                              address oldOwner = _owner;
                              _owner = newOwner;
                              emit OwnershipTransferred(oldOwner, newOwner);
                          }
                      }
                      interface IERC20 {
                          function circulatingSupply() external view returns (uint256);
                          function balanceOf(address account) external view returns (uint256);
                          function transfer(address to, uint256 amount) external returns (bool);
                          function approve(address spender, uint256 amount) external returns (bool);
                      }
                      interface IUniswapV2Router {
                          function WETH() external returns (address);
                          function addLiquidityETH(
                              address token,
                              uint amountTokenDesired,
                              uint amountTokenMin,
                              uint amountETHMin,
                              address to,
                              uint deadline
                          ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
                          function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
                          function swapExactETHForTokensSupportingFeeOnTransferTokens(
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external payable;
                          function swapExactTokensForETHSupportingFeeOnTransferTokens(
                              uint amountIn,
                              uint amountOutMin,
                              address[] calldata path,
                              address to,
                              uint deadline
                          ) external;
                      }
                      interface IUniswapV2Pair {
                          function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                      }
                      interface ILiquidityHub {
                          function processFees(address) external;
                      }
                      interface IX7EcosystemSplitter {
                          function takeBalance() external;
                      }
                      interface IWETH {
                          function withdraw(uint) external;
                      }
                      contract X7DAOLiquidityHubV2 is Ownable, ILiquidityHub {
                          IUniswapV2Router public router;
                          address public offRampPair;
                          IERC20 public x7dao;
                          address public liquidityTokenReceiver;
                          uint256 public minLiquidityRatioTarget = 5;
                          uint256 public maxLiquidityRatioTarget = 99;
                          uint256 public maxSlippageBips = 200; // 2% default slippage
                          uint256 public liquidityRatioTarget = 15;
                          uint256 public minShare = 150;
                          uint256 public maxShare = 400;
                          uint256 public distributeShare = 300;
                          uint256 public liquidityShare = 200;
                          uint256 public auxiliaryShare = 250;
                          uint256 public treasuryShare = 250;
                          uint256 public balanceThreshold = 1 ether;
                          uint256 public distributeBalance;
                          uint256 public auxiliaryBalance;
                          uint256 public treasuryBalance;
                          uint256 public liquidityBalance;
                          uint256 public x7daoLiquidityBalance;
                          address payable public distributeTarget;
                          address payable public auxiliaryTarget;
                          address payable public treasuryTarget;
                          bool public distributeTargetFrozen;
                          bool public auxiliaryTargetFrozen;
                          bool public treasuryTargetFrozen;
                          bool public balanceThresholdFrozen;
                          bool public slippageManagementEnabled = true;
                          event SharesSet(uint256 distributeShare, uint256 liquidityShare, uint256 auxiliaryShare, uint256 treasuryShare);
                          event OffRampPairSet(address indexed offRampPair);
                          event DistributeTargetSet(address indexed oldTarget, address indexed newTarget);
                          event AuxiliaryTargetSet(address indexed oldTarget, address indexed newTarget);
                          event TreasuryTargetSet(address indexed oldTarget, address indexed newTarget);
                          event MaxSlippageSet(uint256 oldSlippage, uint256 newSlippage);
                          event SlippageManagementEnabledSet(bool enabled);
                          event LiquidityRatioTargetSet(uint256 liquidityRatioTarget);
                          event LiquidityTokenReceiverSet(address indexed oldReciever, address indexed newReceiver);
                          event BalanceThresholdSet(uint256 threshold);
                          event RouterSet(address router);
                          event TreasuryTargetFrozen();
                          event AuxiliaryTargetFrozen();
                          event DistributeTargetFrozen();
                          event BalanceThresholdFrozen();
                          constructor(address x7dao_, address router_, address _owner) Ownable(_owner) {
                              router = IUniswapV2Router(router_);
                              x7dao = IERC20(x7dao_);
                              emit RouterSet(router_);
                          }
                          receive() external payable {}
                          function setShares(
                              uint256 distributeShare_,
                              uint256 liquidityShare_,
                              uint256 auxiliaryShare_,
                              uint256 treasuryShare_
                          ) external onlyOwner {
                              require(distributeShare + liquidityShare + auxiliaryShare + treasuryShare == 1000);
                              require(distributeShare_ >= minShare && distributeShare_ <= maxShare);
                              require(liquidityShare_ >= minShare && liquidityShare_ <= maxShare);
                              require(auxiliaryShare_ >= minShare && auxiliaryShare_ <= maxShare);
                              require(treasuryShare_ >= minShare && treasuryShare_ <= maxShare);
                              distributeShare = distributeShare_;
                              liquidityShare = liquidityShare_;
                              auxiliaryShare = auxiliaryShare_;
                              treasuryShare = treasuryShare_;
                              emit SharesSet(distributeShare_, liquidityShare_, auxiliaryShare_, treasuryShare_);
                          }
                          function setRouter(address router_) external onlyOwner {
                              require(router_ != address(router));
                              router = IUniswapV2Router(router_);
                              emit RouterSet(router_);
                          }
                          function setOffRampPair(address offRampPairAddress) external onlyOwner {
                              require(offRampPair != offRampPairAddress);
                              offRampPair = offRampPairAddress;
                              emit OffRampPairSet(offRampPairAddress);
                          }
                          function setBalanceThreshold(uint256 threshold) external onlyOwner {
                              require(!balanceThresholdFrozen);
                              balanceThreshold = threshold;
                              emit BalanceThresholdSet(threshold);
                          }
                          function setMaxSlippage(uint256 newMaxSlippageBips) external onlyOwner {
                              require(newMaxSlippageBips > 0 && newMaxSlippageBips <= 1000, "Invalid slippage value"); // Max 10% slippage
                              uint256 oldSlippage = maxSlippageBips;
                              maxSlippageBips = newMaxSlippageBips;
                              emit MaxSlippageSet(oldSlippage, newMaxSlippageBips);
                          }
                          function setSlippageManagementEnabled(bool enabled) external onlyOwner {
                              require(slippageManagementEnabled != enabled);
                              slippageManagementEnabled = enabled;
                              emit SlippageManagementEnabledSet(enabled);
                          }
                          function setLiquidityRatioTarget(uint256 liquidityRatioTarget_) external onlyOwner {
                              require(liquidityRatioTarget_ != liquidityRatioTarget);
                              require(liquidityRatioTarget_ >= minLiquidityRatioTarget && liquidityRatioTarget <= maxLiquidityRatioTarget);
                              liquidityRatioTarget = liquidityRatioTarget_;
                              emit LiquidityRatioTargetSet(liquidityRatioTarget_);
                          }
                          function setLiquidityTokenReceiver(address liquidityTokenReceiver_) external onlyOwner {
                              require(
                                  liquidityTokenReceiver_ != address(0) &&
                                      liquidityTokenReceiver_ != address(0x000000000000000000000000000000000000dEaD) &&
                                      liquidityTokenReceiver != liquidityTokenReceiver_
                              );
                              address oldLiquidityTokenReceiver = liquidityTokenReceiver;
                              liquidityTokenReceiver = liquidityTokenReceiver_;
                              emit LiquidityTokenReceiverSet(oldLiquidityTokenReceiver, liquidityTokenReceiver_);
                          }
                          function setDistributionTarget(address target) external onlyOwner {
                              require(
                                  target != address(0) &&
                                      target != address(0x000000000000000000000000000000000000dEaD) &&
                                      distributeTarget != payable(target)
                              );
                              require(!distributeTargetFrozen);
                              address oldTarget = address(distributeTarget);
                              distributeTarget = payable(target);
                              emit DistributeTargetSet(oldTarget, distributeTarget);
                          }
                          function setAuxiliaryTarget(address target) external onlyOwner {
                              require(
                                  target != address(0) &&
                                      target != address(0x000000000000000000000000000000000000dEaD) &&
                                      auxiliaryTarget != payable(target)
                              );
                              require(!auxiliaryTargetFrozen);
                              address oldTarget = address(auxiliaryTarget);
                              auxiliaryTarget = payable(target);
                              emit AuxiliaryTargetSet(oldTarget, target);
                          }
                          function setTreasuryTarget(address target) external onlyOwner {
                              require(
                                  target != address(0) &&
                                      target != address(0x000000000000000000000000000000000000dEaD) &&
                                      treasuryTarget != payable(target)
                              );
                              require(!treasuryTargetFrozen);
                              address oldTarget = address(treasuryTarget);
                              treasuryTarget = payable(target);
                              emit TreasuryTargetSet(oldTarget, target);
                          }
                          function freezeTreasuryTarget() external onlyOwner {
                              require(!treasuryTargetFrozen);
                              treasuryTargetFrozen = true;
                              emit TreasuryTargetFrozen();
                          }
                          function freezeDistributeTarget() external onlyOwner {
                              require(!distributeTargetFrozen);
                              distributeTargetFrozen = true;
                              emit DistributeTargetFrozen();
                          }
                          function freezeAuxiliaryTarget() external onlyOwner {
                              require(!auxiliaryTargetFrozen);
                              auxiliaryTargetFrozen = true;
                              emit AuxiliaryTargetFrozen();
                          }
                          function freezeBalanceThreshold() external onlyOwner {
                              require(!balanceThresholdFrozen);
                              balanceThresholdFrozen = true;
                              emit BalanceThresholdFrozen();
                          }
                          function processFees(address tokenAddress) external {
                              require(tokenAddress != address(0), "Invalid token address");
                              require(IERC20(tokenAddress).balanceOf(address(this)) > 0, "No tokens to process");
                              uint256 startingETHBalance = address(this).balance;
                              uint256 tokensToSwap = IERC20(tokenAddress).balanceOf(address(this));
                              if (tokenAddress == address(x7dao)) {
                                  tokensToSwap -= x7daoLiquidityBalance;
                              }
                              if (tokensToSwap > 0) {
                                  uint256 actualTokensToSwap = tokensToSwap;
                                  if (slippageManagementEnabled) {
                                      (uint112 reserve0, uint112 reserve1, ) = IUniswapV2Pair(offRampPair).getReserves();
                                      uint112 tokenReserve = address(x7dao) < router.WETH() ? reserve0 : reserve1;
                                      uint256 maxTokensForTargetSlippage = calculateMaxTokensForSlippage(tokenReserve);
                                      actualTokensToSwap = tokensToSwap < maxTokensForTargetSlippage
                                          ? tokensToSwap
                                          : maxTokensForTargetSlippage;
                                  }
                                  swapTokensForEth(tokenAddress, actualTokensToSwap);
                              }
                              // Rest of the function remains the same
                              uint256 ETHForDistribution = address(this).balance - startingETHBalance;
                              distributeBalance += (ETHForDistribution * distributeShare) / 1000;
                              auxiliaryBalance += (ETHForDistribution * auxiliaryShare) / 1000;
                              treasuryBalance += (ETHForDistribution * treasuryShare) / 1000;
                              liquidityBalance = address(this).balance - distributeBalance - auxiliaryBalance - treasuryBalance;
                              if (distributeBalance >= balanceThreshold) {
                                  sendDistributeBalance();
                              }
                              if (auxiliaryBalance >= balanceThreshold) {
                                  sendAuxiliaryBalance();
                              }
                              if (treasuryBalance >= balanceThreshold) {
                                  sendTreasuryBalance();
                              }
                              if (liquidityBalance >= balanceThreshold) {
                                  buyBackAndAddLiquidity();
                              }
                          }
                          function sendDistributeBalance() public {
                              if (distributeTarget == address(0)) {
                                  return;
                              }
                              IX7EcosystemSplitter(distributeTarget).takeBalance();
                              uint256 ethToSend = distributeBalance;
                              distributeBalance = 0;
                              (bool success, ) = distributeTarget.call{ value: ethToSend }("");
                              if (!success) {
                                  distributeBalance = ethToSend;
                              }
                          }
                          function sendTreasuryBalance() public {
                              if (treasuryTarget == address(0)) {
                                  return;
                              }
                              uint256 ethToSend = treasuryBalance;
                              treasuryBalance = 0;
                              (bool success, ) = treasuryTarget.call{ value: ethToSend }("");
                              if (!success) {
                                  treasuryBalance = ethToSend;
                              }
                          }
                          function sendAuxiliaryBalance() internal {
                              if (auxiliaryTarget == address(0)) {
                                  return;
                              }
                              uint256 ethToSend = auxiliaryBalance;
                              auxiliaryBalance = 0;
                              (bool success, ) = auxiliaryTarget.call{ value: ethToSend }("");
                              if (!success) {
                                  auxiliaryBalance = ethToSend;
                              }
                          }
                          function buyBackAndAddLiquidity() internal {
                              uint256 currentX7DAOBalance = x7dao.balanceOf(address(this));
                              uint256 circulatingSupply = x7dao.circulatingSupply();
                              uint256 pairX7DAOBalance = x7dao.balanceOf(offRampPair);
                              uint256 targetX7DAOLiquidity = (circulatingSupply * liquidityRatioTarget) / 100;
                              if (pairX7DAOBalance >= targetX7DAOLiquidity) {
                                  swapEthForTokens(liquidityBalance);
                              } else {
                                  uint256 x7daoNeeded = targetX7DAOLiquidity - pairX7DAOBalance;
                                  if (currentX7DAOBalance >= x7daoNeeded) {
                                      addLiquidityETH(x7daoNeeded, liquidityBalance);
                                  } else {
                                      uint256 x7daoToBuy = x7daoNeeded - currentX7DAOBalance;
                                      uint256 ethForX7DAO = estimateETHForTokens(x7daoToBuy);
                                      if (ethForX7DAO > liquidityBalance) {
                                          ethForX7DAO = liquidityBalance;
                                      }
                                      swapEthForTokens(ethForX7DAO);
                                      uint256 newX7DAOBalance = x7dao.balanceOf(address(this));
                                      uint256 ethLeft = liquidityBalance - ethForX7DAO;
                                      addLiquidityETH(newX7DAOBalance, ethLeft);
                                  }
                              }
                              liquidityBalance = 0;
                              x7daoLiquidityBalance = x7dao.balanceOf(address(this));
                          }
                          function addLiquidityETH(uint256 tokenAmount, uint256 ethAmount) internal {
                              x7dao.approve(address(router), tokenAmount);
                              router.addLiquidityETH{ value: ethAmount }(
                                  address(x7dao),
                                  tokenAmount,
                                  0,
                                  0,
                                  liquidityTokenReceiver,
                                  block.timestamp
                              );
                          }
                          function estimateETHForTokens(uint256 tokenAmount) internal returns (uint256) {
                              address[] memory path = new address[](2);
                              path[0] = router.WETH();
                              path[1] = address(x7dao);
                              uint256[] memory amounts = router.getAmountsIn(tokenAmount, path);
                              return amounts[0];
                          }
                          function swapTokensForEth(address tokenAddress, uint256 tokenAmount) internal {
                              address[] memory path = new address[](2);
                              path[0] = tokenAddress;
                              path[1] = router.WETH();
                              IERC20(tokenAddress).approve(address(router), tokenAmount);
                              router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, address(this), block.timestamp);
                          }
                          function swapEthForTokens(uint256 ethAmount) internal {
                              address[] memory path = new address[](2);
                              path[0] = router.WETH();
                              path[1] = address(x7dao);
                              router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: ethAmount }(
                                  0,
                                  path,
                                  address(this),
                                  block.timestamp
                              );
                          }
                          function calculateMaxTokensForSlippage(uint112 tokenReserve) internal view returns (uint256) {
                              uint256 slippagePercentage = (maxSlippageBips * 1e14) / 10000;
                              uint256 maxTokens = (uint256(tokenReserve) * slippagePercentage) / (1e18 + slippagePercentage);
                              return maxTokens;
                          }
                          function rescueWETH() external {
                              address wethAddress = router.WETH();
                              IWETH(wethAddress).withdraw(IERC20(wethAddress).balanceOf(address(this)));
                          }
                      }
                      

                      File 3 of 8: X7DAO
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.15;
                      
                      /*
                      
                       /$$   /$$ /$$$$$$$$       /$$$$$$$$ /$$
                      | $$  / $$|_____ $$/      | $$_____/|__/
                      |  $$/ $$/     /$$/       | $$       /$$ /$$$$$$$   /$$$$$$  /$$$$$$$   /$$$$$$$  /$$$$$$
                       \  $$$$/     /$$/        | $$$$$   | $$| $$__  $$ |____  $$| $$__  $$ /$$_____/ /$$__  $$
                        >$$  $$    /$$/         | $$__/   | $$| $$  \ $$  /$$$$$$$| $$  \ $$| $$      | $$$$$$$$
                       /$$/\  $$  /$$/          | $$      | $$| $$  | $$ /$$__  $$| $$  | $$| $$      | $$_____/
                      | $$  \ $$ /$$/           | $$      | $$| $$  | $$|  $$$$$$$| $$  | $$|  $$$$$$$|  $$$$$$$
                      |__/  |__/|__/            |__/      |__/|__/  |__/ \_______/|__/  |__/ \_______/ \_______/
                      
                      Contract: ERC-20 Token X7DAO
                      
                      This contract will NOT be renounced.
                      
                      The following are the only functions that can be called on the contract that affect the contract:
                      
                          function setLiquidityHub(address liquidityHub_) external onlyOwner {
                              require(!liquidityHubFrozen);
                              liquidityHub = ILiquidityHub(liquidityHub_);
                          }
                      
                          function setDiscountAuthority(address discountAuthority_) external onlyOwner {
                              require(!discountAuthorityFrozen);
                              discountAuthority = IDiscountAuthority(discountAuthority_);
                          }
                      
                          function setFeeNumerator(uint256 feeNumerator_) external onlyOwner {
                              require(feeNumerator_ <= maxFeeNumerator);
                              feeNumerator = feeNumerator_;
                          }
                      
                          function setAMM(address ammAddress, bool isAMM) external onlyOwner {
                              ammPair[ammAddress] = isAMM;
                          }
                      
                          function setOffRampPair(address ammAddress) external onlyOwner {
                              offRampPair = ammAddress;
                          }
                      
                          function freezeLiquidityHub() external onlyOwner {
                              require(!liquidityHubFrozen);
                              liquidityHubFrozen = true;
                          }
                      
                          function freezeDiscountAuthority() external onlyOwner {
                              require(!discountAuthorityFrozen);
                              discountAuthorityFrozen = true;
                          }
                      
                      These functions will be passed to DAO governance once the ecosystem stabilizes.
                      
                      */
                      
                      abstract contract Ownable {
                          address private _owner;
                      
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                      
                          constructor(address owner_) {
                              _transferOwnership(owner_);
                          }
                      
                          modifier onlyOwner() {
                              _checkOwner();
                              _;
                          }
                      
                          function owner() public view virtual returns (address) {
                              return _owner;
                          }
                      
                          function _checkOwner() internal view virtual {
                              require(owner() == msg.sender, "Ownable: caller is not the owner");
                          }
                      
                          function renounceOwnership() public virtual onlyOwner {
                              _transferOwnership(address(0));
                          }
                      
                          function transferOwnership(address newOwner) public virtual onlyOwner {
                              require(newOwner != address(0), "Ownable: new owner is the zero address");
                              _transferOwnership(newOwner);
                          }
                      
                          function _transferOwnership(address newOwner) internal virtual {
                              address oldOwner = _owner;
                              _owner = newOwner;
                              emit OwnershipTransferred(oldOwner, newOwner);
                          }
                      }
                      
                      interface IERC20 {
                      
                          event Transfer(address indexed from, address indexed to, uint256 value);
                      
                          event Approval(address indexed owner, address indexed spender, uint256 value);
                      
                          function totalSupply() external view returns (uint256);
                      
                          function balanceOf(address account) external view returns (uint256);
                      
                          function transfer(address to, uint256 amount) external returns (bool);
                      
                          function allowance(address owner, address spender) external view returns (uint256);
                      
                          function approve(address spender, uint256 amount) external returns (bool);
                      
                          function transferFrom(
                              address from,
                              address to,
                              uint256 amount
                          ) external returns (bool);
                      }
                      
                      interface IERC20Metadata is IERC20 {
                      
                          function name() external view returns (string memory);
                      
                          function symbol() external view returns (string memory);
                      
                          function decimals() external view returns (uint8);
                      }
                      
                      contract ERC20 is IERC20, IERC20Metadata {
                          mapping(address => uint256) private _balances;
                      
                          mapping(address => mapping(address => uint256)) private _allowances;
                      
                          uint256 private _totalSupply;
                      
                          string private _name;
                          string private _symbol;
                      
                          constructor(string memory name_, string memory symbol_) {
                              _name = name_;
                              _symbol = symbol_;
                          }
                      
                          function name() public view virtual override returns (string memory) {
                              return _name;
                          }
                      
                          function symbol() public view virtual override returns (string memory) {
                              return _symbol;
                          }
                      
                          function decimals() public view virtual override returns (uint8) {
                              return 18;
                          }
                      
                          function totalSupply() public view virtual override returns (uint256) {
                              return _totalSupply;
                          }
                      
                          function balanceOf(address account) public view virtual override returns (uint256) {
                              return _balances[account];
                          }
                      
                          function transfer(address to, uint256 amount) public virtual override returns (bool) {
                              address owner = msg.sender;
                              _transfer(owner, to, amount);
                              return true;
                          }
                      
                          function allowance(address owner, address spender) public view virtual override returns (uint256) {
                              return _allowances[owner][spender];
                          }
                      
                          function approve(address spender, uint256 amount) public virtual override returns (bool) {
                              address owner = msg.sender;
                              _approve(owner, spender, amount);
                              return true;
                          }
                      
                          function transferFrom(
                              address from,
                              address to,
                              uint256 amount
                          ) public virtual override returns (bool) {
                              address spender = msg.sender;
                              _spendAllowance(from, spender, amount);
                              _transfer(from, to, amount);
                              return true;
                          }
                      
                          function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                              address owner = msg.sender;
                              _approve(owner, spender, allowance(owner, spender) + addedValue);
                              return true;
                          }
                      
                          function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                              address owner = msg.sender;
                              uint256 currentAllowance = allowance(owner, spender);
                              require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                              unchecked {
                                  _approve(owner, spender, currentAllowance - subtractedValue);
                              }
                      
                              return true;
                          }
                      
                          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");
                      
                              uint256 fromBalance = _balances[from];
                              require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                              unchecked {
                                  _balances[from] = fromBalance - amount;
                              }
                      
                              _balances[to] += amount;
                      
                              emit Transfer(from, to, amount);
                          }
                      
                          function _mint(address account, uint256 amount) internal virtual {
                              require(account != address(0), "ERC20: mint to the zero address");
                      
                              _totalSupply += amount;
                              _balances[account] += amount;
                              emit Transfer(address(0), account, amount);
                          }
                      
                          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);
                          }
                      
                          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);
                                  }
                              }
                          }
                      }
                      
                      interface ILiquidityHub {
                          function processFees(address) external;
                      }
                      
                      interface IDiscountAuthority {
                          function discountRatio(address) external view returns (uint256, uint256);
                      }
                      
                      contract X7DAO is ERC20, Ownable {
                      
                          IDiscountAuthority public discountAuthority;
                          ILiquidityHub public liquidityHub;
                      
                          mapping(address => bool) public ammPair;
                          address public offRampPair;
                      
                          // max 7% fee
                          uint256 public maxFeeNumerator = 700;
                      
                          // 6 % fee
                          uint256 public feeNumerator = 600;
                          uint256 public feeDenominator = 10000;
                      
                          bool discountAuthorityFrozen;
                          bool liquidityHubFrozen;
                      
                          bool transfersEnabled;
                      
                          event LiquidityHubSet(address indexed liquidityHub);
                          event DiscountAuthoritySet(address indexed discountAuthority);
                          event FeeNumeratorSet(uint256 feeNumerator);
                          event AMMSet(address indexed pairAddress, bool isAMM);
                          event OffRampPairSet(address indexed offRampPair);
                          event LiquidityHubFrozen();
                          event DiscountAuthorityFrozen();
                      
                          constructor(
                              address discountAuthority_,
                              address liquidityHub_
                          ) ERC20("X7DAO", "X7DAO") Ownable(address(0x7000a09c425ABf5173FF458dF1370C25d1C58105)) {
                              discountAuthority = IDiscountAuthority(discountAuthority_);
                              liquidityHub = ILiquidityHub(liquidityHub_);
                      
                              _mint(address(0x7000a09c425ABf5173FF458dF1370C25d1C58105), 100000000 * 10**18);
                          }
                      
                          function setLiquidityHub(address liquidityHub_) external onlyOwner {
                              require(!liquidityHubFrozen);
                              liquidityHub = ILiquidityHub(liquidityHub_);
                              emit LiquidityHubSet(liquidityHub_);
                          }
                      
                          function setDiscountAuthority(address discountAuthority_) external onlyOwner {
                              require(!discountAuthorityFrozen);
                              discountAuthority = IDiscountAuthority(discountAuthority_);
                              emit DiscountAuthoritySet(discountAuthority_);
                          }
                      
                          function setFeeNumerator(uint256 feeNumerator_) external onlyOwner {
                              require(feeNumerator_ <= maxFeeNumerator);
                              feeNumerator = feeNumerator_;
                              emit FeeNumeratorSet(feeNumerator_);
                          }
                      
                          function setAMM(address ammAddress, bool isAMM) external onlyOwner {
                              ammPair[ammAddress] = isAMM;
                              emit AMMSet(ammAddress, isAMM);
                          }
                      
                          function setOffRampPair(address ammAddress) external onlyOwner {
                              offRampPair = ammAddress;
                              emit OffRampPairSet(ammAddress);
                          }
                      
                          function freezeLiquidityHub() external onlyOwner {
                              require(!liquidityHubFrozen);
                              liquidityHubFrozen = true;
                              emit LiquidityHubFrozen();
                          }
                      
                          function freezeDiscountAuthority() external onlyOwner {
                              require(!discountAuthorityFrozen);
                              discountAuthorityFrozen = true;
                              emit DiscountAuthorityFrozen();
                          }
                      
                          function circulatingSupply() external view returns (uint256) {
                              return totalSupply() - balanceOf(address(0)) - balanceOf(address(0x000000000000000000000000000000000000dEaD));
                          }
                      
                          function enableTrading() external onlyOwner {
                              require(!transfersEnabled);
                              transfersEnabled = true;
                          }
                      
                          function _transfer(
                              address from,
                              address to,
                              uint256 amount
                          ) internal override {
                              require(transfersEnabled || from == owner());
                      
                              uint256 transferAmount = amount;
                      
                              if (
                                  from == address(liquidityHub)
                                  || to == address(liquidityHub)
                              ) {
                                  super._transfer(from, to, amount);
                                  return;
                              }
                      
                              if (
                                  ammPair[to] || ammPair[from]
                              ) {
                                  address effectivePrincipal;
                                  if (ammPair[to]) {
                                      effectivePrincipal = from;
                                  } else {
                                      effectivePrincipal = to;
                                  }
                      
                                  (uint256 feeModifierNumerator, uint256 feeModifierDenominator) = discountAuthority.discountRatio(effectivePrincipal);
                                  if (feeModifierNumerator > feeModifierDenominator || feeModifierDenominator == 0) {
                                      feeModifierNumerator = 1;
                                      feeModifierDenominator = 1;
                                  }
                      
                                  uint256 feeAmount = amount * feeNumerator * feeModifierNumerator / feeDenominator / feeModifierDenominator;
                      
                                  super._transfer(from, address(liquidityHub), feeAmount);
                                  transferAmount = amount - feeAmount;
                              }
                      
                              if (
                                  to == offRampPair
                              ) {
                                  liquidityHub.processFees(address(this));
                              }
                      
                              super._transfer(from, to, transferAmount);
                          }
                      
                          function rescueETH() external {
                              (bool success,) = payable(address(liquidityHub)).call{value: address(this).balance}("");
                              require(success);
                          }
                      
                          function rescueTokens(address tokenAddress) external {
                              IERC20(tokenAddress).transfer(address(liquidityHub), IERC20(tokenAddress).balanceOf(address(this)));
                          }
                      
                      }

                      File 4 of 8: XchangePair
                      /**
                       *Submitted for verification at Etherscan.io on 2023-05-29
                       */
                      
                      // SPDX-License-Identifier: GPL-3.0
                      pragma solidity =0.8.15;
                      
                      /*
                      
                       /$$   /$$ /$$$$$$$$       /$$$$$$$$ /$$
                      | $$  / $$|_____ $$/      | $$_____/|__/
                      |  $$/ $$/     /$$/       | $$       /$$ /$$$$$$$   /$$$$$$  /$$$$$$$   /$$$$$$$  /$$$$$$
                       \  $$$$/     /$$/        | $$$$$   | $$| $$__  $$ |____  $$| $$__  $$ /$$_____/ /$$__  $$
                        >$$  $$    /$$/         | $$__/   | $$| $$  \ $$  /$$$$$$$| $$  \ $$| $$      | $$$$$$$$
                       /$$/\  $$  /$$/          | $$      | $$| $$  | $$ /$$__  $$| $$  | $$| $$      | $$_____/
                      | $$  \ $$ /$$/           | $$      | $$| $$  | $$|  $$$$$$$| $$  | $$|  $$$$$$$|  $$$$$$$
                      |__/  |__/|__/            |__/      |__/|__/  |__/ \_______/|__/  |__/ \_______/ \_______/
                      
                      Contract: UniswapV2 Fork - XchangeFactory and XchangePair
                      
                      The factory contract maintains a number of "trusted" addresses and the pair contract has a number of additional features:
                      
                          * failsafe reserve minimums
                          * failsafe pair token burning (liquidity withdrawal)
                          * trustless and guarenteed fee collection
                          * tokens may swap themselves
                      
                      This contract will NOT be renounced.
                      
                      The following are the only functions that can be called on the factory contract that affect the contract:
                      
                          function setFeeTo(address _feeTo) external onlyOwner {
                              require(_feeTo != feeTo);
                              address oldFeeToo = feeTo;
                              feeTo = _feeTo;
                              emit FeeToSet(oldFeeToo, _feeTo);
                          }
                      
                          function setDiscountAuthority(address _discountAuthority) external onlyOwner {
                              require(_discountAuthority != discountAuthority);
                              address oldDiscountAuthority = discountAuthority;
                              discountAuthority = _discountAuthority;
                              emit DiscountAuthoritySet(oldDiscountAuthority, _discountAuthority);
                          }
                      
                          function setTrusted(address trustAddress, bool shouldTrustAddress) external onlyOwner {
                              require(_isTrusted[trustAddress] != shouldTrustAddress);
                              _isTrusted[trustAddress] = shouldTrustAddress;
                              emit TrustedSet(trustAddress, shouldTrustAddress);
                          }
                      
                          function setFailsafeLiquidator(address trustAddress, bool shouldTrustAddress) external onlyOwner {
                              require(_isFailSafeLiquidator[trustAddress] != shouldTrustAddress);
                              _isFailSafeLiquidator[trustAddress] = shouldTrustAddress;
                              emit FailsafeLiquidatorSet(trustAddress, shouldTrustAddress);
                          }
                      
                      These functions will be passed to DAO governance once the ecosystem stabilizes.
                      
                      */
                      
                      abstract contract Ownable {
                          address private _owner;
                      
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                      
                          constructor(address owner_) {
                              _transferOwnership(owner_);
                          }
                      
                          modifier onlyOwner() {
                              _checkOwner();
                              _;
                          }
                      
                          function owner() public view virtual returns (address) {
                              return _owner;
                          }
                      
                          function _checkOwner() internal view virtual {
                              require(owner() == msg.sender, "Ownable: caller is not the owner");
                          }
                      
                          function renounceOwnership() public virtual onlyOwner {
                              _transferOwnership(address(0));
                          }
                      
                          function transferOwnership(address newOwner) public virtual onlyOwner {
                              require(newOwner != address(0), "Ownable: new owner is the zero address");
                              _transferOwnership(newOwner);
                          }
                      
                          function _transferOwnership(address newOwner) internal virtual {
                              address oldOwner = _owner;
                              _owner = newOwner;
                              emit OwnershipTransferred(oldOwner, newOwner);
                          }
                      }
                      
                      interface IXchangeFactory {
                          event PairCreated(address indexed token0, address indexed token1, address pair, uint);
                          event TrustedSet(address indexed trustedPrincipal, bool isTrusted);
                          event FailsafeLiquidatorSet(address indexed trustedPrincipal, bool isTrusted);
                          event DiscountAuthoritySet(address indexed oldAddress, address indexed newAddress);
                          event FeeToSet(address indexed oldAddress, address indexed newAddress);
                      
                          function feeTo() external view returns (address);
                          function discountAuthority() external view returns (address);
                          function isTrusted(address) external view returns (bool);
                          function isFailsafeLiquidator(address) external view returns (bool);
                      
                          function getPair(address tokenA, address tokenB) external view returns (address pair);
                          function isPair(address pairAddress) external view returns (bool);
                          function allPairs(uint) external view returns (address pair);
                          function allPairsLength() external view returns (uint);
                          function pairTokens(address pairAddress, address tokenAddress) external view returns (bool);
                      
                          function createPair(address tokenA, address tokenB) external returns (address pair);
                      
                          function setFeeTo(address) external;
                          function setTrusted(address, bool) external;
                          function setDiscountAuthority(address) external;
                          function setFailsafeLiquidator(address, bool) external;
                      }
                      
                      interface IXchangePair {
                          event Mint(address indexed sender, uint amount0, uint amount1);
                          event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
                          event Swap(
                              address indexed sender,
                              uint amount0In,
                              uint amount1In,
                              uint amount0Out,
                              uint amount1Out,
                              address indexed to
                          );
                          event Sync(uint112 reserve0, uint112 reserve1);
                      
                          function MINIMUM_LIQUIDITY() external pure returns (uint);
                          function factory() external view returns (address);
                          function token0() external view returns (address);
                          function token1() external view returns (address);
                          function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
                          function price0CumulativeLast() external view returns (uint);
                          function price1CumulativeLast() external view returns (uint);
                          function kLast() external view returns (uint);
                          function mint(address to) external returns (uint liquidity);
                          function mintFee() external;
                          function burn(address to) external returns (uint amount0, uint amount1);
                          function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
                          function skim(address to) external;
                          function sync() external;
                      
                          function initialize(address, address) external;
                      
                          function mustBurn(address to, uint256 gasAmount) external returns (uint256 amount0, uint256 amount1);
                          function swapWithDiscount(
                              uint amount0Out,
                              uint amount1Out,
                              address to,
                              uint feeAmountOverride,
                              bytes calldata data
                          ) external;
                          function syncSafe(uint256 gasAmountToken0, uint256 gasAmountToken1) external;
                      
                          function withdrawTokensAgainstMinimumBalance(
                              address tokenAddress,
                              address to,
                              uint112 amount
                          ) external returns (uint112);
                          function setMinimumBalance(address tokenAddress, uint112 minimumAmount) external;
                      }
                      
                      interface IXchangeERC20 {
                          event Approval(address indexed owner, address indexed spender, uint value);
                          event Transfer(address indexed from, address indexed to, uint value);
                      
                          function name() external pure returns (string memory);
                          function symbol() external pure returns (string memory);
                          function decimals() external pure returns (uint8);
                          function totalSupply() external view returns (uint);
                          function balanceOf(address owner) external view returns (uint);
                          function allowance(address owner, address spender) external view returns (uint);
                      
                          function approve(address spender, uint value) external returns (bool);
                          function transfer(address to, uint value) external returns (bool);
                          function transferFrom(address from, address to, uint value) external returns (bool);
                      
                          function DOMAIN_SEPARATOR() external view returns (bytes32);
                          function PERMIT_TYPEHASH() external pure returns (bytes32);
                          function nonces(address owner) external view returns (uint);
                      
                          function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
                      }
                      
                      interface IERC20 {
                          event Approval(address indexed owner, address indexed spender, uint value);
                          event Transfer(address indexed from, address indexed to, uint value);
                      
                          function name() external view returns (string memory);
                          function symbol() external view returns (string memory);
                          function decimals() external view returns (uint8);
                          function totalSupply() external view returns (uint);
                          function balanceOf(address owner) external view returns (uint);
                          function allowance(address owner, address spender) external view returns (uint);
                      
                          function approve(address spender, uint value) external returns (bool);
                          function transfer(address to, uint value) external returns (bool);
                          function transferFrom(address from, address to, uint value) external returns (bool);
                      }
                      
                      interface IXchangeDiscountAuthority {
                          function fee(address) external view returns (uint8);
                      }
                      
                      interface IUniswapV2Callee {
                          function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
                      }
                      
                      contract XchangeERC20 is IXchangeERC20 {
                          string public constant name = "Xchange AMM V1";
                          string public constant symbol = "X7-AMM-V1";
                          uint8 public constant decimals = 6;
                          uint public totalSupply;
                          mapping(address => uint) public balanceOf;
                          mapping(address => mapping(address => uint)) public allowance;
                      
                          bytes32 public DOMAIN_SEPARATOR;
                          // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                          bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                          mapping(address => uint) public nonces;
                      
                          constructor() {
                              uint chainId;
                              assembly {
                                  chainId := chainid()
                              }
                              DOMAIN_SEPARATOR = keccak256(
                                  abi.encode(
                                      keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                                      keccak256(bytes(name)),
                                      keccak256(bytes("1")),
                                      chainId,
                                      address(this)
                                  )
                              );
                          }
                      
                          function approve(address spender, uint value) external returns (bool) {
                              _approve(msg.sender, spender, value);
                              return true;
                          }
                      
                          function transfer(address to, uint value) external returns (bool) {
                              _transfer(msg.sender, to, value);
                              return true;
                          }
                      
                          function transferFrom(address from, address to, uint value) external returns (bool) {
                              if (allowance[from][msg.sender] != type(uint).max) {
                                  allowance[from][msg.sender] = allowance[from][msg.sender] - value;
                              }
                              _transfer(from, to, value);
                              return true;
                          }
                      
                          function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
                              require(deadline >= block.timestamp, "Xchange: EXPIRED");
                              bytes32 digest = keccak256(
                                  abi.encodePacked(
                                      "\x19\x01",
                                      DOMAIN_SEPARATOR,
                                      keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                                  )
                              );
                              address recoveredAddress = ecrecover(digest, v, r, s);
                              require(recoveredAddress != address(0) && recoveredAddress == owner, "Xchange: INVALID_SIGNATURE");
                              _approve(owner, spender, value);
                          }
                      
                          function _mint(address to, uint value) internal {
                              totalSupply = totalSupply + value;
                              balanceOf[to] = balanceOf[to] + value;
                              emit Transfer(address(0), to, value);
                          }
                      
                          function _burn(address from, uint value) internal {
                              balanceOf[from] = balanceOf[from] - value;
                              totalSupply = totalSupply - value;
                              emit Transfer(from, address(0), value);
                          }
                      
                          function _approve(address owner, address spender, uint value) private {
                              allowance[owner][spender] = value;
                              emit Approval(owner, spender, value);
                          }
                      
                          function _transfer(address from, address to, uint value) private {
                              balanceOf[from] = balanceOf[from] - value;
                              balanceOf[to] = balanceOf[to] + value;
                              emit Transfer(from, to, value);
                          }
                      }
                      
                      contract XchangePair is IXchangePair, XchangeERC20 {
                          using UQ112x112 for uint224;
                      
                          uint public constant MINIMUM_LIQUIDITY = 10 ** 3;
                          bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
                      
                          IXchangeFactory _factory;
                          address public token0;
                          address public token1;
                      
                          uint112 private reserve0; // uses single storage slot, accessible via getReserves
                          uint112 private reserve1; // uses single storage slot, accessible via getReserves
                          uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
                      
                          uint public price0CumulativeLast;
                          uint public price1CumulativeLast;
                          uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
                      
                          bool public hasMinimums;
                          mapping(address => uint112) public tokenMinimumBalance;
                      
                          uint private unlocked = 1;
                          modifier lock() {
                              require(unlocked == 1, "Xchange: LOCKED");
                              unlocked = 0;
                              _;
                              unlocked = 1;
                          }
                      
                          function factory() public view returns (address) {
                              return address(_factory);
                          }
                      
                          function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
                              _reserve0 = reserve0;
                              _reserve1 = reserve1;
                              _blockTimestampLast = blockTimestampLast;
                          }
                      
                          constructor() {
                              _factory = IXchangeFactory(msg.sender);
                          }
                      
                          // called once by the factory at time of deployment
                          function initialize(address _token0, address _token1) external {
                              require(msg.sender == address(_factory), "Xchange: FORBIDDEN"); // sufficient check
                              token0 = _token0;
                              token1 = _token1;
                          }
                      
                          function mintFee() external {
                              (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
                              _mintFee(_reserve0, _reserve1);
                          }
                      
                          function setMinimumBalance(address tokenAddress, uint112 minimumAmount) external {
                              require(_factory.isTrusted(msg.sender), "Xchange: FORBIDDEN");
                              tokenMinimumBalance[tokenAddress] = minimumAmount;
                      
                              if (tokenMinimumBalance[token0] == 0 && tokenMinimumBalance[token1] == 0) {
                                  hasMinimums = false;
                              } else {
                                  hasMinimums = true;
                              }
                          }
                      
                          // this low-level function should be called from a contract which performs important safety checks
                          // The caller should try to call `sync` or `syncSafe`
                          function withdrawTokensAgainstMinimumBalance(
                              address tokenAddress,
                              address to,
                              uint112 amount
                          ) external returns (uint112) {
                              require(_factory.isTrusted(msg.sender), "Xchange: FORBIDDEN");
                              if (amount > tokenMinimumBalance[tokenAddress]) {
                                  amount = tokenMinimumBalance[tokenAddress];
                              }
                              tokenMinimumBalance[tokenAddress] -= amount;
                              _safeTransfer(tokenAddress, to, amount);
                      
                              if (tokenMinimumBalance[token0] == 0 && tokenMinimumBalance[token1] == 0) {
                                  hasMinimums = false;
                              }
                      
                              return amount;
                          }
                      
                          // this low-level function should be called from a contract which performs important safety checks
                          function mint(address to) external lock returns (uint liquidity) {
                              (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
                              uint balance0 = IERC20(token0).balanceOf(address(this));
                              uint balance1 = IERC20(token1).balanceOf(address(this));
                              uint amount0 = balance0 - _reserve0;
                              uint amount1 = balance1 - _reserve1;
                      
                              bool feeOn = _mintFee(_reserve0, _reserve1);
                              uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                              if (_totalSupply == 0) {
                                  liquidity = Math.sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY;
                                  _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
                              } else {
                                  liquidity = Math.min((amount0 * _totalSupply) / _reserve0, (amount1 * _totalSupply) / _reserve1);
                              }
                              require(liquidity > 0, "Xchange: INSUFFICIENT_LIQUIDITY_MINTED");
                              _mint(to, liquidity);
                      
                              _update(balance0, balance1, _reserve0, _reserve1);
                              if (feeOn) kLast = uint(reserve0) * reserve1; // reserve0 and reserve1 are up-to-date
                              emit Mint(msg.sender, amount0, amount1);
                          }
                      
                          // this low-level function should be called from a contract which performs important safety checks
                          function burn(address to) external lock returns (uint amount0, uint amount1) {
                              (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
                              address _token0 = token0; // gas savings
                              address _token1 = token1; // gas savings
                              uint balance0 = IERC20(_token0).balanceOf(address(this));
                              uint balance1 = IERC20(_token1).balanceOf(address(this));
                              uint liquidity = balanceOf[address(this)];
                      
                              bool feeOn = _mintFee(_reserve0, _reserve1);
                              uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                              amount0 = (liquidity * balance0) / _totalSupply; // using balances ensures pro-rata distribution
                              amount1 = (liquidity * balance1) / _totalSupply; // using balances ensures pro-rata distribution
                              require(amount0 > 0 && amount1 > 0, "Xchange: INSUFFICIENT_LIQUIDITY_BURNED");
                              _burn(address(this), liquidity);
                              _safeTransfer(_token0, to, amount0);
                              _safeTransfer(_token1, to, amount1);
                              balance0 = IERC20(_token0).balanceOf(address(this));
                              balance1 = IERC20(_token1).balanceOf(address(this));
                      
                              _update(balance0, balance1, _reserve0, _reserve1);
                              if (feeOn) kLast = uint(reserve0) * reserve1; // reserve0 and reserve1 are up-to-date
                              if (hasMinimums) {
                                  require(balance0 >= tokenMinimumBalance[_token0], "Xchange: INSUFFICIENT_TOKEN0_BALANCE");
                                  require(balance1 >= tokenMinimumBalance[_token1], "Xchange: INSUFFICIENT_TOKEN1_BALANCE");
                              }
                              emit Burn(msg.sender, amount0, amount1, to);
                          }
                      
                          function mustBurn(address to, uint256 gasAmount) external lock returns (uint amount0, uint amount1) {
                              require(_factory.isFailsafeLiquidator(msg.sender));
                              (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
                              address _token0 = token0; // gas savings
                              address _token1 = token1; // gas savings
                      
                              uint balance0 = _reserve0;
                              uint balance1 = _reserve1;
                              uint liquidity = balanceOf[address(this)];
                      
                              bool feeOn = _mintFee(_reserve0, _reserve1);
                              uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
                              amount0 = (liquidity * balance0) / _totalSupply; // using balances ensures pro-rata distribution
                              amount1 = (liquidity * balance1) / _totalSupply; // using balances ensures pro-rata distribution
                              require(amount0 > 0 && amount1 > 0, "Xchange: INSUFFICIENT_LIQUIDITY_BURNED");
                              _burn(address(this), liquidity);
                              amount0 = _trySafeTransfer(_token0, to, amount0, gasAmount);
                              amount1 = _trySafeTransfer(_token1, to, amount1, gasAmount);
                      
                              if (gasAmount > 0) {
                                  try IERC20(_token0).balanceOf{ gas: gasAmount }(address(this)) returns (uint256 balance0_) {
                                      balance0 = balance0_;
                                  } catch {}
                      
                                  try IERC20(_token1).balanceOf{ gas: gasAmount }(address(this)) returns (uint256 balance1_) {
                                      balance1 = balance1_;
                                  } catch {}
                              } else {
                                  balance0 = IERC20(_token0).balanceOf(address(this));
                                  balance1 = IERC20(_token1).balanceOf(address(this));
                              }
                      
                              _update(balance0, balance1, _reserve0, _reserve1);
                              if (feeOn) kLast = uint(reserve0) * reserve1; // reserve0 and reserve1 are up-to-date
                              if (hasMinimums) {
                                  require(balance0 >= tokenMinimumBalance[_token0], "Xchange: INSUFFICIENT_TOKEN0_BALANCE");
                                  require(balance1 >= tokenMinimumBalance[_token1], "Xchange: INSUFFICIENT_TOKEN1_BALANCE");
                              }
                              emit Burn(msg.sender, amount0, amount1, to);
                          }
                      
                          // this low-level function should be called from a contract which performs important safety checks
                          function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
                              _swap(amount0Out, amount1Out, to, 200, data);
                          }
                      
                          // this low-level function should be called from a contract which performs important safety checks
                          function swapWithDiscount(
                              uint amount0Out,
                              uint amount1Out,
                              address to,
                              uint feeAmountOverride,
                              bytes calldata data
                          ) external lock {
                              _swap(amount0Out, amount1Out, to, feeAmountOverride, data);
                          }
                      
                          // force balances to match reserves
                          function skim(address to) external lock {
                              address _token0 = token0; // gas savings
                              address _token1 = token1; // gas savings
                              _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)) - reserve0);
                              _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)) - reserve1);
                              if (hasMinimums) {
                                  require(
                                      IERC20(_token0).balanceOf(address(this)) >= tokenMinimumBalance[_token0],
                                      "Xchange: INSUFFICIENT_TOKEN0_BALANCE"
                                  );
                                  require(
                                      IERC20(_token1).balanceOf(address(this)) >= tokenMinimumBalance[_token1],
                                      "Xchange: INSUFFICIENT_TOKEN1_BALANCE"
                                  );
                              }
                          }
                      
                          // force reserves to match balances
                          function sync() external lock {
                              _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
                          }
                      
                          // attempt to force reserves to match balances
                          function syncSafe(uint256 gasAmountToken0, uint256 gasAmountToken1) external lock {
                              require(_factory.isTrusted(msg.sender), "Xchange: FORBIDDEN");
                              _update(
                                  IERC20(token0).balanceOf{ gas: gasAmountToken0 }(address(this)),
                                  IERC20(token1).balanceOf{ gas: gasAmountToken1 }(address(this)),
                                  reserve0,
                                  reserve1
                              );
                          }
                      
                          // if fee is on, mint liquidity equivalent to 1/2th of the growth in sqrt(k)
                          function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
                              address feeTo = _factory.feeTo();
                              feeOn = feeTo != address(0);
                              uint _kLast = kLast; // gas savings
                              if (feeOn) {
                                  if (_kLast != 0) {
                                      uint rootK = Math.sqrt(uint(_reserve0) * _reserve1);
                                      uint rootKLast = Math.sqrt(_kLast);
                                      if (rootK > rootKLast) {
                                          uint numerator = totalSupply * (rootK - rootKLast);
                                          uint denominator = rootK + rootKLast;
                                          uint liquidity = numerator / denominator;
                                          if (liquidity > 0) _mint(feeTo, liquidity);
                                      }
                                  }
                              } else if (_kLast != 0) {
                                  kLast = 0;
                              }
                          }
                      
                          function _swap(uint amount0Out, uint amount1Out, address to, uint feeAmountOverride, bytes calldata data) internal {
                              require(amount0Out > 0 || amount1Out > 0, "Xchange: INSUFFICIENT_OUTPUT_AMOUNT");
                              (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); // gas savings
                              require(amount0Out < _reserve0 && amount1Out < _reserve1, "Xchange: INSUFFICIENT_LIQUIDITY");
                      
                              uint[2] memory balances;
                              {
                                  // scope for _token{0,1}, avoids stack too deep errors
                                  address _token0 = token0;
                                  address _token1 = token1;
                                  if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
                                  if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
                                  if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
                                  balances[0] = IERC20(_token0).balanceOf(address(this));
                                  balances[1] = IERC20(_token1).balanceOf(address(this));
                                  if (hasMinimums) {
                                      require(balances[0] >= tokenMinimumBalance[_token0], "Xchange: INSUFFICIENT_TOKEN0_BALANCE");
                                      require(balances[1] >= tokenMinimumBalance[_token1], "Xchange: INSUFFICIENT_TOKEN1_BALANCE");
                                  }
                              }
                              uint amount0In = balances[0] > _reserve0 - amount0Out ? balances[0] - (_reserve0 - amount0Out) : 0;
                              uint amount1In = balances[1] > _reserve1 - amount1Out ? balances[1] - (_reserve1 - amount1Out) : 0;
                              require(amount0In > 0 || amount1In > 0, "Xchange: INSUFFICIENT_INPUT_AMOUNT");
                              {
                                  // scope for reserve{0,1}Adjusted, avoids stack too deep errors
                                  uint feeAmount = 200;
                                  if (feeAmountOverride != 200) {
                                      if (_factory.isTrusted(msg.sender)) {
                                          feeAmount = feeAmountOverride;
                                      } else {
                                          feeAmount = IXchangeDiscountAuthority(_factory.discountAuthority()).fee(msg.sender);
                                      }
                                      feeAmount = feeAmount <= 200 ? feeAmount : 200;
                                  }
                      
                                  uint balance0Adjusted = (balances[0] * 100000) - (amount0In * feeAmount);
                                  uint balance1Adjusted = (balances[1] * 100000) - (amount1In * feeAmount);
                                  require(balance0Adjusted * balance1Adjusted >= uint(_reserve0) * _reserve1 * 100000 ** 2, "Xchange: K");
                              }
                      
                              _update(balances[0], balances[1], _reserve0, _reserve1);
                              emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
                          }
                      
                          // update reserves and, on the first call per block, price accumulators
                          function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
                              require(balance0 <= type(uint112).max && balance1 <= type(uint112).max, "Xchange: OVERFLOW");
                      
                              unchecked {
                                  uint32 timeElapsed = uint32(block.timestamp) - blockTimestampLast; // overflow is desired
                                  if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                                      // * never overflows, and + overflow is desired
                                      price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                                      price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
                                  }
                              }
                              reserve0 = uint112(balance0);
                              reserve1 = uint112(balance1);
                              blockTimestampLast = uint32(block.timestamp);
                              emit Sync(reserve0, reserve1);
                          }
                      
                          function _safeTransfer(address token, address to, uint value) private {
                              (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
                              require(success && (data.length == 0 || abi.decode(data, (bool))), "Xchange: TRANSFER_FAILED");
                          }
                      
                          function _trySafeTransfer(address token, address to, uint value, uint gasAmount) private returns (uint) {
                              (bool ok, ) = token.call{ gas: gasAmount }(abi.encodeWithSelector(SELECTOR, to, value));
                              if (ok) {
                                  return value;
                              } else {
                                  return 0;
                              }
                          }
                      }
                      
                      contract XchangeFactory is IXchangeFactory, Ownable {
                          address public feeTo;
                          address public discountAuthority;
                          mapping(address => bool) _isTrusted;
                          mapping(address => bool) _isFailSafeLiquidator;
                      
                          mapping(address => mapping(address => address)) public getPair;
                          mapping(address => bool) public isPair;
                          address[] public allPairs;
                      
                          // Pair Address => token address => Is in the pair
                          mapping(address => mapping(address => bool)) public pairTokens;
                      
                          constructor() Ownable(address(0xC71a68467c5e090a61079797E1ED96df7DA69266)) {
                              _isTrusted[address(this)] = true;
                          }
                      
                          function allPairsLength() external view returns (uint) {
                              return allPairs.length;
                          }
                      
                          function isTrusted(address checkAddress) external view returns (bool) {
                              return _isTrusted[checkAddress];
                          }
                      
                          function isFailsafeLiquidator(address checkAddress) external view returns (bool) {
                              return _isFailSafeLiquidator[checkAddress];
                          }
                      
                          function setFeeTo(address _feeTo) external onlyOwner {
                              require(_feeTo != feeTo);
                              address oldFeeToo = feeTo;
                              feeTo = _feeTo;
                              emit FeeToSet(oldFeeToo, _feeTo);
                          }
                      
                          function setDiscountAuthority(address _discountAuthority) external onlyOwner {
                              require(_discountAuthority != discountAuthority);
                              address oldDiscountAuthority = discountAuthority;
                              discountAuthority = _discountAuthority;
                              emit DiscountAuthoritySet(oldDiscountAuthority, _discountAuthority);
                          }
                      
                          function setTrusted(address trustAddress, bool shouldTrustAddress) external onlyOwner {
                              require(_isTrusted[trustAddress] != shouldTrustAddress);
                              _isTrusted[trustAddress] = shouldTrustAddress;
                              emit TrustedSet(trustAddress, shouldTrustAddress);
                          }
                      
                          function setFailsafeLiquidator(address trustAddress, bool shouldTrustAddress) external onlyOwner {
                              require(_isFailSafeLiquidator[trustAddress] != shouldTrustAddress);
                              _isFailSafeLiquidator[trustAddress] = shouldTrustAddress;
                              emit FailsafeLiquidatorSet(trustAddress, shouldTrustAddress);
                          }
                      
                          function createPair(address tokenA, address tokenB) external returns (address pair) {
                              require(tokenA != tokenB, "Xchange: IDENTICAL_ADDRESSES");
                              (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
                              require(token0 != address(0), "Xchange: ZERO_ADDRESS");
                              require(getPair[token0][token1] == address(0), "Xchange: PAIR_EXISTS"); // single check is sufficient
                              bytes memory bytecode = type(XchangePair).creationCode;
                              bytes32 salt = keccak256(abi.encodePacked(token0, token1));
                              assembly {
                                  pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
                              }
                      
                              IXchangePair(pair).initialize(token0, token1);
                              getPair[token0][token1] = pair;
                              getPair[token1][token0] = pair; // populate mapping in the reverse direction
                              pairTokens[pair][token0] = true;
                              pairTokens[pair][token1] = true;
                              isPair[pair] = true;
                              allPairs.push(pair);
                              emit PairCreated(token0, token1, pair, allPairs.length);
                          }
                      }
                      
                      // a library for performing various math operations
                      
                      library Math {
                          function min(uint x, uint y) internal pure returns (uint z) {
                              z = x < y ? x : y;
                          }
                      
                          // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
                          function sqrt(uint y) internal pure returns (uint z) {
                              if (y > 3) {
                                  z = y;
                                  uint x = y / 2 + 1;
                                  while (x < z) {
                                      z = x;
                                      x = (y / x + x) / 2;
                                  }
                              } else if (y != 0) {
                                  z = 1;
                              }
                          }
                      }
                      
                      // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
                      
                      // range: [0, 2**112 - 1]
                      // resolution: 1 / 2**112
                      
                      library UQ112x112 {
                          uint224 constant Q112 = 2 ** 112;
                      
                          // encode a uint112 as a UQ112x112
                          function encode(uint112 y) internal pure returns (uint224 z) {
                              z = uint224(y) * Q112; // never overflows
                          }
                      
                          // divide a UQ112x112 by a uint112, returning a UQ112x112
                          function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
                              z = x / uint224(y);
                          }
                      }

                      File 5 of 8: WETH9
                      // Copyright (C) 2015, 2016, 2017 Dapphub
                      
                      // This program is free software: you can redistribute it and/or modify
                      // it under the terms of the GNU General Public License as published by
                      // the Free Software Foundation, either version 3 of the License, or
                      // (at your option) any later version.
                      
                      // This program is distributed in the hope that it will be useful,
                      // but WITHOUT ANY WARRANTY; without even the implied warranty of
                      // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                      // GNU General Public License for more details.
                      
                      // You should have received a copy of the GNU General Public License
                      // along with this program.  If not, see <http://www.gnu.org/licenses/>.
                      
                      pragma solidity ^0.4.18;
                      
                      contract WETH9 {
                          string public name     = "Wrapped Ether";
                          string public symbol   = "WETH";
                          uint8  public decimals = 18;
                      
                          event  Approval(address indexed src, address indexed guy, uint wad);
                          event  Transfer(address indexed src, address indexed dst, uint wad);
                          event  Deposit(address indexed dst, uint wad);
                          event  Withdrawal(address indexed src, uint wad);
                      
                          mapping (address => uint)                       public  balanceOf;
                          mapping (address => mapping (address => uint))  public  allowance;
                      
                          function() public payable {
                              deposit();
                          }
                          function deposit() public payable {
                              balanceOf[msg.sender] += msg.value;
                              Deposit(msg.sender, msg.value);
                          }
                          function withdraw(uint wad) public {
                              require(balanceOf[msg.sender] >= wad);
                              balanceOf[msg.sender] -= wad;
                              msg.sender.transfer(wad);
                              Withdrawal(msg.sender, wad);
                          }
                      
                          function totalSupply() public view returns (uint) {
                              return this.balance;
                          }
                      
                          function approve(address guy, uint wad) public returns (bool) {
                              allowance[msg.sender][guy] = wad;
                              Approval(msg.sender, guy, wad);
                              return true;
                          }
                      
                          function transfer(address dst, uint wad) public returns (bool) {
                              return transferFrom(msg.sender, dst, wad);
                          }
                      
                          function transferFrom(address src, address dst, uint wad)
                              public
                              returns (bool)
                          {
                              require(balanceOf[src] >= wad);
                      
                              if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                                  require(allowance[src][msg.sender] >= wad);
                                  allowance[src][msg.sender] -= wad;
                              }
                      
                              balanceOf[src] -= wad;
                              balanceOf[dst] += wad;
                      
                              Transfer(src, dst, wad);
                      
                              return true;
                          }
                      }
                      
                      
                      /*
                                          GNU GENERAL PUBLIC LICENSE
                                             Version 3, 29 June 2007
                      
                       Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
                       Everyone is permitted to copy and distribute verbatim copies
                       of this license document, but changing it is not allowed.
                      
                                                  Preamble
                      
                        The GNU General Public License is a free, copyleft license for
                      software and other kinds of works.
                      
                        The licenses for most software and other practical works are designed
                      to take away your freedom to share and change the works.  By contrast,
                      the GNU General Public License is intended to guarantee your freedom to
                      share and change all versions of a program--to make sure it remains free
                      software for all its users.  We, the Free Software Foundation, use the
                      GNU General Public License for most of our software; it applies also to
                      any other work released this way by its authors.  You can apply it to
                      your programs, too.
                      
                        When we speak of free software, we are referring to freedom, not
                      price.  Our General Public Licenses are designed to make sure that you
                      have the freedom to distribute copies of free software (and charge for
                      them if you wish), that you receive source code or can get it if you
                      want it, that you can change the software or use pieces of it in new
                      free programs, and that you know you can do these things.
                      
                        To protect your rights, we need to prevent others from denying you
                      these rights or asking you to surrender the rights.  Therefore, you have
                      certain responsibilities if you distribute copies of the software, or if
                      you modify it: responsibilities to respect the freedom of others.
                      
                        For example, if you distribute copies of such a program, whether
                      gratis or for a fee, you must pass on to the recipients the same
                      freedoms that you received.  You must make sure that they, too, receive
                      or can get the source code.  And you must show them these terms so they
                      know their rights.
                      
                        Developers that use the GNU GPL protect your rights with two steps:
                      (1) assert copyright on the software, and (2) offer you this License
                      giving you legal permission to copy, distribute and/or modify it.
                      
                        For the developers' and authors' protection, the GPL clearly explains
                      that there is no warranty for this free software.  For both users' and
                      authors' sake, the GPL requires that modified versions be marked as
                      changed, so that their problems will not be attributed erroneously to
                      authors of previous versions.
                      
                        Some devices are designed to deny users access to install or run
                      modified versions of the software inside them, although the manufacturer
                      can do so.  This is fundamentally incompatible with the aim of
                      protecting users' freedom to change the software.  The systematic
                      pattern of such abuse occurs in the area of products for individuals to
                      use, which is precisely where it is most unacceptable.  Therefore, we
                      have designed this version of the GPL to prohibit the practice for those
                      products.  If such problems arise substantially in other domains, we
                      stand ready to extend this provision to those domains in future versions
                      of the GPL, as needed to protect the freedom of users.
                      
                        Finally, every program is threatened constantly by software patents.
                      States should not allow patents to restrict development and use of
                      software on general-purpose computers, but in those that do, we wish to
                      avoid the special danger that patents applied to a free program could
                      make it effectively proprietary.  To prevent this, the GPL assures that
                      patents cannot be used to render the program non-free.
                      
                        The precise terms and conditions for copying, distribution and
                      modification follow.
                      
                                             TERMS AND CONDITIONS
                      
                        0. Definitions.
                      
                        "This License" refers to version 3 of the GNU General Public License.
                      
                        "Copyright" also means copyright-like laws that apply to other kinds of
                      works, such as semiconductor masks.
                      
                        "The Program" refers to any copyrightable work licensed under this
                      License.  Each licensee is addressed as "you".  "Licensees" and
                      "recipients" may be individuals or organizations.
                      
                        To "modify" a work means to copy from or adapt all or part of the work
                      in a fashion requiring copyright permission, other than the making of an
                      exact copy.  The resulting work is called a "modified version" of the
                      earlier work or a work "based on" the earlier work.
                      
                        A "covered work" means either the unmodified Program or a work based
                      on the Program.
                      
                        To "propagate" a work means to do anything with it that, without
                      permission, would make you directly or secondarily liable for
                      infringement under applicable copyright law, except executing it on a
                      computer or modifying a private copy.  Propagation includes copying,
                      distribution (with or without modification), making available to the
                      public, and in some countries other activities as well.
                      
                        To "convey" a work means any kind of propagation that enables other
                      parties to make or receive copies.  Mere interaction with a user through
                      a computer network, with no transfer of a copy, is not conveying.
                      
                        An interactive user interface displays "Appropriate Legal Notices"
                      to the extent that it includes a convenient and prominently visible
                      feature that (1) displays an appropriate copyright notice, and (2)
                      tells the user that there is no warranty for the work (except to the
                      extent that warranties are provided), that licensees may convey the
                      work under this License, and how to view a copy of this License.  If
                      the interface presents a list of user commands or options, such as a
                      menu, a prominent item in the list meets this criterion.
                      
                        1. Source Code.
                      
                        The "source code" for a work means the preferred form of the work
                      for making modifications to it.  "Object code" means any non-source
                      form of a work.
                      
                        A "Standard Interface" means an interface that either is an official
                      standard defined by a recognized standards body, or, in the case of
                      interfaces specified for a particular programming language, one that
                      is widely used among developers working in that language.
                      
                        The "System Libraries" of an executable work include anything, other
                      than the work as a whole, that (a) is included in the normal form of
                      packaging a Major Component, but which is not part of that Major
                      Component, and (b) serves only to enable use of the work with that
                      Major Component, or to implement a Standard Interface for which an
                      implementation is available to the public in source code form.  A
                      "Major Component", in this context, means a major essential component
                      (kernel, window system, and so on) of the specific operating system
                      (if any) on which the executable work runs, or a compiler used to
                      produce the work, or an object code interpreter used to run it.
                      
                        The "Corresponding Source" for a work in object code form means all
                      the source code needed to generate, install, and (for an executable
                      work) run the object code and to modify the work, including scripts to
                      control those activities.  However, it does not include the work's
                      System Libraries, or general-purpose tools or generally available free
                      programs which are used unmodified in performing those activities but
                      which are not part of the work.  For example, Corresponding Source
                      includes interface definition files associated with source files for
                      the work, and the source code for shared libraries and dynamically
                      linked subprograms that the work is specifically designed to require,
                      such as by intimate data communication or control flow between those
                      subprograms and other parts of the work.
                      
                        The Corresponding Source need not include anything that users
                      can regenerate automatically from other parts of the Corresponding
                      Source.
                      
                        The Corresponding Source for a work in source code form is that
                      same work.
                      
                        2. Basic Permissions.
                      
                        All rights granted under this License are granted for the term of
                      copyright on the Program, and are irrevocable provided the stated
                      conditions are met.  This License explicitly affirms your unlimited
                      permission to run the unmodified Program.  The output from running a
                      covered work is covered by this License only if the output, given its
                      content, constitutes a covered work.  This License acknowledges your
                      rights of fair use or other equivalent, as provided by copyright law.
                      
                        You may make, run and propagate covered works that you do not
                      convey, without conditions so long as your license otherwise remains
                      in force.  You may convey covered works to others for the sole purpose
                      of having them make modifications exclusively for you, or provide you
                      with facilities for running those works, provided that you comply with
                      the terms of this License in conveying all material for which you do
                      not control copyright.  Those thus making or running the covered works
                      for you must do so exclusively on your behalf, under your direction
                      and control, on terms that prohibit them from making any copies of
                      your copyrighted material outside their relationship with you.
                      
                        Conveying under any other circumstances is permitted solely under
                      the conditions stated below.  Sublicensing is not allowed; section 10
                      makes it unnecessary.
                      
                        3. Protecting Users' Legal Rights From Anti-Circumvention Law.
                      
                        No covered work shall be deemed part of an effective technological
                      measure under any applicable law fulfilling obligations under article
                      11 of the WIPO copyright treaty adopted on 20 December 1996, or
                      similar laws prohibiting or restricting circumvention of such
                      measures.
                      
                        When you convey a covered work, you waive any legal power to forbid
                      circumvention of technological measures to the extent such circumvention
                      is effected by exercising rights under this License with respect to
                      the covered work, and you disclaim any intention to limit operation or
                      modification of the work as a means of enforcing, against the work's
                      users, your or third parties' legal rights to forbid circumvention of
                      technological measures.
                      
                        4. Conveying Verbatim Copies.
                      
                        You may convey verbatim copies of the Program's source code as you
                      receive it, in any medium, provided that you conspicuously and
                      appropriately publish on each copy an appropriate copyright notice;
                      keep intact all notices stating that this License and any
                      non-permissive terms added in accord with section 7 apply to the code;
                      keep intact all notices of the absence of any warranty; and give all
                      recipients a copy of this License along with the Program.
                      
                        You may charge any price or no price for each copy that you convey,
                      and you may offer support or warranty protection for a fee.
                      
                        5. Conveying Modified Source Versions.
                      
                        You may convey a work based on the Program, or the modifications to
                      produce it from the Program, in the form of source code under the
                      terms of section 4, provided that you also meet all of these conditions:
                      
                          a) The work must carry prominent notices stating that you modified
                          it, and giving a relevant date.
                      
                          b) The work must carry prominent notices stating that it is
                          released under this License and any conditions added under section
                          7.  This requirement modifies the requirement in section 4 to
                          "keep intact all notices".
                      
                          c) You must license the entire work, as a whole, under this
                          License to anyone who comes into possession of a copy.  This
                          License will therefore apply, along with any applicable section 7
                          additional terms, to the whole of the work, and all its parts,
                          regardless of how they are packaged.  This License gives no
                          permission to license the work in any other way, but it does not
                          invalidate such permission if you have separately received it.
                      
                          d) If the work has interactive user interfaces, each must display
                          Appropriate Legal Notices; however, if the Program has interactive
                          interfaces that do not display Appropriate Legal Notices, your
                          work need not make them do so.
                      
                        A compilation of a covered work with other separate and independent
                      works, which are not by their nature extensions of the covered work,
                      and which are not combined with it such as to form a larger program,
                      in or on a volume of a storage or distribution medium, is called an
                      "aggregate" if the compilation and its resulting copyright are not
                      used to limit the access or legal rights of the compilation's users
                      beyond what the individual works permit.  Inclusion of a covered work
                      in an aggregate does not cause this License to apply to the other
                      parts of the aggregate.
                      
                        6. Conveying Non-Source Forms.
                      
                        You may convey a covered work in object code form under the terms
                      of sections 4 and 5, provided that you also convey the
                      machine-readable Corresponding Source under the terms of this License,
                      in one of these ways:
                      
                          a) Convey the object code in, or embodied in, a physical product
                          (including a physical distribution medium), accompanied by the
                          Corresponding Source fixed on a durable physical medium
                          customarily used for software interchange.
                      
                          b) Convey the object code in, or embodied in, a physical product
                          (including a physical distribution medium), accompanied by a
                          written offer, valid for at least three years and valid for as
                          long as you offer spare parts or customer support for that product
                          model, to give anyone who possesses the object code either (1) a
                          copy of the Corresponding Source for all the software in the
                          product that is covered by this License, on a durable physical
                          medium customarily used for software interchange, for a price no
                          more than your reasonable cost of physically performing this
                          conveying of source, or (2) access to copy the
                          Corresponding Source from a network server at no charge.
                      
                          c) Convey individual copies of the object code with a copy of the
                          written offer to provide the Corresponding Source.  This
                          alternative is allowed only occasionally and noncommercially, and
                          only if you received the object code with such an offer, in accord
                          with subsection 6b.
                      
                          d) Convey the object code by offering access from a designated
                          place (gratis or for a charge), and offer equivalent access to the
                          Corresponding Source in the same way through the same place at no
                          further charge.  You need not require recipients to copy the
                          Corresponding Source along with the object code.  If the place to
                          copy the object code is a network server, the Corresponding Source
                          may be on a different server (operated by you or a third party)
                          that supports equivalent copying facilities, provided you maintain
                          clear directions next to the object code saying where to find the
                          Corresponding Source.  Regardless of what server hosts the
                          Corresponding Source, you remain obligated to ensure that it is
                          available for as long as needed to satisfy these requirements.
                      
                          e) Convey the object code using peer-to-peer transmission, provided
                          you inform other peers where the object code and Corresponding
                          Source of the work are being offered to the general public at no
                          charge under subsection 6d.
                      
                        A separable portion of the object code, whose source code is excluded
                      from the Corresponding Source as a System Library, need not be
                      included in conveying the object code work.
                      
                        A "User Product" is either (1) a "consumer product", which means any
                      tangible personal property which is normally used for personal, family,
                      or household purposes, or (2) anything designed or sold for incorporation
                      into a dwelling.  In determining whether a product is a consumer product,
                      doubtful cases shall be resolved in favor of coverage.  For a particular
                      product received by a particular user, "normally used" refers to a
                      typical or common use of that class of product, regardless of the status
                      of the particular user or of the way in which the particular user
                      actually uses, or expects or is expected to use, the product.  A product
                      is a consumer product regardless of whether the product has substantial
                      commercial, industrial or non-consumer uses, unless such uses represent
                      the only significant mode of use of the product.
                      
                        "Installation Information" for a User Product means any methods,
                      procedures, authorization keys, or other information required to install
                      and execute modified versions of a covered work in that User Product from
                      a modified version of its Corresponding Source.  The information must
                      suffice to ensure that the continued functioning of the modified object
                      code is in no case prevented or interfered with solely because
                      modification has been made.
                      
                        If you convey an object code work under this section in, or with, or
                      specifically for use in, a User Product, and the conveying occurs as
                      part of a transaction in which the right of possession and use of the
                      User Product is transferred to the recipient in perpetuity or for a
                      fixed term (regardless of how the transaction is characterized), the
                      Corresponding Source conveyed under this section must be accompanied
                      by the Installation Information.  But this requirement does not apply
                      if neither you nor any third party retains the ability to install
                      modified object code on the User Product (for example, the work has
                      been installed in ROM).
                      
                        The requirement to provide Installation Information does not include a
                      requirement to continue to provide support service, warranty, or updates
                      for a work that has been modified or installed by the recipient, or for
                      the User Product in which it has been modified or installed.  Access to a
                      network may be denied when the modification itself materially and
                      adversely affects the operation of the network or violates the rules and
                      protocols for communication across the network.
                      
                        Corresponding Source conveyed, and Installation Information provided,
                      in accord with this section must be in a format that is publicly
                      documented (and with an implementation available to the public in
                      source code form), and must require no special password or key for
                      unpacking, reading or copying.
                      
                        7. Additional Terms.
                      
                        "Additional permissions" are terms that supplement the terms of this
                      License by making exceptions from one or more of its conditions.
                      Additional permissions that are applicable to the entire Program shall
                      be treated as though they were included in this License, to the extent
                      that they are valid under applicable law.  If additional permissions
                      apply only to part of the Program, that part may be used separately
                      under those permissions, but the entire Program remains governed by
                      this License without regard to the additional permissions.
                      
                        When you convey a copy of a covered work, you may at your option
                      remove any additional permissions from that copy, or from any part of
                      it.  (Additional permissions may be written to require their own
                      removal in certain cases when you modify the work.)  You may place
                      additional permissions on material, added by you to a covered work,
                      for which you have or can give appropriate copyright permission.
                      
                        Notwithstanding any other provision of this License, for material you
                      add to a covered work, you may (if authorized by the copyright holders of
                      that material) supplement the terms of this License with terms:
                      
                          a) Disclaiming warranty or limiting liability differently from the
                          terms of sections 15 and 16 of this License; or
                      
                          b) Requiring preservation of specified reasonable legal notices or
                          author attributions in that material or in the Appropriate Legal
                          Notices displayed by works containing it; or
                      
                          c) Prohibiting misrepresentation of the origin of that material, or
                          requiring that modified versions of such material be marked in
                          reasonable ways as different from the original version; or
                      
                          d) Limiting the use for publicity purposes of names of licensors or
                          authors of the material; or
                      
                          e) Declining to grant rights under trademark law for use of some
                          trade names, trademarks, or service marks; or
                      
                          f) Requiring indemnification of licensors and authors of that
                          material by anyone who conveys the material (or modified versions of
                          it) with contractual assumptions of liability to the recipient, for
                          any liability that these contractual assumptions directly impose on
                          those licensors and authors.
                      
                        All other non-permissive additional terms are considered "further
                      restrictions" within the meaning of section 10.  If the Program as you
                      received it, or any part of it, contains a notice stating that it is
                      governed by this License along with a term that is a further
                      restriction, you may remove that term.  If a license document contains
                      a further restriction but permits relicensing or conveying under this
                      License, you may add to a covered work material governed by the terms
                      of that license document, provided that the further restriction does
                      not survive such relicensing or conveying.
                      
                        If you add terms to a covered work in accord with this section, you
                      must place, in the relevant source files, a statement of the
                      additional terms that apply to those files, or a notice indicating
                      where to find the applicable terms.
                      
                        Additional terms, permissive or non-permissive, may be stated in the
                      form of a separately written license, or stated as exceptions;
                      the above requirements apply either way.
                      
                        8. Termination.
                      
                        You may not propagate or modify a covered work except as expressly
                      provided under this License.  Any attempt otherwise to propagate or
                      modify it is void, and will automatically terminate your rights under
                      this License (including any patent licenses granted under the third
                      paragraph of section 11).
                      
                        However, if you cease all violation of this License, then your
                      license from a particular copyright holder is reinstated (a)
                      provisionally, unless and until the copyright holder explicitly and
                      finally terminates your license, and (b) permanently, if the copyright
                      holder fails to notify you of the violation by some reasonable means
                      prior to 60 days after the cessation.
                      
                        Moreover, your license from a particular copyright holder is
                      reinstated permanently if the copyright holder notifies you of the
                      violation by some reasonable means, this is the first time you have
                      received notice of violation of this License (for any work) from that
                      copyright holder, and you cure the violation prior to 30 days after
                      your receipt of the notice.
                      
                        Termination of your rights under this section does not terminate the
                      licenses of parties who have received copies or rights from you under
                      this License.  If your rights have been terminated and not permanently
                      reinstated, you do not qualify to receive new licenses for the same
                      material under section 10.
                      
                        9. Acceptance Not Required for Having Copies.
                      
                        You are not required to accept this License in order to receive or
                      run a copy of the Program.  Ancillary propagation of a covered work
                      occurring solely as a consequence of using peer-to-peer transmission
                      to receive a copy likewise does not require acceptance.  However,
                      nothing other than this License grants you permission to propagate or
                      modify any covered work.  These actions infringe copyright if you do
                      not accept this License.  Therefore, by modifying or propagating a
                      covered work, you indicate your acceptance of this License to do so.
                      
                        10. Automatic Licensing of Downstream Recipients.
                      
                        Each time you convey a covered work, the recipient automatically
                      receives a license from the original licensors, to run, modify and
                      propagate that work, subject to this License.  You are not responsible
                      for enforcing compliance by third parties with this License.
                      
                        An "entity transaction" is a transaction transferring control of an
                      organization, or substantially all assets of one, or subdividing an
                      organization, or merging organizations.  If propagation of a covered
                      work results from an entity transaction, each party to that
                      transaction who receives a copy of the work also receives whatever
                      licenses to the work the party's predecessor in interest had or could
                      give under the previous paragraph, plus a right to possession of the
                      Corresponding Source of the work from the predecessor in interest, if
                      the predecessor has it or can get it with reasonable efforts.
                      
                        You may not impose any further restrictions on the exercise of the
                      rights granted or affirmed under this License.  For example, you may
                      not impose a license fee, royalty, or other charge for exercise of
                      rights granted under this License, and you may not initiate litigation
                      (including a cross-claim or counterclaim in a lawsuit) alleging that
                      any patent claim is infringed by making, using, selling, offering for
                      sale, or importing the Program or any portion of it.
                      
                        11. Patents.
                      
                        A "contributor" is a copyright holder who authorizes use under this
                      License of the Program or a work on which the Program is based.  The
                      work thus licensed is called the contributor's "contributor version".
                      
                        A contributor's "essential patent claims" are all patent claims
                      owned or controlled by the contributor, whether already acquired or
                      hereafter acquired, that would be infringed by some manner, permitted
                      by this License, of making, using, or selling its contributor version,
                      but do not include claims that would be infringed only as a
                      consequence of further modification of the contributor version.  For
                      purposes of this definition, "control" includes the right to grant
                      patent sublicenses in a manner consistent with the requirements of
                      this License.
                      
                        Each contributor grants you a non-exclusive, worldwide, royalty-free
                      patent license under the contributor's essential patent claims, to
                      make, use, sell, offer for sale, import and otherwise run, modify and
                      propagate the contents of its contributor version.
                      
                        In the following three paragraphs, a "patent license" is any express
                      agreement or commitment, however denominated, not to enforce a patent
                      (such as an express permission to practice a patent or covenant not to
                      sue for patent infringement).  To "grant" such a patent license to a
                      party means to make such an agreement or commitment not to enforce a
                      patent against the party.
                      
                        If you convey a covered work, knowingly relying on a patent license,
                      and the Corresponding Source of the work is not available for anyone
                      to copy, free of charge and under the terms of this License, through a
                      publicly available network server or other readily accessible means,
                      then you must either (1) cause the Corresponding Source to be so
                      available, or (2) arrange to deprive yourself of the benefit of the
                      patent license for this particular work, or (3) arrange, in a manner
                      consistent with the requirements of this License, to extend the patent
                      license to downstream recipients.  "Knowingly relying" means you have
                      actual knowledge that, but for the patent license, your conveying the
                      covered work in a country, or your recipient's use of the covered work
                      in a country, would infringe one or more identifiable patents in that
                      country that you have reason to believe are valid.
                      
                        If, pursuant to or in connection with a single transaction or
                      arrangement, you convey, or propagate by procuring conveyance of, a
                      covered work, and grant a patent license to some of the parties
                      receiving the covered work authorizing them to use, propagate, modify
                      or convey a specific copy of the covered work, then the patent license
                      you grant is automatically extended to all recipients of the covered
                      work and works based on it.
                      
                        A patent license is "discriminatory" if it does not include within
                      the scope of its coverage, prohibits the exercise of, or is
                      conditioned on the non-exercise of one or more of the rights that are
                      specifically granted under this License.  You may not convey a covered
                      work if you are a party to an arrangement with a third party that is
                      in the business of distributing software, under which you make payment
                      to the third party based on the extent of your activity of conveying
                      the work, and under which the third party grants, to any of the
                      parties who would receive the covered work from you, a discriminatory
                      patent license (a) in connection with copies of the covered work
                      conveyed by you (or copies made from those copies), or (b) primarily
                      for and in connection with specific products or compilations that
                      contain the covered work, unless you entered into that arrangement,
                      or that patent license was granted, prior to 28 March 2007.
                      
                        Nothing in this License shall be construed as excluding or limiting
                      any implied license or other defenses to infringement that may
                      otherwise be available to you under applicable patent law.
                      
                        12. No Surrender of Others' Freedom.
                      
                        If conditions are imposed on you (whether by court order, agreement or
                      otherwise) that contradict the conditions of this License, they do not
                      excuse you from the conditions of this License.  If you cannot convey a
                      covered work so as to satisfy simultaneously your obligations under this
                      License and any other pertinent obligations, then as a consequence you may
                      not convey it at all.  For example, if you agree to terms that obligate you
                      to collect a royalty for further conveying from those to whom you convey
                      the Program, the only way you could satisfy both those terms and this
                      License would be to refrain entirely from conveying the Program.
                      
                        13. Use with the GNU Affero General Public License.
                      
                        Notwithstanding any other provision of this License, you have
                      permission to link or combine any covered work with a work licensed
                      under version 3 of the GNU Affero General Public License into a single
                      combined work, and to convey the resulting work.  The terms of this
                      License will continue to apply to the part which is the covered work,
                      but the special requirements of the GNU Affero General Public License,
                      section 13, concerning interaction through a network will apply to the
                      combination as such.
                      
                        14. Revised Versions of this License.
                      
                        The Free Software Foundation may publish revised and/or new versions of
                      the GNU General Public License from time to time.  Such new versions will
                      be similar in spirit to the present version, but may differ in detail to
                      address new problems or concerns.
                      
                        Each version is given a distinguishing version number.  If the
                      Program specifies that a certain numbered version of the GNU General
                      Public License "or any later version" applies to it, you have the
                      option of following the terms and conditions either of that numbered
                      version or of any later version published by the Free Software
                      Foundation.  If the Program does not specify a version number of the
                      GNU General Public License, you may choose any version ever published
                      by the Free Software Foundation.
                      
                        If the Program specifies that a proxy can decide which future
                      versions of the GNU General Public License can be used, that proxy's
                      public statement of acceptance of a version permanently authorizes you
                      to choose that version for the Program.
                      
                        Later license versions may give you additional or different
                      permissions.  However, no additional obligations are imposed on any
                      author or copyright holder as a result of your choosing to follow a
                      later version.
                      
                        15. Disclaimer of Warranty.
                      
                        THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
                      APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
                      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
                      OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
                      THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
                      PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
                      IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
                      ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
                      
                        16. Limitation of Liability.
                      
                        IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                      WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
                      THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
                      GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
                      USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
                      DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
                      PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
                      EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
                      SUCH DAMAGES.
                      
                        17. Interpretation of Sections 15 and 16.
                      
                        If the disclaimer of warranty and limitation of liability provided
                      above cannot be given local legal effect according to their terms,
                      reviewing courts shall apply local law that most closely approximates
                      an absolute waiver of all civil liability in connection with the
                      Program, unless a warranty or assumption of liability accompanies a
                      copy of the Program in return for a fee.
                      
                                           END OF TERMS AND CONDITIONS
                      
                                  How to Apply These Terms to Your New Programs
                      
                        If you develop a new program, and you want it to be of the greatest
                      possible use to the public, the best way to achieve this is to make it
                      free software which everyone can redistribute and change under these terms.
                      
                        To do so, attach the following notices to the program.  It is safest
                      to attach them to the start of each source file to most effectively
                      state the exclusion of warranty; and each file should have at least
                      the "copyright" line and a pointer to where the full notice is found.
                      
                          <one line to give the program's name and a brief idea of what it does.>
                          Copyright (C) <year>  <name of author>
                      
                          This program is free software: you can redistribute it and/or modify
                          it under the terms of the GNU General Public License as published by
                          the Free Software Foundation, either version 3 of the License, or
                          (at your option) any later version.
                      
                          This program is distributed in the hope that it will be useful,
                          but WITHOUT ANY WARRANTY; without even the implied warranty of
                          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                          GNU General Public License for more details.
                      
                          You should have received a copy of the GNU General Public License
                          along with this program.  If not, see <http://www.gnu.org/licenses/>.
                      
                      Also add information on how to contact you by electronic and paper mail.
                      
                        If the program does terminal interaction, make it output a short
                      notice like this when it starts in an interactive mode:
                      
                          <program>  Copyright (C) <year>  <name of author>
                          This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
                          This is free software, and you are welcome to redistribute it
                          under certain conditions; type `show c' for details.
                      
                      The hypothetical commands `show w' and `show c' should show the appropriate
                      parts of the General Public License.  Of course, your program's commands
                      might be different; for a GUI interface, you would use an "about box".
                      
                        You should also get your employer (if you work as a programmer) or school,
                      if any, to sign a "copyright disclaimer" for the program, if necessary.
                      For more information on this, and how to apply and follow the GNU GPL, see
                      <http://www.gnu.org/licenses/>.
                      
                        The GNU General Public License does not permit incorporating your program
                      into proprietary programs.  If your program is a subroutine library, you
                      may consider it more useful to permit linking proprietary applications with
                      the library.  If this is what you want to do, use the GNU Lesser General
                      Public License instead of this License.  But first, please read
                      <http://www.gnu.org/philosophy/why-not-lgpl.html>.
                      
                      */

                      File 6 of 8: X7DAODiscountAuthority
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.15;
                      
                      /*
                      
                       /$$   /$$ /$$$$$$$$       /$$$$$$$$ /$$
                      | $$  / $$|_____ $$/      | $$_____/|__/
                      |  $$/ $$/     /$$/       | $$       /$$ /$$$$$$$   /$$$$$$  /$$$$$$$   /$$$$$$$  /$$$$$$
                       \  $$$$/     /$$/        | $$$$$   | $$| $$__  $$ |____  $$| $$__  $$ /$$_____/ /$$__  $$
                        >$$  $$    /$$/         | $$__/   | $$| $$  \ $$  /$$$$$$$| $$  \ $$| $$      | $$$$$$$$
                       /$$/\  $$  /$$/          | $$      | $$| $$  | $$ /$$__  $$| $$  | $$| $$      | $$_____/
                      | $$  \ $$ /$$/           | $$      | $$| $$  | $$|  $$$$$$$| $$  | $$|  $$$$$$$|  $$$$$$$
                      |__/  |__/|__/            |__/      |__/|__/  |__/ \_______/|__/  |__/ \_______/ \_______/
                      
                      Contract: Smart Contract for X7DAO fee discounts
                      
                      This contract will NOT be renounced.
                      
                      The following are the only functions that can be called on the contract that affect the contract:
                      
                          function setEcosystemMaxiNFT(address tokenAddress) external onlyOwner {
                              require(address(ecoMaxiNFT) != tokenAddress);
                              address oldTokenAddress = address(ecoMaxiNFT);
                              ecoMaxiNFT = IERC721(tokenAddress);
                              emit EcosystemMaxiNFTSet(oldTokenAddress, tokenAddress);
                          }
                      
                          function setLiquidityMaxiNFT(address tokenAddress) external onlyOwner {
                              require(address(liqMaxiNFT) != tokenAddress);
                              address oldTokenAddress = address(liqMaxiNFT);
                              liqMaxiNFT = IERC721(tokenAddress);
                              emit LiquidityMaxiNFTSet(oldTokenAddress, tokenAddress);
                          }
                      
                      These functions will be passed to DAO governance once the ecosystem stabilizes.
                      
                      */
                      
                      abstract contract Ownable {
                          address private _owner;
                      
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                      
                          constructor(address owner_) {
                              _transferOwnership(owner_);
                          }
                      
                          modifier onlyOwner() {
                              _checkOwner();
                              _;
                          }
                      
                          function owner() public view virtual returns (address) {
                              return _owner;
                          }
                      
                          function _checkOwner() internal view virtual {
                              require(owner() == msg.sender, "Ownable: caller is not the owner");
                          }
                      
                          function renounceOwnership() public virtual onlyOwner {
                              _transferOwnership(address(0));
                          }
                      
                          function transferOwnership(address newOwner) public virtual onlyOwner {
                              require(newOwner != address(0), "Ownable: new owner is the zero address");
                              _transferOwnership(newOwner);
                          }
                      
                          function _transferOwnership(address newOwner) internal virtual {
                              address oldOwner = _owner;
                              _owner = newOwner;
                              emit OwnershipTransferred(oldOwner, newOwner);
                          }
                      }
                      
                      interface IERC721 {
                          function balanceOf(address owner) external view returns (uint256);
                      }
                      
                      interface IDiscountAuthority {
                          function discountRatio(address) external view returns (uint256, uint256);
                      }
                      
                      contract X7DAODiscountAuthority is Ownable {
                      
                          IERC721 public ecoMaxiNFT;
                          IERC721 public liqMaxiNFT;
                      
                          event EcosystemMaxiNFTSet(address indexed oldTokenAddress, address indexed newTokenAddress);
                          event LiquidityMaxiNFTSet(address indexed oldTokenAddress, address indexed newTokenAddress);
                      
                          constructor() Ownable(address(0x7000a09c425ABf5173FF458dF1370C25d1C58105)) {}
                      
                          function setEcosystemMaxiNFT(address tokenAddress) external onlyOwner {
                              require(address(ecoMaxiNFT) != tokenAddress);
                              address oldTokenAddress = address(ecoMaxiNFT);
                              ecoMaxiNFT = IERC721(tokenAddress);
                              emit EcosystemMaxiNFTSet(oldTokenAddress, tokenAddress);
                          }
                      
                          function setLiquidityMaxiNFT(address tokenAddress) external onlyOwner {
                              require(address(liqMaxiNFT) != tokenAddress);
                              address oldTokenAddress = address(liqMaxiNFT);
                              liqMaxiNFT = IERC721(tokenAddress);
                              emit LiquidityMaxiNFTSet(oldTokenAddress, tokenAddress);
                          }
                      
                          function discountRatio(address swapper) external view returns (uint256 numerator, uint256 denominator) {
                              numerator = 1;
                              denominator = 1;
                      
                              if (liqMaxiNFT.balanceOf(swapper) > 0) {
                                  // 15% discount
                                  numerator = 85;
                                  denominator = 100;
                              } else if (ecoMaxiNFT.balanceOf(swapper) > 0) {
                                  // 10% discount
                                  numerator = 90;
                                  denominator = 100;
                              }
                          }
                      }

                      File 7 of 8: X7LiquidityMaxi
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.15;
                      
                      /*
                      
                       /$$   /$$ /$$$$$$$$       /$$$$$$$$ /$$
                      | $$  / $$|_____ $$/      | $$_____/|__/
                      |  $$/ $$/     /$$/       | $$       /$$ /$$$$$$$   /$$$$$$  /$$$$$$$   /$$$$$$$  /$$$$$$
                       \  $$$$/     /$$/        | $$$$$   | $$| $$__  $$ |____  $$| $$__  $$ /$$_____/ /$$__  $$
                        >$$  $$    /$$/         | $$__/   | $$| $$  \ $$  /$$$$$$$| $$  \ $$| $$      | $$$$$$$$
                       /$$/\  $$  /$$/          | $$      | $$| $$  | $$ /$$__  $$| $$  | $$| $$      | $$_____/
                      | $$  \ $$ /$$/           | $$      | $$| $$  | $$|  $$$$$$$| $$  | $$|  $$$$$$$|  $$$$$$$
                      |__/  |__/|__/            |__/      |__/|__/  |__/ \_______/|__/  |__/ \_______/ \_______/
                      
                      Contract: ERC-721 Token "X7 Liquidity Maxi" NFT
                      
                      A utility NFT offering fee discounts across the X7 ecosystem.
                      
                      This contract will NOT be renounced.
                      
                      The following are the only functions that can be called on the contract that affect the contract:
                      
                          function setMintFeeDestination(address mintFeeDestination_) external onlyOwner {
                              require(mintFeeDestination != mintFeeDestination_);
                              address oldMintFeeDestination = mintFeeDestination;
                              mintFeeDestination = mintFeeDestination_;
                              emit MintFeeDestinationSet(oldMintFeeDestination, mintFeeDestination_);
                          }
                      
                          function setBaseURI(string memory baseURI_) external onlyOwner {
                              require(keccak256(abi.encodePacked(_internalBaseURI)) != keccak256(abi.encodePacked(baseURI_)));
                              string memory oldBaseURI = _internalBaseURI;
                              _internalBaseURI = baseURI_;
                              emit BaseURISet(oldBaseURI, baseURI_);
                          }
                      
                          function setMintPrice(uint256 mintPrice_) external onlyOwner {
                              require(mintPrice_ > mintPrice);
                              uint256 oldPrice = mintPrice;
                              mintPrice = mintPrice_;
                              emit MintPriceSet(oldPrice, mintPrice_);
                          }
                      
                      These functions will be passed to DAO governance once the ecosystem stabilizes.
                      
                      */
                      
                      abstract contract Ownable {
                          address private _owner;
                      
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                      
                          constructor(address owner_) {
                              _transferOwnership(owner_);
                          }
                      
                          modifier onlyOwner() {
                              _checkOwner();
                              _;
                          }
                      
                          function owner() public view virtual returns (address) {
                              return _owner;
                          }
                      
                          function _checkOwner() internal view virtual {
                              require(owner() == msg.sender, "Ownable: caller is not the owner");
                          }
                      
                          function renounceOwnership() public virtual onlyOwner {
                              _transferOwnership(address(0));
                          }
                      
                          function transferOwnership(address newOwner) public virtual onlyOwner {
                              require(newOwner != address(0), "Ownable: new owner is the zero address");
                              _transferOwnership(newOwner);
                          }
                      
                          function _transferOwnership(address newOwner) internal virtual {
                              address oldOwner = _owner;
                              _owner = newOwner;
                              emit OwnershipTransferred(oldOwner, newOwner);
                          }
                      }
                      
                      /**
                       * @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);
                      }
                      
                      /**
                       * @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);
                      }
                      
                      /**
                       * @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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
                           *
                           * 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);
                      }
                      
                      /**
                       * @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);
                      }
                      
                      /**
                       * @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://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 functionCall(target, data, "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");
                              require(isContract(target), "Address: call to non-contract");
                      
                              (bool success, bytes memory returndata) = target.call{value: value}(data);
                              return verifyCallResult(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) {
                              require(isContract(target), "Address: static call to non-contract");
                      
                              (bool success, bytes memory returndata) = target.staticcall(data);
                              return verifyCallResult(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) {
                              require(isContract(target), "Address: delegate call to non-contract");
                      
                              (bool success, bytes memory returndata) = target.delegatecall(data);
                              return verifyCallResult(success, returndata, errorMessage);
                          }
                      
                          /**
                           * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                           * revert reason 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 {
                                  // 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);
                                  }
                              }
                          }
                      }
                      
                      /**
                       * @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;
                          }
                      }
                      
                      /**
                       * @dev String operations.
                       */
                      library Strings {
                          bytes16 private constant _HEX_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) {
                              // Inspired by OraclizeAPI's implementation - MIT licence
                              // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                      
                              if (value == 0) {
                                  return "0";
                              }
                              uint256 temp = value;
                              uint256 digits;
                              while (temp != 0) {
                                  digits++;
                                  temp /= 10;
                              }
                              bytes memory buffer = new bytes(digits);
                              while (value != 0) {
                                  digits -= 1;
                                  buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                                  value /= 10;
                              }
                              return string(buffer);
                          }
                      
                          /**
                           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                           */
                          function toHexString(uint256 value) internal pure returns (string memory) {
                              if (value == 0) {
                                  return "0x00";
                              }
                              uint256 temp = value;
                              uint256 length = 0;
                              while (temp != 0) {
                                  length++;
                                  temp >>= 8;
                              }
                              return toHexString(value, length);
                          }
                      
                          /**
                           * @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] = _HEX_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 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;
                          }
                      }
                      
                      /**
                       * @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;
                      
                          // 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;
                      
                          /**
                           * @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 = _owners[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;
                          }
                      
                          /**
                           * @dev See {IERC721Metadata-tokenURI}.
                           */
                          function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
                              _requireMinted(tokenId);
                      
                              string memory baseURI = _baseURI();
                              return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
                          }
                      
                          /**
                           * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
                           * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
                           * by default, can be overridden in child contracts.
                           */
                          function _baseURI() internal view virtual returns (string memory) {
                              return "";
                          }
                      
                          /**
                           * @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 nor 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 nor 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 nor 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 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 _owners[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);
                      
                              _balances[to] += 1;
                              _owners[tokenId] = to;
                      
                              emit Transfer(address(0), to, tokenId);
                      
                              _afterTokenTransfer(address(0), to, tokenId);
                          }
                      
                          /**
                           * @dev Destroys `tokenId`.
                           * The approval is cleared when the token is burned.
                           *
                           * Requirements:
                           *
                           * - `tokenId` must exist.
                           *
                           * Emits a {Transfer} event.
                           */
                          function _burn(uint256 tokenId) internal virtual {
                              address owner = ERC721.ownerOf(tokenId);
                      
                              _beforeTokenTransfer(owner, address(0), tokenId);
                      
                              // Clear approvals
                              _approve(address(0), tokenId);
                      
                              _balances[owner] -= 1;
                              delete _owners[tokenId];
                      
                              emit Transfer(owner, address(0), tokenId);
                      
                              _afterTokenTransfer(owner, address(0), tokenId);
                          }
                      
                          /**
                           * @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);
                      
                              // Clear approvals from the previous owner
                              _approve(address(0), tokenId);
                      
                              _balances[from] -= 1;
                              _balances[to] += 1;
                              _owners[tokenId] = to;
                      
                              emit Transfer(from, to, tokenId);
                      
                              _afterTokenTransfer(from, to, tokenId);
                          }
                      
                          /**
                           * @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.
                           *
                           * Calling conditions:
                           *
                           * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
                           * transferred to `to`.
                           * - When `from` is zero, `tokenId` will be minted for `to`.
                           * - When `to` is zero, ``from``'s `tokenId` 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 tokenId
                          ) 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.
                           * - `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 tokenId
                          ) internal virtual {}
                      }
                      
                      /**
                       * @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);
                      }
                      
                      /**
                       * @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 Hook that is called before any token transfer. This includes minting
                           * and burning.
                           *
                           * Calling conditions:
                           *
                           * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
                           * transferred to `to`.
                           * - When `from` is zero, `tokenId` will be minted for `to`.
                           * - When `to` is zero, ``from``'s `tokenId` will be burned.
                           * - `from` cannot be the zero address.
                           * - `to` cannot be the zero address.
                           *
                           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                           */
                          function _beforeTokenTransfer(
                              address from,
                              address to,
                              uint256 tokenId
                          ) internal virtual override {
                              super._beforeTokenTransfer(from, to, tokenId);
                      
                              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();
                          }
                      }
                      
                      /**
                       * @dev Implementation of the {IERC721Receiver} interface.
                       *
                       * Accepts all token transfers.
                       * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
                       */
                      contract ERC721Holder is IERC721Receiver {
                          /**
                           * @dev See {IERC721Receiver-onERC721Received}.
                           *
                           * Always returns `IERC721Receiver.onERC721Received.selector`.
                           */
                          function onERC721Received(
                              address,
                              address,
                              uint256,
                              bytes memory
                          ) public virtual override returns (bytes4) {
                              return this.onERC721Received.selector;
                          }
                      }
                      
                      interface IX7Migration {
                          function inMigration(address) external view returns (bool);
                      }
                      
                      contract X7LiquidityMaxi is ERC721Enumerable, ERC721Holder, Ownable {
                      
                          address payable public mintFeeDestination;
                          address payable public treasury;
                          string public _internalBaseURI;
                      
                          uint256 public maxSupply = 250;
                          uint256 public mintPrice = 5 * 10**17;
                          uint256 public maxMintsPerTransaction = 4;
                      
                          bool public mintingOpen;
                          bool public whitelistComplete;
                      
                          bool public whitelistActive = true;
                          IX7Migration public whitelistAuthority;
                      
                          event MintingOpen();
                          event MintFeeDestinationSet(address indexed oldDestination, address indexed newDestination);
                          event MintPriceSet(uint256 oldPrice, uint256 newPrice);
                          event BaseURISet(string oldURI, string newURI);
                          event WhitelistActivitySet(bool whitelistActive);
                          event WhitelistAuthoritySet(address indexed oldWhitelistAuthority, address indexed newWhitelistAuthority);
                      
                          constructor(address mintFeeDestination_, address treasury_) ERC721("X7 Liquidity Maxi", "X7LMAXI") Ownable(0x7000a09c425ABf5173FF458dF1370C25d1C58105) {
                              mintFeeDestination = payable(mintFeeDestination_);
                              treasury = payable(treasury_);
                          }
                      
                          function whitelist(address holder) external view returns (bool) {
                              return whitelistAuthority.inMigration(holder);
                          }
                      
                          function setMintFeeDestination(address mintFeeDestination_) external onlyOwner {
                              require(mintFeeDestination != mintFeeDestination_);
                              address oldMintFeeDestination = mintFeeDestination;
                              mintFeeDestination = payable(mintFeeDestination_);
                              emit MintFeeDestinationSet(oldMintFeeDestination, mintFeeDestination_);
                          }
                      
                          function setBaseURI(string memory baseURI_) external onlyOwner {
                              require(keccak256(abi.encodePacked(_internalBaseURI)) != keccak256(abi.encodePacked(baseURI_)));
                              string memory oldBaseURI = _internalBaseURI;
                              _internalBaseURI = baseURI_;
                              emit BaseURISet(oldBaseURI, baseURI_);
                          }
                      
                          function setMintPrice(uint256 mintPrice_) external onlyOwner {
                              require(mintPrice_ > mintPrice);
                              uint256 oldPrice = mintPrice;
                              mintPrice = mintPrice_;
                              emit MintPriceSet(oldPrice, mintPrice_);
                          }
                      
                          function setWhitelist(bool isActive) external onlyOwner {
                              require(!whitelistComplete);
                              require(whitelistActive != isActive);
                              whitelistActive = isActive;
                              emit WhitelistActivitySet(isActive);
                          }
                      
                          function setWhitelistComplete() external onlyOwner {
                              require(!whitelistComplete);
                              whitelistComplete = true;
                              whitelistActive = false;
                          }
                      
                          function setWhitelistAuthority(address whitelistAuthority_) external onlyOwner {
                              require(address(whitelistAuthority) != whitelistAuthority_);
                              address oldWhitelistAuthority = address(whitelistAuthority);
                              whitelistAuthority = IX7Migration(whitelistAuthority_);
                              emit WhitelistAuthoritySet(oldWhitelistAuthority, whitelistAuthority_);
                          }
                      
                          function openMinting() external onlyOwner {
                              require(!mintingOpen);
                              require(mintFeeDestination != address(0));
                              mintingOpen = true;
                              emit MintingOpen();
                          }
                      
                          function mint() external payable {
                              _mintMany(1);
                          }
                      
                          function mintMany(uint256 numMints) external payable {
                              _mintMany(numMints);
                          }
                      
                          function _mintMany(uint256 numMints) internal {
                              require(mintingOpen);
                              require(!whitelistActive || whitelistAuthority.inMigration(msg.sender));
                              require(totalSupply() + numMints <= maxSupply);
                              require(numMints > 0 && numMints <= maxMintsPerTransaction);
                              require(msg.value == numMints * mintPrice);
                      
                              uint256 treasuryFee = msg.value * 10 / 100;
                      
                              bool success;
                      
                              (success,) = treasury.call{value: treasuryFee}("");
                              require(success);
                      
                              (success,) = mintFeeDestination.call{value: msg.value - treasuryFee}("");
                              require(success);
                      
                              uint256 nextTokenId = ERC721Enumerable.totalSupply();
                      
                              for (uint i=0; i < numMints; i++) {
                                  super._mint(msg.sender, nextTokenId + i);
                              }
                          }
                      
                          function _baseURI() internal view override returns (string memory) {
                              return _internalBaseURI;
                          }
                      }

                      File 8 of 8: X7EcosystemMaxi
                      // SPDX-License-Identifier: MIT
                      pragma solidity ^0.8.15;
                      
                      /*
                      
                       /$$   /$$ /$$$$$$$$       /$$$$$$$$ /$$
                      | $$  / $$|_____ $$/      | $$_____/|__/
                      |  $$/ $$/     /$$/       | $$       /$$ /$$$$$$$   /$$$$$$  /$$$$$$$   /$$$$$$$  /$$$$$$
                       \  $$$$/     /$$/        | $$$$$   | $$| $$__  $$ |____  $$| $$__  $$ /$$_____/ /$$__  $$
                        >$$  $$    /$$/         | $$__/   | $$| $$  \ $$  /$$$$$$$| $$  \ $$| $$      | $$$$$$$$
                       /$$/\  $$  /$$/          | $$      | $$| $$  | $$ /$$__  $$| $$  | $$| $$      | $$_____/
                      | $$  \ $$ /$$/           | $$      | $$| $$  | $$|  $$$$$$$| $$  | $$|  $$$$$$$|  $$$$$$$
                      |__/  |__/|__/            |__/      |__/|__/  |__/ \_______/|__/  |__/ \_______/ \_______/
                      
                      Contract: ERC-721 Token "X7 Ecosystem Maxi" NFT
                      
                      A utility NFT offering fee discounts across the X7 ecosystem.
                      
                      This contract will NOT be renounced.
                      
                      The following are the only functions that can be called on the contract that affect the contract:
                      
                          function setMintFeeDestination(address mintFeeDestination_) external onlyOwner {
                              require(mintFeeDestination != mintFeeDestination_);
                              address oldMintFeeDestination = mintFeeDestination;
                              mintFeeDestination = mintFeeDestination_;
                              emit MintFeeDestinationSet(oldMintFeeDestination, mintFeeDestination_);
                          }
                      
                          function setBaseURI(string memory baseURI_) external onlyOwner {
                              require(keccak256(abi.encodePacked(_internalBaseURI)) != keccak256(abi.encodePacked(baseURI_)));
                              string memory oldBaseURI = _internalBaseURI;
                              _internalBaseURI = baseURI_;
                              emit BaseURISet(oldBaseURI, baseURI_);
                          }
                      
                          function setMintPrice(uint256 mintPrice_) external onlyOwner {
                              require(mintPrice_ > mintPrice);
                              uint256 oldPrice = mintPrice;
                              mintPrice = mintPrice_;
                              emit MintPriceSet(oldPrice, mintPrice_);
                          }
                      
                      These functions will be passed to DAO governance once the ecosystem stabilizes.
                      
                      */
                      
                      abstract contract Ownable {
                          address private _owner;
                      
                          event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                      
                          constructor(address owner_) {
                              _transferOwnership(owner_);
                          }
                      
                          modifier onlyOwner() {
                              _checkOwner();
                              _;
                          }
                      
                          function owner() public view virtual returns (address) {
                              return _owner;
                          }
                      
                          function _checkOwner() internal view virtual {
                              require(owner() == msg.sender, "Ownable: caller is not the owner");
                          }
                      
                          function renounceOwnership() public virtual onlyOwner {
                              _transferOwnership(address(0));
                          }
                      
                          function transferOwnership(address newOwner) public virtual onlyOwner {
                              require(newOwner != address(0), "Ownable: new owner is the zero address");
                              _transferOwnership(newOwner);
                          }
                      
                          function _transferOwnership(address newOwner) internal virtual {
                              address oldOwner = _owner;
                              _owner = newOwner;
                              emit OwnershipTransferred(oldOwner, newOwner);
                          }
                      }
                      
                      /**
                       * @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);
                      }
                      
                      /**
                       * @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);
                      }
                      
                      /**
                       * @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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
                           *
                           * 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);
                      }
                      
                      /**
                       * @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);
                      }
                      
                      /**
                       * @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://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 functionCall(target, data, "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");
                              require(isContract(target), "Address: call to non-contract");
                      
                              (bool success, bytes memory returndata) = target.call{value: value}(data);
                              return verifyCallResult(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) {
                              require(isContract(target), "Address: static call to non-contract");
                      
                              (bool success, bytes memory returndata) = target.staticcall(data);
                              return verifyCallResult(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) {
                              require(isContract(target), "Address: delegate call to non-contract");
                      
                              (bool success, bytes memory returndata) = target.delegatecall(data);
                              return verifyCallResult(success, returndata, errorMessage);
                          }
                      
                          /**
                           * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
                           * revert reason 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 {
                                  // 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);
                                  }
                              }
                          }
                      }
                      
                      /**
                       * @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;
                          }
                      }
                      
                      /**
                       * @dev String operations.
                       */
                      library Strings {
                          bytes16 private constant _HEX_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) {
                              // Inspired by OraclizeAPI's implementation - MIT licence
                              // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
                      
                              if (value == 0) {
                                  return "0";
                              }
                              uint256 temp = value;
                              uint256 digits;
                              while (temp != 0) {
                                  digits++;
                                  temp /= 10;
                              }
                              bytes memory buffer = new bytes(digits);
                              while (value != 0) {
                                  digits -= 1;
                                  buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
                                  value /= 10;
                              }
                              return string(buffer);
                          }
                      
                          /**
                           * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                           */
                          function toHexString(uint256 value) internal pure returns (string memory) {
                              if (value == 0) {
                                  return "0x00";
                              }
                              uint256 temp = value;
                              uint256 length = 0;
                              while (temp != 0) {
                                  length++;
                                  temp >>= 8;
                              }
                              return toHexString(value, length);
                          }
                      
                          /**
                           * @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] = _HEX_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 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;
                          }
                      }
                      
                      /**
                       * @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;
                      
                          // 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;
                      
                          /**
                           * @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 = _owners[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;
                          }
                      
                          /**
                           * @dev See {IERC721Metadata-tokenURI}.
                           */
                          function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
                              _requireMinted(tokenId);
                      
                              string memory baseURI = _baseURI();
                              return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
                          }
                      
                          /**
                           * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
                           * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
                           * by default, can be overridden in child contracts.
                           */
                          function _baseURI() internal view virtual returns (string memory) {
                              return "";
                          }
                      
                          /**
                           * @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 nor 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 nor 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 nor 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 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 _owners[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);
                      
                              _balances[to] += 1;
                              _owners[tokenId] = to;
                      
                              emit Transfer(address(0), to, tokenId);
                      
                              _afterTokenTransfer(address(0), to, tokenId);
                          }
                      
                          /**
                           * @dev Destroys `tokenId`.
                           * The approval is cleared when the token is burned.
                           *
                           * Requirements:
                           *
                           * - `tokenId` must exist.
                           *
                           * Emits a {Transfer} event.
                           */
                          function _burn(uint256 tokenId) internal virtual {
                              address owner = ERC721.ownerOf(tokenId);
                      
                              _beforeTokenTransfer(owner, address(0), tokenId);
                      
                              // Clear approvals
                              _approve(address(0), tokenId);
                      
                              _balances[owner] -= 1;
                              delete _owners[tokenId];
                      
                              emit Transfer(owner, address(0), tokenId);
                      
                              _afterTokenTransfer(owner, address(0), tokenId);
                          }
                      
                          /**
                           * @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);
                      
                              // Clear approvals from the previous owner
                              _approve(address(0), tokenId);
                      
                              _balances[from] -= 1;
                              _balances[to] += 1;
                              _owners[tokenId] = to;
                      
                              emit Transfer(from, to, tokenId);
                      
                              _afterTokenTransfer(from, to, tokenId);
                          }
                      
                          /**
                           * @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.
                           *
                           * Calling conditions:
                           *
                           * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
                           * transferred to `to`.
                           * - When `from` is zero, `tokenId` will be minted for `to`.
                           * - When `to` is zero, ``from``'s `tokenId` 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 tokenId
                          ) 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.
                           * - `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 tokenId
                          ) internal virtual {}
                      }
                      
                      /**
                       * @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);
                      }
                      
                      /**
                       * @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 Hook that is called before any token transfer. This includes minting
                           * and burning.
                           *
                           * Calling conditions:
                           *
                           * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
                           * transferred to `to`.
                           * - When `from` is zero, `tokenId` will be minted for `to`.
                           * - When `to` is zero, ``from``'s `tokenId` will be burned.
                           * - `from` cannot be the zero address.
                           * - `to` cannot be the zero address.
                           *
                           * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                           */
                          function _beforeTokenTransfer(
                              address from,
                              address to,
                              uint256 tokenId
                          ) internal virtual override {
                              super._beforeTokenTransfer(from, to, tokenId);
                      
                              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();
                          }
                      }
                      
                      /**
                       * @dev Implementation of the {IERC721Receiver} interface.
                       *
                       * Accepts all token transfers.
                       * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
                       */
                      contract ERC721Holder is IERC721Receiver {
                          /**
                           * @dev See {IERC721Receiver-onERC721Received}.
                           *
                           * Always returns `IERC721Receiver.onERC721Received.selector`.
                           */
                          function onERC721Received(
                              address,
                              address,
                              uint256,
                              bytes memory
                          ) public virtual override returns (bytes4) {
                              return this.onERC721Received.selector;
                          }
                      }
                      
                      interface IX7Migration {
                          function inMigration(address) external view returns (bool);
                      }
                      
                      contract X7EcosystemMaxi is ERC721Enumerable, ERC721Holder, Ownable {
                      
                          address payable public mintFeeDestination;
                          address payable public treasury;
                          string public _internalBaseURI;
                      
                          uint256 public maxSupply = 500;
                          uint256 public mintPrice = 10**17;
                          uint256 public maxMintsPerTransaction = 5;
                      
                          bool public mintingOpen;
                          bool public whitelistComplete;
                      
                          bool public whitelistActive = true;
                          IX7Migration public whitelistAuthority;
                      
                          event MintingOpen();
                          event MintFeeDestinationSet(address indexed oldDestination, address indexed newDestination);
                          event MintPriceSet(uint256 oldPrice, uint256 newPrice);
                          event BaseURISet(string oldURI, string newURI);
                          event WhitelistActivitySet(bool whitelistActive);
                          event WhitelistAuthoritySet(address indexed oldWhitelistAuthority, address indexed newWhitelistAuthority);
                      
                          constructor(address mintFeeDestination_, address treasury_) ERC721("X7 Ecosystem Maxi", "X7EMAXI") Ownable(0x7000a09c425ABf5173FF458dF1370C25d1C58105) {
                              mintFeeDestination = payable(mintFeeDestination_);
                              treasury = payable(treasury_);
                          }
                      
                          function whitelist(address holder) external view returns (bool) {
                              return whitelistAuthority.inMigration(holder);
                          }
                      
                          function setMintFeeDestination(address mintFeeDestination_) external onlyOwner {
                              require(mintFeeDestination != mintFeeDestination_);
                              address oldMintFeeDestination = mintFeeDestination;
                              mintFeeDestination = payable(mintFeeDestination_);
                              emit MintFeeDestinationSet(oldMintFeeDestination, mintFeeDestination_);
                          }
                      
                          function setBaseURI(string memory baseURI_) external onlyOwner {
                              require(keccak256(abi.encodePacked(_internalBaseURI)) != keccak256(abi.encodePacked(baseURI_)));
                              string memory oldBaseURI = _internalBaseURI;
                              _internalBaseURI = baseURI_;
                              emit BaseURISet(oldBaseURI, baseURI_);
                          }
                      
                          function setMintPrice(uint256 mintPrice_) external onlyOwner {
                              require(mintPrice_ > mintPrice);
                              uint256 oldPrice = mintPrice;
                              mintPrice = mintPrice_;
                              emit MintPriceSet(oldPrice, mintPrice_);
                          }
                      
                          function setWhitelist(bool isActive) external onlyOwner {
                              require(!whitelistComplete);
                              require(whitelistActive != isActive);
                              whitelistActive = isActive;
                              emit WhitelistActivitySet(isActive);
                          }
                      
                          function setWhitelistComplete() external onlyOwner {
                              require(!whitelistComplete);
                              whitelistComplete = true;
                              whitelistActive = false;
                          }
                      
                          function setWhitelistAuthority(address whitelistAuthority_) external onlyOwner {
                              require(address(whitelistAuthority) != whitelistAuthority_);
                              address oldWhitelistAuthority = address(whitelistAuthority);
                              whitelistAuthority = IX7Migration(whitelistAuthority_);
                              emit WhitelistAuthoritySet(oldWhitelistAuthority, whitelistAuthority_);
                          }
                      
                          function openMinting() external onlyOwner {
                              require(!mintingOpen);
                              require(mintFeeDestination != address(0));
                              mintingOpen = true;
                              emit MintingOpen();
                          }
                      
                          function mint() external payable {
                              _mintMany(1);
                          }
                      
                          function mintMany(uint256 numMints) external payable {
                              _mintMany(numMints);
                          }
                      
                          function _mintMany(uint256 numMints) internal {
                              require(mintingOpen);
                              require(!whitelistActive || whitelistAuthority.inMigration(msg.sender));
                              require(totalSupply() + numMints <= maxSupply);
                              require(numMints > 0 && numMints <= maxMintsPerTransaction);
                              require(msg.value == numMints * mintPrice);
                      
                              uint256 treasuryFee = msg.value * 10 / 100;
                      
                              bool success;
                      
                              (success,) = treasury.call{value: treasuryFee}("");
                              require(success);
                      
                              (success,) = mintFeeDestination.call{value: msg.value - treasuryFee}("");
                              require(success);
                      
                              uint256 nextTokenId = ERC721Enumerable.totalSupply();
                      
                              for (uint i=0; i < numMints; i++) {
                                  super._mint(msg.sender, nextTokenId + i);
                              }
                          }
                      
                          function _baseURI() internal view override returns (string memory) {
                              return _internalBaseURI;
                          }
                      }