// File: src/bridgeZaps/zapFrom.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import {ERC20} from "lib/solmate/src/tokens/ERC20.sol";
import {SafeTransferLib} from "lib/solmate/src/utils/SafeTransferLib.sol";
import {WETH} from "lib/solmate/src/tokens/WETH.sol";
import {SwapController} from "./controllers/swapController.sol";
import {IErrors} from "../interfaces/IErrors.sol";
import {IStargateRouter} from "../interfaces/bridges/IStargateRouter.sol";
import {ILayerZeroRouter} from "../interfaces/bridges/ILayerZeroRouter.sol";

contract ZapFrom is IErrors, SwapController {
    using SafeTransferLib for ERC20;
    uint16 public constant ARBITRUM_CHAIN_ID = 110; // NOTE: Id used by Stargate for Arbitrum
    // NOTE: This is the abi.encodePacked destAddress
    bytes public constant ARB_RECEIVER =
        "0x9c668a934611706f84f5b22705ecdf94c3349c5d";
    address public immutable stargateRouter;
    address public immutable stargateRouterEth;
    address public immutable layerZeroRouter;
    address public immutable y2kArbRouter;
    // TODO: Make this constant with pre-computed address and additional var
    // NOTE: abi.encodePacked(remoteAddress, localAddress)
    bytes public layerZeroRemoteAndLocal;

    struct Config {
        address _stargateRouter;
        address _stargateRouterEth;
        address _layerZeroRouterLocal;
        address _y2kArbRouter;
        address _uniswapV2Factory;
        address _sushiSwapFactory;
        address _uniswapV3Factory;
        address _balancerVault;
        address _wethAddress;
        bytes _primaryInitHash;
        bytes _secondaryInitHash;
    }

    constructor(
        Config memory _config
    )
        SwapController(
            _config._uniswapV2Factory,
            _config._sushiSwapFactory,
            _config._uniswapV3Factory,
            _config._balancerVault,
            _config._wethAddress,
            _config._primaryInitHash,
            _config._secondaryInitHash
        )
    {
        if (_config._stargateRouter == address(0)) revert InvalidInput();
        if (_config._stargateRouterEth == address(0)) revert InvalidInput();
        if (_config._layerZeroRouterLocal == address(0)) revert InvalidInput();
        if (_config._y2kArbRouter == address(0)) revert InvalidInput();
        stargateRouter = _config._stargateRouter;
        stargateRouterEth = _config._stargateRouterEth;
        layerZeroRouter = _config._layerZeroRouterLocal;
        // TODO: Remove this for a constant
        layerZeroRemoteAndLocal = abi.encodePacked(
            _config._y2kArbRouter,
            address(this)
        );
        y2kArbRouter = _config._y2kArbRouter;
    }

    //////////////////////////////////////////////
    //                 PUBLIC                   //
    //////////////////////////////////////////////
    /// @param amountIn The qty of local _token contract tokens
    /// @param fromToken The fromChain token address
    /// @param srcPoolId The poolId for the fromChain
    /// @param dstPoolId The poolId for the toChain
    /// @param payload The encoded payload to deposit into vault abi.encode(receiver, vaultId)
    function bridge(
        uint amountIn,
        address fromToken,
        uint16 srcPoolId,
        uint16 dstPoolId,
        bytes calldata payload
    ) external payable {
        if (msg.value == 0) revert InvalidInput();
        if (amountIn == 0) revert InvalidInput();

        if (fromToken != address(0)) {
            ERC20(fromToken).safeTransferFrom(
                msg.sender,
                address(this),
                amountIn
            );
        }
        _bridge(amountIn, fromToken, srcPoolId, dstPoolId, payload);
    }

    // TODO: Need to implement this
    function permitSwapAndBridge(
        uint amountIn,
        address fromToken,
        address receivedToken,
        uint16 srcPoolId,
        uint16 dstPoolId,
        bytes calldata swapPayload,
        bytes calldata bridgePayload
    ) public payable {
        if (msg.value == 0) revert InvalidInput();
        if (amountIn == 0) revert InvalidInput();

        // TODO: implement permit2 for the fromToken transfer
        ERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn);
        uint256 receivedAmount = _swap(
            swapPayload[0],
            amountIn,
            swapPayload[32:]
        );
        _bridge(
            receivedAmount,
            receivedToken,
            srcPoolId,
            dstPoolId,
            bridgePayload
        );
    }

    function swapAndBridge(
        uint amountIn,
        address fromToken,
        address receivedToken,
        uint16 srcPoolId,
        uint16 dstPoolId,
        bytes1 dexId,
        bytes calldata swapPayload,
        bytes calldata bridgePayload
    ) external payable {
        if (msg.value == 0) revert InvalidInput();
        if (amountIn == 0) revert InvalidInput();

        ERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn);

        // NOTE: Check if not Balancer as fromToken location is dynamic
        uint256 receivedAmount;
        if (dexId != 0x05) {
            receivedAmount = _swap(dexId, amountIn, swapPayload);
        } else {
            ERC20(fromToken).safeApprove(balancerVault, amountIn);
            receivedAmount = _swapBalancer(swapPayload);
        }

        if (receivedToken == wethAddress) {
            WETH(wethAddress).withdraw(receivedAmount);
            receivedToken = address(0);
        }

        _bridge(
            receivedAmount,
            receivedToken,
            srcPoolId,
            dstPoolId,
            bridgePayload
        );
    }

    // TODO: Check the construction of the remote and local variables
    function withdraw(bytes memory payload) external payable {
        if (msg.value == 0) revert InvalidInput();
        ILayerZeroRouter(layerZeroRouter).send{value: msg.value}(
            uint16(ARBITRUM_CHAIN_ID), // destination LayerZero chainId
            layerZeroRemoteAndLocal, // send to this address on the destination
            payload, // bytes payload
            payable(msg.sender), // refund address
            address(0x0), // future parameter
            bytes("") // adapterParams (see "Advanced Features")
        );
    }

    //////////////////////////////////////////////
    //                 INTERNAL                 //
    //////////////////////////////////////////////

    function _bridge(
        uint amountIn,
        address fromToken,
        uint16 srcPoolId,
        uint16 dstPoolId,
        bytes calldata payload
    ) private {
        if (fromToken == address(0)) {
            // NOTE: When sending after a swap msg.value will be < amountIn as only contains the fee
            // When sending without swap msg.value will be > amountIn as contains fee + amountIn
            uint256 msgValue = msg.value > amountIn
                ? msg.value
                : amountIn + msg.value;
            IStargateRouter(stargateRouterEth).swapETHAndCall{value: msgValue}(
                uint16(ARBITRUM_CHAIN_ID), // destination Stargate chainId
                payable(msg.sender), // refund additional messageFee to this address
                ARB_RECEIVER, // the receiver of the destination ETH
                IStargateRouter.SwapAmount(amountIn, (amountIn * 950) / 1000),
                IStargateRouter.lzTxObj(200000, 0, "0x"), // default lzTxObj
                payload // the payload to send to the destination
            );
        } else {
            ERC20(fromToken).safeApprove(stargateRouter, amountIn);
            // Sends tokens to the destChain
            IStargateRouter(stargateRouter).swap{value: msg.value}(
                uint16(ARBITRUM_CHAIN_ID), // the destination chain id
                srcPoolId, // the source Stargate poolId
                dstPoolId, // the destination Stargate poolId
                payable(msg.sender), // refund adddress. if msg.sender pays too much gas, return extra eth
                amountIn, // total tokens to send to destination chain
                (amountIn * 950) / 1000, // min amount allowed out
                IStargateRouter.lzTxObj(200000, 0, "0x"), // default lzTxObj
                ARB_RECEIVER, // destination address, the sgReceive() implementer
                payload
            );
        }
    }

    receive() external payable {}
}

