// File: contracts/antiMev/OneDirectionPerBlockAntiMevStrategy.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;

import {Ownable} from "../oz/access/Ownable.sol";
import {IAntiMevStrategy} from "../interfaces/IAntiMevStrategy.sol";
import {IPair} from "../interfaces/IPair.sol";
import {IUniswapV2Factory} from "../interfaces/IUniswapV2Factory.sol";
import {IUniswapV3Factory} from "../interfaces/IUniswapV3Factory.sol";
import {IPoolV3} from "../interfaces/IPoolV3.sol";

/// @title
/// @author Ben Coin Collective
/// @notice This contains the logic necessary for blocking MEV bots from frontrunning transactions.
contract OneDirectionPerBlockAntiMevStrategy is Ownable, IAntiMevStrategy {
  event SetFactoryWhitelist(address whitelist, uint8 version, bool isWhitelisted);
  event SetMEVWhitelist(address whitelist, bool isWhitelisted);

  error OnlyOneTransferPerBlockPerAddress(address);
  error OnlyBen();

  struct FactoryInfo {
    bool isWhitelisted;
    uint8 version;
  }

  address public ben;
  mapping(bytes32 accountHash => bool[2] directions) private accountTransferredPerBlock;
  mapping(address whitelist => bool isWhitelisted) public MEVWhitelist; // For certain addresses to be exempt from MEV like exchanges
  mapping(address factory => FactoryInfo factoryInfo) public factoryInfos;

  modifier onlyBen() {
    if (msg.sender != ben) {
      revert OnlyBen();
    }
    _;
  }

  constructor(address _ben) {
    ben = _ben;
  }

  function onTransfer(
    address _from,
    address _to,
    uint256 /*_amount*/,
    bool _isTaxingInProgress
  ) external override onlyBen {
    // If from or to an LP, then whitelist it from MEV
    if (_isTaxingInProgress) {
      return;
    }

    bool fromIsWhitelisted = MEVWhitelist[_from];
    if (!fromIsWhitelisted) {
      fromIsWhitelisted = _isPair(_from);
    }

    bool toIsWhitelisted = MEVWhitelist[_to];
    if (!toIsWhitelisted) {
      toIsWhitelisted = _isPair(_to);
    }

    if (!fromIsWhitelisted) {
      bytes32 key = keccak256(abi.encodePacked(block.number, _from));
      if (accountTransferredPerBlock[key][1]) {
        revert OnlyOneTransferPerBlockPerAddress(_from);
      }
      accountTransferredPerBlock[key][0] = true;
    }
    if (!toIsWhitelisted) {
      bytes32 key = keccak256(abi.encodePacked(block.number, _to));
      if (accountTransferredPerBlock[key][0]) {
        revert OnlyOneTransferPerBlockPerAddress(_to);
      }
      accountTransferredPerBlock[key][1] = true;
    }
  }

  function _isPair(address _target) private view returns (bool) {
    // Not a contract
    if (_target.code.length == 0) {
      return false;
    }

    IPair pairContract = IPair(_target);
    address factory;
    try pairContract.factory() returns (address _factory) {
      factory = _factory;
    } catch {
      return false;
    }

    // Possible pair, check if factory is whitelisted
    FactoryInfo memory factoryInfo = factoryInfos[factory];
    if (!factoryInfo.isWhitelisted) {
      return false;
    }

    // Check if this is actually an LP
    address token0;
    try pairContract.token0() returns (address _token0) {
      token0 = _token0;
    } catch {
      return false;
    }

    address token1;
    try pairContract.token1() returns (address _token1) {
      token1 = _token1;
    } catch {
      return false;
    }

    if (factoryInfo.version == 2) {
      // UniV2 pairs
      return IUniswapV2Factory(factory).getPair(token0, token1) == _target;
    } else if (factoryInfo.version == 3) {
      // UniV3 pairs
      uint24 fee;
      try IPoolV3(_target).fee() returns (uint24 _fee) {
        fee = _fee;
      } catch {
        return false;
      }

      return IUniswapV3Factory(factory).getPool(token0, token1, fee) == _target;
    }
  }

  function _setMEVWhitelist(address _whitelist, bool _isWhitelisted) private {
    MEVWhitelist[_whitelist] = _isWhitelisted;
    emit SetMEVWhitelist(_whitelist, _isWhitelisted);
  }

  function setFactoryWhitelist(address _whitelist, uint8 _version, bool _isWhitelisted) external onlyOwner {
    factoryInfos[_whitelist].isWhitelisted = _isWhitelisted;
    factoryInfos[_whitelist].version = _version;
    emit SetFactoryWhitelist(_whitelist, _version, _isWhitelisted);
  }

  function setMEVWhitelist(address _whitelist, bool _isWhitelisted) external onlyOwner {
    _setMEVWhitelist(_whitelist, _isWhitelisted);
  }

  function setMEVWhitelists(address[] calldata _whitelists, bool[] calldata _isWhitelisted) external onlyOwner {
    for (uint i; i < _whitelists.length; i++) {
      _setMEVWhitelist(_whitelists[i], _isWhitelisted[i]);
    }
  }
}

// File: contracts/interfaces/IAntiMevStrategy.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;

interface IAntiMevStrategy {
  function onTransfer(address from, address to, uint256 amount, bool isTaxingInProgress) external;
}

// File: contracts/interfaces/IPair.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;

interface IPair {
  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);
}

// File: contracts/interfaces/IPoolV3.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;

interface IPoolV3 {
  function fee() external view returns (uint24);
}

// File: contracts/interfaces/IUniswapV2Factory.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;

interface IUniswapV2Factory {
  function getPair(address tokenA, address tokenB) external view returns (address);

  function createPair(address tokenA, address tokenB) external returns (address);
}

// File: contracts/interfaces/IUniswapV3Factory.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;

interface IUniswapV3Factory {
  function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address pool);
}

// File: contracts/oz/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    error OnlyOwner();
    error NewOwnerIsZeroAddress();

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OnlyOwner();
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert NewOwnerIsZeroAddress();
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: contracts/oz/utils/Context.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}