// File: src/Thundercock.sol



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

import {Owned} from "solmate/auth/Owned.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";
import {WETH} from "solmate/tokens/WETH.sol";
import {Index} from "./Index.sol";
import {LightningBolt} from "./LightningBolt.sol";

import {IUniswapV2Router} from "./interfaces/IUniswapV2Router.sol";
import {ISwapRouter} from "@uniswap/v3-periphery/interfaces/ISwapRouter.sol";

//
//       .____.
//    xuu$``$$$uuu.
//  . $``$  $$$`$$$
// dP*$  $  $$$ $$$
// ?k $  $  $$$ $$$
//  $ $  $  $$$ $$$
//  ":$  $  $$$ $$$
//   N$  $  $$$ $$$
//   $$  $  $$$ $$$
//    $  $  $$$ $$$
//    $  $  $$$ $$$
//    $  $  $$$ $$$
//    $  $  $$$ $$$
//    $  $  $$$ $$$
//    $$#$  $$$ $$$
//    $$'$  $$$ $$$±
//    $$`R  $$$ $$$
//    $$$&  $$$ $$$
//    $#*$  $$$ $$$
//    $  $  $$$ @$$
//    $  $  $$$ $$$
//    $  $  $$$ $$$
//    $  $  $B$ $$&.
//    $  $  $D$ $$$$$muL.
//    $  $  $Q$ $$$$$  `"**mu..
//    $  $  $R$ $$$$$    k  `$$*t
//    $  @  $$$ $$$$$    k   $$!4
//    $ x$uu@B8u$NB@$uuuu6...$$X?
//    $ $(`RF`$`````R$ $$5`"""#"R
//    $ $" M$ $     $$ $$$      ?
//    $ $  ?$ $     T$ $$$      $
//    $ $F H$ $     M$ $$K      $  ..
//    $ $L $$ $     $$ $$R.     "d$$$$Ns.
//    $ $~ $$ $     N$ $$X      ."    "%2h
//    $ 4k f  $     *$ $$&      R       "iN
//    $ $$ %uz!     tuuR$$:     Buu      ?`:
//    $ $F          $??$8B      | '*Ned*$~L$
//    $ $k          $'@$$$      |$.suu+!' !$
//    $ ?N          $'$$@$      $*`      d:"
//    $ dL..........M.$&$$      5       d"P
//  ..$.^"*I$RR*$C""??77*?      "nu...n*L*
// '$C"R   ``""!$*@#""` .uor    bu8BUU+!`
// '*@m@.       *d"     *$Rouxxd"```$
//      R*@mu.           "#$R *$    !
//      *%x. "*L               $     %.
//         "N  `%.      ...u.d!` ..ue$$$o..
//          @    ".    $*"""" .u$$$$$$$$$$$$beu...
//         8  .mL %  :R`     x$$$$$$$$$$$$$$$$$$$$$$$$$$WmeemeeWc
//        |$e!" "s:k 4      d$N"`"#$$$$$$$$$$$$$$$$$$$$$$$$$$$$$>
//        $$      "N @      $?$    F$$$$$$$$$$$$$$$$$$$$$$$$$$$$>
//        $@       ^%Uu..   R#8buu$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$>
//                   ```""*u$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$>
//                          #$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$>
//                           "5$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$>
//                             `*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$>
//                               ^#$$$$$$$$$$$$$$$$$$$$$$$$$$$$$>
//                                  "*$$$$$$$$$$$$$$$$$$$$$$$$$$>
//                                    `"*$$$$$$$$$$$$$$$$$$$$$$$>
//                                        ^!$$$$$$$$$$$$$$$$$$$$>
//                                            `"#+$$$$$$$$$$$$$$>
//                                                  ""**$$$$$$$$>
//                                                         ```""
//
// CHAD                   STAYS                     THUNDERCOCKED
//
contract Thundercock is Owned {
  using SafeTransferLib for ERC20;
  struct SellOrder {
    address token;
    uint256 amount;
    Index.UniswapVersion version;
    uint24 fee;
  }

  event IndexComponentUpdated(address indexed token, uint8 weight);
  event TokenPurchased(address indexed token, uint256 amount);
  event TokenRedeemed(address indexed token, uint256 amount);
  event TokenSold(address indexed token, uint256 amount);
  event TokenReturned(address indexed token, uint256 amount);

  IUniswapV2Router public immutable uniswapV2Router;
  ISwapRouter public immutable uniswapV3Router;
  address public immutable wethAddress;

  Index public immutable index;
  address public immutable timelock;
  address public immutable chad;

  constructor(address timelockAddress) Owned(msg.sender) {
    index = Index(payable(0xdCe46b2D2193b5fab04b3129eA9498c9B601A140));
    timelock = timelockAddress;
    chad = 0xB777eb033557490abb7Fb8F3948000826423Ea07;
    uniswapV2Router = IUniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
    uniswapV3Router = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564);
    wethAddress = uniswapV2Router.WETH();
  }

  receive() external payable {
    WETH(payable(wethAddress)).deposit{value: msg.value}();
  }

  function _requireIsOwner() internal view {
    require(msg.sender == owner, "!owner");
  }

  function reclaimIndexOwnership() external {
    _requireIsOwner();
    index.transferOwnership(owner);
  }

  function liquidateTokens(SellOrder[] calldata orders) external {
    _requireIsOwner();
    _redeemIndex();

    uint256 saleAmount;
    uint256 tokenBalance;
    address token;
    uint24 fee;
    Index.UniswapVersion version;

    for (uint256 i; i < orders.length; ) {
      token = orders[i].token;
      saleAmount = orders[i].amount;
      fee = orders[i].fee;
      version = orders[i].version;
      tokenBalance = ERC20(token).balanceOf(address(this));
      if (saleAmount > tokenBalance) {
        saleAmount = tokenBalance;
      }
      if (version == Index.UniswapVersion.V2) {
        _sellToV2(token, saleAmount);
      } else {
        _sellToV3(token, saleAmount, fee);
      }
      unchecked {
        i++;
      }
    }

    ERC20(wethAddress).safeTransfer(address(index), ERC20(wethAddress).balanceOf(address(this)));
    _returnAssets();
  }

  function enterNewParadigm() external {
    _requireIsOwner();
    uint256 priorWethBalance = ERC20(wethAddress).balanceOf(address(this));
    index.enterNewParadigm();
    ERC20(wethAddress).safeTransfer(msg.sender, ERC20(wethAddress).balanceOf(address(this)) - priorWethBalance);
  }

  function enterNewParadigmAndBurn() external {
    _requireIsOwner();
    _redeemIndex();

    uint256 etherBalance = address(this).balance;
    if (etherBalance > 0) {
      WETH(payable(wethAddress)).deposit{value: etherBalance}();
    }
    uint256 wethBalance = ERC20(wethAddress).balanceOf(address(this));

    if (wethBalance == 0) {
      return;
    }

    uint256 managementFee = (wethBalance * 2) / 100;
    uint256 purchaseAmount = (wethBalance * 98) / 100;

    WETH(payable(wethAddress)).withdraw(managementFee);
    (bool success, ) = address(owner).call{value: managementFee}("");
    require(success);

    address token;
    uint256 ethAmount;
    uint8 weight;
    uint24 fee;
    Index.UniswapVersion version;

    for (uint8 i = 0; i < index.currentTokenCount(); ) {
      token = index.tokens(i);
      (, weight, fee, version) = index.components(token);
      ethAmount = (weight * purchaseAmount) / 100;
      if (version == Index.UniswapVersion.V2) {
        _purchaseFromV2(token, ethAmount);
      } else {
        _purchaseFromV3(token, ethAmount, fee);
      }
      unchecked {
        i++;
      }
    }

    _returnAssets();
  }

  function burnChad() external {
    _requireIsOwner();
    require(ERC20(chad).balanceOf(address(index)) > 0, "!chad");
    _redeemIndex();
    _returnAssets();
  }

  function setChad() external {
    _requireIsOwner();
    index.setChad(chad);
  }

  function _redeemIndex() internal {
    ERC20 redemptionToken = new LightningBolt();
    index.setChad(address(redemptionToken));
    index.redeem(redemptionToken.balanceOf(address(this)));
    index.setChad(chad);
    uint256 chadBalance = ERC20(chad).balanceOf(address(this));
    if (chadBalance > 0) {
      index.redeem(chadBalance);
    }
  }

  function _returnAssets() internal {
    Index.TokenAmount[] memory tokenAmounts = index.redemptionAmounts();
    for (uint i; i < tokenAmounts.length; ) {
      address token = tokenAmounts[i].token;
      uint256 balance = ERC20(token).balanceOf(address(this));
      if (balance > 0) {
        ERC20(token).safeTransfer(address(index), balance);
        emit TokenReturned(token, balance);
      }
      unchecked {
        i++;
      }
    }
  }

  function _purchaseFromV2(address token, uint256 amount) internal {
    address[] memory path = new address[](2);
    path[0] = wethAddress;
    path[1] = token;
    uint256 balanceBefore = ERC20(token).balanceOf(address(this));
    uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
      amount,
      0,
      path,
      address(this),
      block.timestamp
    );
    uint256 balanceAfter = ERC20(token).balanceOf(address(this));
    emit TokenPurchased(token, balanceAfter - balanceBefore);
  }

  function _purchaseFromV3(address token, uint256 amount, uint24 fee) internal {
    uint256 balanceBefore = ERC20(token).balanceOf(address(this));
    uniswapV3Router.exactInput(
      ISwapRouter.ExactInputParams({
        path: abi.encodePacked(wethAddress, fee, token),
        recipient: address(this),
        deadline: block.timestamp,
        amountIn: amount,
        amountOutMinimum: 0
      })
    );
    uint256 balanceAfter = ERC20(token).balanceOf(address(this));
    emit TokenPurchased(token, balanceAfter - balanceBefore);
  }

  function _sellToV2(address token, uint256 amount) internal {
    ERC20(token).approve(address(uniswapV2Router), type(uint256).max);
    address[] memory path = new address[](2);
    path[0] = token;
    path[1] = wethAddress;
    uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
      amount,
      0,
      path,
      address(this),
      block.timestamp
    );
    emit TokenSold(token, amount);
  }

  function _sellToV3(address token, uint256 amount, uint24 fee) internal {
    ERC20(token).approve(address(uniswapV3Router), type(uint256).max);
    uniswapV3Router.exactInput(
      ISwapRouter.ExactInputParams({
        path: abi.encodePacked(token, fee, wethAddress),
        recipient: address(this),
        deadline: block.timestamp,
        amountIn: amount,
        amountOutMinimum: 0
      })
    );
    emit TokenSold(token, amount);
  }

  // Emergency Function

  function executeAssembly(address _target, bytes memory _data) public payable returns (bytes memory response) {
    require(msg.sender == timelock, "!timelock");
    require(_target != address(0), "!target");

    // call contract in current context
    assembly {
      let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0)
      let size := returndatasize()

      response := mload(0x40)
      mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))))
      mstore(response, size)
      returndatacopy(add(response, 0x20), 0, size)

      switch iszero(succeeded)
      case 1 {
        // throw if delegatecall failed
        revert(add(response, 0x20), size)
      }
    }
  }

  function execute(address _target, bytes calldata _data) external {
    require(msg.sender == timelock, "!timelock");
    require(_target != address(0), "!target");

    (bool success, ) = _target.call(_data);
    require(success);
  }
}