// 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), from) // Append the "from" argument.
            mstore(add(freeMemoryPointer, 36), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument.

            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), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            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), to) // Append the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument.

            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/bridgeZaps/controllers/swapController.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import {ERC20} from "lib/solmate/src/tokens/ERC20.sol";
import {SafeTransferLib} from "lib/solmate/src/utils/SafeTransferLib.sol";
import {UniswapV2Swapper} from "../dexHelpers/uniswapV2.sol";
import {UniswapV3Swapper} from "../dexHelpers/uniswapV3.sol";
import {CurveSwapper} from "../dexHelpers/curve.sol";

abstract contract SwapController is
    UniswapV2Swapper,
    UniswapV3Swapper,
    CurveSwapper
{
    using SafeTransferLib for ERC20;
    address public immutable balancerVault;
    error FailedSwap();

    constructor(
        address _uniswapV2Factory,
        address _sushiFactory,
        address _uniswapV3Factory,
        address _balancerVault,
        address _wethAddress,
        bytes memory _primaryInitHash,
        bytes memory _secondaryInitHash
    )
        UniswapV2Swapper(
            _uniswapV2Factory,
            _sushiFactory,
            _primaryInitHash,
            _secondaryInitHash
        )
        UniswapV3Swapper(_uniswapV3Factory)
        CurveSwapper(_wethAddress)
    {
        if (_balancerVault == address(0)) revert InvalidInput();
        balancerVault = _balancerVault;
    }

    function _swap(
        bytes1 dexId,
        uint256 fromAmount,
        bytes calldata swapPayload
    ) internal returns (uint256) {
        if (dexId == 0x01) return _swapUniswapV2(0x01, fromAmount, swapPayload);
        else if (dexId == 0x02) return _swapUniswapV3(fromAmount, swapPayload);
        else if (dexId == 0x03)
            return _swapUniswapV2(0x02, fromAmount, swapPayload);
        else if (dexId == 0x04) return _swapWithCurve(swapPayload);
        else revert InvalidInput();
    }

    function _swapBalancer(
        bytes calldata swapPayload
    ) internal returns (uint256) {
        (bool success, bytes memory data) = balancerVault.call(swapPayload);
        if (!success) revert FailedSwap();

        bytes4 selector = abi.decode(swapPayload, (bytes4));
        if (selector == bytes4(0x52bbbe29)) {
            return abi.decode(data, (uint256));
        } else {
            int256[] memory assetDeltas = abi.decode(data, (int256[]));
            for (uint256 i = 0; i < assetDeltas.length; ) {
                if (assetDeltas[i] < 0) return uint256(-assetDeltas[i]);
                unchecked {
                    i++;
                }
            }
            revert FailedSwap();
        }
    }
}