// File: lib/solmate/src/auth/Owned.sol



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

/// @notice Simple single owner authorization mixin.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Owned.sol)
abstract contract Owned {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

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

    /*//////////////////////////////////////////////////////////////
                            OWNERSHIP STORAGE
    //////////////////////////////////////////////////////////////*/

    address public owner;

    modifier onlyOwner() virtual {
        require(msg.sender == owner, "UNAUTHORIZED");

        _;
    }

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

    constructor(address _owner) {
        owner = _owner;

        emit OwnershipTransferred(address(0), _owner);
    }

    /*//////////////////////////////////////////////////////////////
                             OWNERSHIP LOGIC
    //////////////////////////////////////////////////////////////*/

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

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

// File: lib/solmate/src/tokens/ERC20.sol



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

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

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

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

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

    string public name;

    string public symbol;

    uint8 public immutable decimals;

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

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

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

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

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

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

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

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

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

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

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

        return true;
    }

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

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

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

        return true;
    }

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

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

        balanceOf[from] -= amount;

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

        emit Transfer(from, to, amount);

        return true;
    }

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

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

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

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

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

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

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

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

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

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

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

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

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

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

// File: lib/solmate/src/utils/SafeTransferLib.sol



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

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

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

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

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

        require(success, "ETH_TRANSFER_FAILED");
    }

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

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

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

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

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

        require(success, "TRANSFER_FROM_FAILED");
    }

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

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

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

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

        require(success, "TRANSFER_FAILED");
    }

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

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

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

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

        require(success, "APPROVE_FAILED");
    }
}

// File: lib/solmate/src/tokens/WETH.sol



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

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

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

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

    event Deposit(address indexed from, uint256 amount);

    event Withdrawal(address indexed to, uint256 amount);

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

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

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

        emit Withdrawal(msg.sender, amount);

        msg.sender.safeTransferETH(amount);
    }

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

// File: src/Index.sol



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

import {Owned} from "solmate/auth/Owned.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {SafeTransferLib} from "solmate/utils/SafeTransferLib.sol";
import {WETH as IWETH} from "solmate/tokens/WETH.sol";
import {IChad} from "./interfaces/IChad.sol";

import {IUniswapV2Router} from "./interfaces/IUniswapV2Router.sol";
import {ISwapRouter} from "@uniswap/v3-periphery/interfaces/ISwapRouter.sol";
import {IQuoter} from "@uniswap/v3-periphery/interfaces/IQuoter.sol";

contract Index is Owned {
  using SafeTransferLib for ERC20;

  enum UniswapVersion {
    V2,
    V3
  }

  struct IndexComponent {
    address token;
    uint8 weight;
    uint24 fee;
    UniswapVersion version;
  }
  struct TokenAmount {
    address token;
    uint256 amount;
  }

  event SetChad(address indexed chad);
  event IndexComponentUpdated(address indexed token, uint8 weight);
  event TokenPurchased(address indexed token, uint256 amount);
  event TokenRedeemed(address indexed token, uint256 amount);

  IUniswapV2Router public immutable uniswapV2Router;
  ISwapRouter public immutable uniswapV3Router;

  /// @dev enable perfect granularity
  uint256 public constant MAX_BPS = 1_000_000_000 * 1e18;
  uint24 public immutable LOW_FEE = 3_000;
  uint24 public immutable HIGH_FEE = 10_000;
  address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
  address public constant OX = 0x78a0A62Fba6Fb21A83FE8a3433d44C73a4017A6f;
  address public constant RLB = 0x046EeE2cc3188071C02BfC1745A6b17c656e3f3d;
  address public constant DMT = 0x0B7f0e51Cd1739D6C96982D55aD8fA634dd43A9C;
  address public constant BITCOIN = 0x72e4f9F808C49A2a61dE9C5896298920Dc4EEEa9;
  address public constant UNIBOT = 0xf819d9Cb1c2A819Fd991781A822dE3ca8607c3C9;

  bool public canUpdateWeights = true;
  address public chad;
  address public timelock;
  uint256 public lastPurchase;

  // Current implementation
  mapping(address => IndexComponent) public components;
  mapping(address => bool) public hasToken;
  address[] public tokens;
  address[] public allTokens;

  constructor(address routerAddressV2, address routerAddressV3, address timelockAddress) Owned(msg.sender) {
    uniswapV2Router = IUniswapV2Router(routerAddressV2);
    uniswapV3Router = ISwapRouter(routerAddressV3);
    timelock = timelockAddress;

    components[OX] = IndexComponent({token: OX, weight: 25, fee: HIGH_FEE, version: UniswapVersion.V3});
    components[RLB] = IndexComponent({token: RLB, weight: 25, fee: LOW_FEE, version: UniswapVersion.V3});
    components[DMT] = IndexComponent({token: DMT, weight: 10, fee: LOW_FEE, version: UniswapVersion.V3});
    components[BITCOIN] = IndexComponent({token: BITCOIN, weight: 20, fee: 0, version: UniswapVersion.V2});
    components[UNIBOT] = IndexComponent({token: UNIBOT, weight: 20, fee: 0, version: UniswapVersion.V2});

    tokens = [OX, RLB, DMT, BITCOIN, UNIBOT];
    allTokens = [OX, RLB, DMT, BITCOIN, UNIBOT];

    hasToken[OX] = true;
    hasToken[RLB] = true;
    hasToken[DMT] = true;
    hasToken[BITCOIN] = true;
    hasToken[UNIBOT] = true;

    ERC20(WETH).approve(routerAddressV2, type(uint256).max);
    ERC20(WETH).approve(routerAddressV3, type(uint256).max);

    lastPurchase = block.timestamp;
  }

  receive() external payable {}

  function _requireIsOwner() internal view {
    require(msg.sender == owner, "!owner");
  }

  function setChad(address newChad) external {
    _requireIsOwner();
    chad = newChad;
    ERC20(IChad(chad).uniswapV2Pair()).approve(address(uniswapV2Router), type(uint256).max);
    emit SetChad(newChad);
  }

  function enterNewParadigm() external {
    _requireIsOwner();
    uint256 wethBalance = ERC20(WETH).balanceOf(address(this));
    uint256 etherBalance = address(this).balance;

    uint256 totalBalance = wethBalance + etherBalance;

    if (totalBalance == 0) {
      return;
    }

    uint256 managementFee = (totalBalance * 2) / 100;
    uint256 purchaseAmount = (totalBalance * 98) / 100;
    uint256 etherToWithdraw = managementFee - etherBalance;

    if (etherToWithdraw > 0) {
      IWETH(payable(WETH)).withdraw(etherToWithdraw);
    }
    (bool success, ) = address(owner).call{value: managementFee}("");
    require(success);

    address token;
    uint256 ethAmount;
    IndexComponent memory component;
    for (uint8 i = 0; i < tokens.length; ) {
      token = tokens[i];
      component = components[token];
      ethAmount = (component.weight * purchaseAmount) / 100;
      if (component.version == UniswapVersion.V2) {
        _purchaseFromV2(token, ethAmount);
      } else {
        _purchaseFromV3(token, ethAmount, component.fee);
      }
      unchecked {
        i++;
      }
    }

    lastPurchase = block.timestamp;
  }

  /// @dev cannot update weights without using timelock as an anti rug measure
  function updateWeights(IndexComponent[] calldata newComponents) external {
    require(timelock != address(0) && msg.sender == timelock, "!timelock");
    uint8 totalWeight;
    for (uint8 i = 0; i < newComponents.length; ) {
      totalWeight += newComponents[i].weight;
      unchecked {
        i++;
      }
    }
    require(totalWeight == 100, "!valid");
    for (uint i = 0; i < allTokens.length; ) {
      address token = allTokens[i];
      delete components[token];
      emit IndexComponentUpdated(token, 0);
      unchecked {
        i++;
      }
    }
    delete tokens;
    IndexComponent memory currentComponent;
    for (uint i = 0; i < newComponents.length; ) {
      currentComponent = newComponents[i];
      components[currentComponent.token] = currentComponent;
      tokens.push(currentComponent.token);
      if (!hasToken[currentComponent.token]) {
        hasToken[currentComponent.token] = true;
        allTokens.push(currentComponent.token);
      }
      emit IndexComponentUpdated(currentComponent.token, currentComponent.weight);
      unchecked {
        i++;
      }
    }
  }

  function redeem(uint256 amount) external {
    require(chad != address(0));
    require(amount > 0, "!tokens");
    uint256 share = (amount * MAX_BPS) / ERC20(chad).totalSupply();

    IChad(chad).burn(msg.sender, amount);

    address token;
    uint256 allocation;
    uint256 contractBalance;
    for (uint8 i = 0; i < allTokens.length; ) {
      token = allTokens[i];
      contractBalance = ERC20(token).balanceOf(address(this));
      if (contractBalance > 0) {
        allocation = (contractBalance * share) / MAX_BPS;
        ERC20(token).safeTransfer(msg.sender, allocation);
        emit TokenRedeemed(token, allocation);
      }
      unchecked {
        i++;
      }
    }

    if (lastPurchase != 0 && lastPurchase + 15 days < block.timestamp) {
      // anti-rug vector, if deployed dies or project stagnates the initial LP can be redeemed + all added liquidity
      address liquidityAddress = IChad(chad).uniswapV2Pair();
      uint256 liquidityBalance = ERC20(liquidityAddress).balanceOf(address(this));
      uint256 liquidityAllocation = (liquidityBalance * share) / MAX_BPS;
      if (liquidityAllocation > 0) {
        uniswapV2Router.removeLiquidity(WETH, chad, liquidityAllocation, 0, 0, address(this), block.timestamp);
      }
      uint256 chadRemoved = ERC20(chad).balanceOf(address(this));
      IChad(chad).burn(address(this), chadRemoved);

      // anti-rug vector, if deployer dies or never updates the index - can redeem for weth
      uint256 wethBalance = ERC20(WETH).balanceOf(address(this));
      uint256 wethAllocation = (wethBalance * share) / MAX_BPS;
      if (wethAllocation > 0) {
        ERC20(WETH).safeTransfer(msg.sender, wethAllocation);
      }
    }
  }

  function redemptionAmounts() external view returns (TokenAmount[] memory) {
    TokenAmount[] memory tokenAmounts = new TokenAmount[](allTokens.length);
    for (uint8 i = 0; i < allTokens.length; ) {
      address token = allTokens[i];
      tokenAmounts[i].token = token;
      tokenAmounts[i].amount = ERC20(token).balanceOf(address(this));
      unchecked {
        i++;
      }
    }
    return tokenAmounts;
  }

  function currentTokenCount() external view returns (uint256) {
    return tokens.length;
  }

  function totalTokenCount() external view returns (uint256) {
    return allTokens.length;
  }

  function _purchaseFromV2(address token, uint256 amount) internal {
    address[] memory path = new address[](2);
    path[0] = WETH;
    path[1] = token;
    uint256 balanceBefore = ERC20(token).balanceOf(address(this));
    uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
      amount,
      0,
      path,
      address(this),
      block.timestamp
    );
    uint256 balanceAfter = ERC20(token).balanceOf(address(this));
    emit TokenPurchased(token, balanceAfter - balanceBefore);
  }

  function _purchaseFromV3(address token, uint256 amount, uint24 fee) internal {
    uint256 balanceBefore = ERC20(token).balanceOf(address(this));
    uniswapV3Router.exactInput(
      ISwapRouter.ExactInputParams({
        path: abi.encodePacked(WETH, fee, token),
        recipient: address(this),
        deadline: block.timestamp,
        amountIn: amount,
        amountOutMinimum: 0
      })
    );
    uint256 balanceAfter = ERC20(token).balanceOf(address(this));
    emit TokenPurchased(token, balanceAfter - balanceBefore);
  }
}