// File: src/interfaces/IErrors.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

interface IErrors {
    // TODO: Either invalidMintOut or InvalidOutput
    error InvalidMinOut(uint256 minOut);
    error InvalidInput();
    error InvalidOutput();
    error FailedCall(bytes data);
    error InvalidCaller();
    error InvalidFunctionId();
    error InvalidSwapId();
    error InvalidBridgeId();
    error InvalidVault();
    error InvalidHopBridge();
    error NullBalance();
}

// File: src/interfaces/bridges/IStargateRouter.sol



pragma solidity 0.8.18;

interface IStargateRouter {
    struct lzTxObj {
        uint256 dstGasForCall;
        uint256 dstNativeAmount;
        bytes dstNativeAddr;
    }

    struct SwapAmount {
        uint256 amountLD; // the amount, in Local Decimals, to be swapped
        uint256 minAmountLD; // the minimum amount accepted out on destination
    }

    function swap(
        uint16 _dstChainId,
        uint256 _srcPoolId,
        uint256 _dstPoolId,
        address payable _refundAddress,
        uint256 _amountLD,
        uint256 _minAmountLD,
        lzTxObj memory _lzTxParams,
        bytes calldata _to,
        bytes calldata _payload
    ) external payable;

    function swapETHAndCall(
        uint16 _dstChainId, // destination Stargate chainId
        address payable _refundAddress, // refund additional messageFee to this address
        bytes calldata _toAddress, // the receiver of the destination ETH
        SwapAmount memory _swapAmount, // the amount and the minimum swap amount
        IStargateRouter.lzTxObj memory _lzTxParams, // the LZ tx params
        bytes calldata _payload // the payload to send to the destination
    ) external payable;
}

// File: src/interfaces/bridges/ILayerZeroRouter.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

interface ILayerZeroRouter {
    // @notice send a LayerZero message to the specified address at a LayerZero endpoint specified by our chainId.
    // @param _dstChainId - the destination chain identifier
    // @param _remoteAndLocalAddresses - remote address concated with local address packed into 40 bytes
    // @param _payload - a custom bytes payload to send to the destination contract
    // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address
    // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction
    // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination
    function send(
        uint16 _dstChainId,
        bytes calldata _remoteAndLocalAddresses,
        bytes calldata _payload,
        address payable _refundAddress,
        address _zroPaymentAddress,
        bytes calldata _adapterParams
    ) external payable;
}