// File: src/LightningBolt.sol



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

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

/**

Create a token that implements the Chad burn.

 */
contract LightningBolt is ERC20 {
  address public uniswapV2Pair = 0x2DB071E62C052f9709F916A585cc9249D46Da778;

  constructor() ERC20("LightningBolt Token", "THUNDER", 18) {
    _mint(msg.sender, 1_000_000_000 * 1e18);
  }

  function burn(address from, uint256 amount) external {
    _burn(from, amount);
  }
}

// File: src/interfaces/IUniswapV2Router.sol



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

interface IUniswapV2Router {
  function factory() external pure returns (address);

  function WETH() external pure returns (address);

  function addLiquidity(
    address tokenA,
    address tokenB,
    uint256 amountADesired,
    uint256 amountBDesired,
    uint256 amountAMin,
    uint256 amountBMin,
    address to,
    uint256 deadline
  ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);

  function removeLiquidity(
    address tokenA,
    address tokenB,
    uint liquidity,
    uint amountAMin,
    uint amountBMin,
    address to,
    uint deadline
  ) external returns (uint amountA, uint amountB);

  function addLiquidityETH(
    address token,
    uint256 amountTokenDesired,
    uint256 amountTokenMin,
    uint256 amountETHMin,
    address to,
    uint256 deadline
  ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);