// File: src/bridgeZaps/dexHelpers/uniswapV2.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import {ERC20} from "lib/solmate/src/tokens/ERC20.sol";
import {SafeTransferLib} from "lib/solmate/src/utils/SafeTransferLib.sol";
import {IUniswapPair} from "../../interfaces/dexes/IUniswapPair.sol";
import {IEarthquake} from "../../interfaces/IEarthquake.sol";
import {IErrors} from "../../interfaces/IErrors.sol";

contract UniswapV2Swapper is IErrors {
    using SafeTransferLib for ERC20;
    address public immutable uniswapV2ForkFactory;
    address public immutable sushiFactory;
    // TODO: Could hardcode these as constants
    bytes internal primaryInitHash;
    bytes internal secondaryInitHash;

    constructor(
        address _uniswapV2Factory,
        address _sushiFactory,
        bytes memory _primaryInitHash,
        bytes memory _secondaryInitHash
    ) {
        if (_uniswapV2Factory == address(0)) revert InvalidInput();
        if (_sushiFactory == address(0)) revert InvalidInput();
        if (keccak256(_primaryInitHash) == keccak256(bytes("")))
            revert InvalidInput();
        if (keccak256(_secondaryInitHash) == keccak256(bytes("")))
            revert InvalidInput();

        uniswapV2ForkFactory = _uniswapV2Factory;
        sushiFactory = _sushiFactory;
        primaryInitHash = _primaryInitHash;
        secondaryInitHash = _secondaryInitHash;
    }

    function _swapUniswapV2(
        bytes1 dexId,
        uint256 fromAmount,
        bytes memory payload
    ) internal returns (uint256 amountOut) {
        (address[] memory path, uint256 toAmountMin) = abi.decode(
            payload,
            (address[], uint256)
        );
        uint256[] memory amounts = new uint256[](path.length - 1);
        address[] memory pairs = new address[](path.length - 1);

        bytes memory initCodeHash;
        address factory;
        if (dexId == 0x01) {
            initCodeHash = primaryInitHash;
            factory = uniswapV2ForkFactory;
        } else if (dexId == 0x02) {
            initCodeHash = secondaryInitHash;
            factory = sushiFactory;
        }

        amountOut = fromAmount;
        for (uint256 i = 0; i < path.length - 1; ) {
            {
                address fromToken = path[i];
                address toToken = path[i + 1];

                pairs[i] = _getPair(fromToken, toToken, initCodeHash, factory);
                (uint256 reserveA, uint256 reserveB, ) = IUniswapPair(pairs[i])
                    .getReserves();

                if (fromToken > toToken)
                    (reserveA, reserveB) = (reserveB, reserveA);

                amounts[i] =
                    ((amountOut * 997) * reserveB) /
                    ((reserveA * 1000) + (amountOut * 997));
                amountOut = amounts[i];
            }

            unchecked {
                i++;
            }
        }

        if (amounts[amounts.length - 1] < toAmountMin)
            revert InvalidMinOut(amounts[amounts.length - 1]);

        SafeTransferLib.safeTransfer(ERC20(path[0]), pairs[0], fromAmount);

        return _swap(path, pairs, amounts);
    }

    function _getPair(
        address tokenA,
        address tokenB,
        bytes memory initCodeHash,
        address factory
    ) internal pure returns (address pair) {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        pair = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(
                            hex"ff",
                            factory,
                            keccak256(abi.encodePacked(tokenA, tokenB)),
                            initCodeHash
                        )
                    )
                )
            )
        );
    }

    function _swap(
        address[] memory path,
        address[] memory pairs,
        uint256[] memory amounts
    ) internal returns (uint256) {
        bool zeroForOne = path[0] < path[1];
        if (pairs.length > 1) {
            IUniswapPair(pairs[0]).swap(
                zeroForOne ? 0 : amounts[0],
                zeroForOne ? amounts[0] : 0,
                pairs[1],
                ""
            );
            for (uint256 i = 1; i < pairs.length - 1; ) {
                zeroForOne = path[i] < path[i + 1];
                IUniswapPair(pairs[i]).swap(
                    zeroForOne ? 0 : amounts[i],
                    zeroForOne ? amounts[i] : 0,
                    pairs[i + 1],
                    ""
                );
                unchecked {
                    i++;
                }
            }
            zeroForOne = path[path.length - 2] < path[path.length - 1];
            IUniswapPair(pairs[pairs.length - 1]).swap(
                zeroForOne ? 0 : amounts[pairs.length - 1],
                zeroForOne ? amounts[pairs.length - 1] : 0,
                address(this),
                ""
            );
        } else {
            IUniswapPair(pairs[0]).swap(
                zeroForOne ? 0 : amounts[0],
                zeroForOne ? amounts[0] : 0,
                address(this),
                ""
            );
        }

        return amounts[amounts.length - 1];
    }
}