  function swapExactTokensForTokensSupportingFeeOnTransferTokens(
    uint256 amountIn,
    uint256 amountOutMin,
    address[] calldata path,
    address to,
    uint256 deadline
  ) external;

  function swapExactETHForTokensSupportingFeeOnTransferTokens(
    uint256 amountOutMin,
    address[] calldata path,
    address to,
    uint256 deadline
  ) external payable;

  function swapExactTokensForETHSupportingFeeOnTransferTokens(
    uint256 amountIn,
    uint256 amountOutMin,
    address[] calldata path,
    address to,
    uint256 deadline
  ) external;
}

// File: lib/v3-periphery/contracts/interfaces/ISwapRouter.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}

// File: src/interfaces/IChad.sol



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

interface IChad {
  function burn(address from, uint256 amount) external;

  function uniswapV2Pair() external returns (address);
}

// File: lib/v3-periphery/contracts/interfaces/IQuoter.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Quoter Interface
/// @notice Supports quoting the calculated amounts from exact input or exact output swaps
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface IQuoter {
    /// @notice Returns the amount out received for a given exact input swap without executing the swap
    /// @param path The path of the swap, i.e. each token pair and the pool fee
    /// @param amountIn The amount of the first token to swap
    /// @return amountOut The amount of the last token that would be received
    function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut);

    /// @notice Returns the amount out received for a given exact input but for a swap of a single pool
    /// @param tokenIn The token being swapped in
    /// @param tokenOut The token being swapped out
    /// @param fee The fee of the token pool to consider for the pair
    /// @param amountIn The desired input amount
    /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
    /// @return amountOut The amount of `tokenOut` that would be received
    function quoteExactInputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96
    ) external returns (uint256 amountOut);

    /// @notice Returns the amount in required for a given exact output swap without executing the swap
    /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order
    /// @param amountOut The amount of the last token to receive
    /// @return amountIn The amount of first token required to be paid
    function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn);

    /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool
    /// @param tokenIn The token being swapped in
    /// @param tokenOut The token being swapped out
    /// @param fee The fee of the token pool to consider for the pair
    /// @param amountOut The desired output amount
    /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
    /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`
    function quoteExactOutputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        uint256 amountOut,
        uint160 sqrtPriceLimitX96
    ) external returns (uint256 amountIn);
}

// File: lib/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol



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

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}