// File: src/bridgeZaps/dexHelpers/uniswapV3.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import {ERC20} from "lib/solmate/src/tokens/ERC20.sol";
import {SafeTransferLib} from "lib/solmate/src/utils/SafeTransferLib.sol";
import {BytesLib} from "../../libraries/BytesLib.sol";
import {IUniswapV3Pool} from "../../interfaces/dexes/IUniswapV3Pool.sol";
import {IUniswapV3Callback} from "../../interfaces/dexes/IUniswapV3Callback.sol";
import {IEarthquake} from "../../interfaces/IEarthquake.sol";
import {IErrors} from "../../interfaces/IErrors.sol";

contract UniswapV3Swapper is IErrors, IUniswapV3Callback {
    using SafeTransferLib for ERC20;
    using BytesLib for bytes;
    address public immutable uniswapV3Factory;
    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant _MIN_SQRT_RATIO = 4295128740;

    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant _MAX_SQRT_RATIO =
        1461446703485210103287273052203988822378723970341;
    bytes32 internal constant _POOL_INIT_CODE_HASH =
        0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;

    constructor(address _uniswapV3Factory) {
        if (_uniswapV3Factory == address(0)) revert InvalidInput();
        uniswapV3Factory = _uniswapV3Factory;
    }

    function _swapUniswapV3(
        uint256 fromAmount,
        bytes memory payload
    ) internal returns (uint256 amountOut) {
        (address[] memory path, uint24[] memory fee, uint256 toAmountMin) = abi
            .decode(payload, (address[], uint24[], uint256));
        if (path.length > 2) {
            amountOut = _executeSwap(path[0], path[1], fromAmount, fee[0]);
            for (uint256 i = 1; i < path.length - 2; ) {
                amountOut = _executeSwap(
                    path[i],
                    path[i + 1],
                    amountOut,
                    fee[i]
                );
                unchecked {
                    i++;
                }
            }
            amountOut = _executeSwap(
                path[path.length - 2],
                path[path.length - 1],
                amountOut,
                fee[path.length - 2]
            );
        } else {
            amountOut = _executeSwap(path[0], path[1], fromAmount, fee[0]);
        }

        if (amountOut < toAmountMin) revert InvalidMinOut(amountOut);
    }

    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata _data
    ) external override {
        require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
        (address tokenIn, address tokenOut, uint24 fee) = decodePool(_data);

        if (msg.sender != getPool(tokenIn, tokenOut, fee))
            revert InvalidCaller();

        SafeTransferLib.safeTransfer(
            ERC20(tokenIn),
            msg.sender,
            amount0Delta > 0 ? uint256(amount0Delta) : uint256(amount1Delta)
        );
    }

    function _executeSwap(
        address tokenIn,
        address tokenOut,
        uint256 fromAmount,
        uint24 fee
    ) internal returns (uint256) {
        bool zeroForOne = tokenIn < tokenOut;

        if (zeroForOne) {
            (, int256 amountOut) = IUniswapV3Pool(
                getPool(tokenIn, tokenOut, fee)
            ).swap(
                    address(this),
                    zeroForOne,
                    int256(fromAmount),
                    _MIN_SQRT_RATIO,
                    abi.encodePacked(tokenIn, fee, tokenOut)
                );
            return uint256(-amountOut);
        } else {
            (int256 amountOut, ) = IUniswapV3Pool(
                getPool(tokenIn, tokenOut, fee)
            ).swap(
                    address(this),
                    zeroForOne,
                    int256(fromAmount),
                    _MAX_SQRT_RATIO,
                    abi.encodePacked(tokenIn, fee, tokenOut)
                );
            return uint256(-amountOut);
        }
    }

    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) internal view returns (address pool) {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        pool = address(
            uint160(
                uint256(
                    keccak256(
                        abi.encodePacked(
                            hex"ff",
                            uniswapV3Factory,
                            keccak256(abi.encode(tokenA, tokenB, fee)),
                            _POOL_INIT_CODE_HASH
                        )
                    )
                )
            )
        );
    }

    function decodePool(
        bytes memory path
    ) internal pure returns (address tokenA, address tokenB, uint24 fee) {
        tokenA = path.toAddress(0);
        fee = path.toUint24(20);
        tokenB = path.toAddress(23);
    }
}

// File: src/bridgeZaps/dexHelpers/curve.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import {ERC20} from "lib/solmate/src/tokens/ERC20.sol";
import {SafeTransferLib} from "lib/solmate/src/utils/SafeTransferLib.sol";
import {IErrors} from "../../interfaces/IErrors.sol";
import {ICurvePair} from "../../interfaces/dexes/ICurvePair.sol";

contract CurveSwapper is IErrors {
    using SafeTransferLib for ERC20;
    address payable immutable wethAddress;

    constructor(address _wethAddress) {
        if (_wethAddress == address(0)) revert InvalidInput();
        wethAddress = payable(_wethAddress);
    }

    function _swapWithCurve(
        bytes calldata payload
    ) internal returns (uint256 amountOut) {
        // TODO: Need to find most efficient way to get the bytes
        bytes1 swapType = abi.decode(payload, (bytes1));
        if (swapType == 0x01) {
            (
                ,
                address fromToken,
                address toToken,
                int128 i,
                int128 j,
                address pool,
                uint256 fromAmount,
                uint256 toAmountMin
            ) = abi.decode(
                    payload,
                    (
                        bytes1,
                        address,
                        address,
                        int128,
                        int128,
                        address,
                        uint256,
                        uint256
                    )
                );
            amountOut = _swap(
                fromToken,
                toToken,
                pool,
                i,
                j,
                fromAmount,
                toAmountMin
            );
            if (amountOut == 0) revert InvalidOutput();
        } else if (swapType == 0x02) {
            (
                ,
                address fromToken,
                address toToken,
                uint256 i,
                uint256 j,
                address pool,
                uint256 fromAmount,
                uint256 toAmountIn
            ) = abi.decode(
                    payload,
                    (
                        bytes1,
                        address,
                        address,
                        uint256,
                        uint256,
                        address,
                        uint256,
                        uint256
                    )
                );
            amountOut = _swapEth(
                fromToken,
                toToken,
                pool,
                i,
                j,
                fromAmount,
                toAmountIn
            );
            if (amountOut == 0) revert InvalidOutput();
        } else if (swapType == 0x03) {
            return zapInMulti(payload);
        } else revert InvalidInput();
    }

    // NOTE: Logic has to be abstract to avoid stack too deep errors
    function zapInMulti(bytes calldata payload) internal returns (uint256) {
        (
            ,
            address[] memory path,
            address[] memory pools,
            uint256[] memory iValues,
            uint256[] memory jValues,
            uint256 fromAmount,
            uint256 toAmountMin
        ) = abi.decode(
                payload,
                (
                    bytes1,
                    address[],
                    address[],
                    uint256[],
                    uint256[],
                    uint256,
                    uint256
                )
            );
        uint256 amountOut = _multiSwap(
            path,
            pools,
            iValues,
            jValues,
            fromAmount,
            toAmountMin
        );
        if (amountOut == 0) revert InvalidOutput();
        return amountOut;
    }

    function _multiSwap(
        address[] memory path,
        address[] memory pools,
        uint256[] memory iValues,
        uint256[] memory jValues,
        uint256 fromAmount,
        uint256 toAmountMin
    ) internal returns (uint256 amountOut) {
        amountOut = fromAmount;
        for (uint256 i = 0; i < pools.length; ) {
            if (path[i + 1] != address(0)) {
                amountOut = _swap(
                    path[i],
                    path[i + 1],
                    pools[i],
                    int128(int256(iValues[i])),
                    int128(int256(jValues[i])),
                    amountOut,
                    i == pools.length - 1 ? toAmountMin : 0
                );
            } else {
                amountOut = _swapEth(
                    path[i],
                    wethAddress,
                    pools[i],
                    iValues[i],
                    jValues[i],
                    amountOut,
                    i == pools.length - 1 ? toAmountMin : 0
                );
            }
            unchecked {
                i++;
            }
        }
    }

    function _swap(
        address fromToken,
        address toToken,
        address pool,
        int128 i,
        int128 j,
        uint256 fromAmount,
        uint256 toAmountIn
    ) private returns (uint256) {
        ERC20(fromToken).safeApprove(pool, fromAmount);
        uint256 cachedBalance = ERC20(toToken).balanceOf(address(this));

        ICurvePair(pool).exchange(i, j, fromAmount, toAmountIn);
        fromAmount = ERC20(toToken).balanceOf(address(this)) - cachedBalance;
        return fromAmount;
    }

    function _swapEth(
        address fromToken,
        address toToken,
        address pool,
        uint256 i,
        uint256 j,
        uint256 fromAmount,
        uint256 toAmountIn
    ) private returns (uint256) {
        ERC20(fromToken).safeApprove(pool, fromAmount);
        uint256 cachedBalance = ERC20(toToken).balanceOf(address(this));

        ICurvePair(pool).exchange(i, j, fromAmount, toAmountIn, false);
        fromAmount = ERC20(toToken).balanceOf(address(this)) - cachedBalance;
        return fromAmount;
    }
}

// File: src/interfaces/dexes/IUniswapPair.sol



pragma solidity 0.8.18;

interface IUniswapPair {
    function token0() external view returns (address);

    function token1() external view returns (address);

    function getReserves()
        external
        view
        returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);

    function swap(
        uint256 amount0Out,
        uint256 amount1Out,
        address to,
        bytes calldata data
    ) external;

    function getAmountOut(
        uint256 amountIn,
        address tokenIn
    ) external view returns (uint256 amountOut);
}

// File: src/interfaces/IEarthquake.sol



pragma solidity 0.8.18;

interface IEarthquake {
    function asset() external view returns (address asset);

    function deposit(uint256 pid, uint256 amount, address to) external;

    function depositETH(uint256 pid, address to) external payable;

    function withdraw(
        uint256 id,
        uint256 assets,
        address receiver,
        address owner
    ) external returns (uint256 shares);

    // TODO: Remove
    function balanceOf(
        address account,
        uint256 id
    ) external view returns (uint256);
}

// File: src/libraries/BytesLib.sol



// SPDX-License-Identifier: MIT

/// @title Library for Bytes Manipulation
pragma solidity ^0.8.9;

library BytesLib {
    function toAddress(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (address tempAddress) {
        assembly {
            tempAddress := mload(add(add(_bytes, 0x14), _start))
        }
    }

    function toUint24(
        bytes memory _bytes,
        uint256 _start
    ) internal pure returns (uint24 amount) {
        assembly {
            amount := mload(add(add(_bytes, 0x3), _start))
        }
    }

    /// @param _bytes The bytes input
    /// @param _start The start index of the slice
    /// @param _length The length of the slice
    function sliceBytes(
        bytes memory _bytes,
        uint256 _start,
        uint256 _length
    ) internal pure returns (bytes memory slicedBytes) {
        assembly {
            slicedBytes := mload(0x40)

            let lengthmod := and(_length, 31)

            let mc := add(
                add(slicedBytes, lengthmod),
                mul(0x20, iszero(lengthmod))
            )
            let end := add(mc, _length)

            for {
                let cc := add(
                    add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))),
                    _start
                )
            } lt(mc, end) {
                mc := add(mc, 0x20)
                cc := add(cc, 0x20)
            } {
                mstore(mc, mload(cc))
            }

            mstore(slicedBytes, _length)
            mstore(0x40, and(add(mc, 31), not(31)))
        }
        return slicedBytes;
    }
}

// File: src/interfaces/dexes/IUniswapV3Pool.sol



pragma solidity 0.8.18;

interface IUniswapV3Pool {
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

// File: src/interfaces/dexes/IUniswapV3Callback.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3Callback {
    /// @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;
}

// File: src/interfaces/dexes/ICurvePair.sol



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

interface ICurvePair {
    function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external;

    function exchange(
        uint256 i,
        uint256 j,
        uint256 dx,
        uint256 min_dy,
        bool use_eth
    ) external payable;

    function coins(uint256 i) external view returns (address);
}