// File: @openzeppelin/contracts/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);

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. 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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/security/Pausable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

// File: @openzeppelin/contracts/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;
    }
}

// File: contracts/interfaces/Permit2/IAllowanceTransfer.sol



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

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

/// @title AllowanceTransfer
/// @notice Handles ERC20 token permissions through signature based allowance setting and ERC20 token transfers by checking allowed amounts
/// @dev Requires user's token approval on the Permit2 contract
interface IAllowanceTransfer is IEIP712 {
    /// @notice Thrown when an allowance on a token has expired.
    /// @param deadline The timestamp at which the allowed amount is no longer valid
    error AllowanceExpired(uint256 deadline);

    /// @notice Thrown when an allowance on a token has been depleted.
    /// @param amount The maximum amount allowed
    error InsufficientAllowance(uint256 amount);

    /// @notice Thrown when too many nonces are invalidated.
    error ExcessiveInvalidation();

    /// @notice Emits an event when the owner successfully invalidates an ordered nonce.
    event NonceInvalidation(address indexed owner, address indexed token, address indexed spender, uint48 newNonce, uint48 oldNonce);

    /// @notice Emits an event when the owner successfully sets permissions on a token for the spender.
    event Approval(address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration);

    /// @notice Emits an event when the owner successfully sets permissions using a permit signature on a token for the spender.
    event Permit(address indexed owner, address indexed token, address indexed spender, uint160 amount, uint48 expiration, uint48 nonce);

    /// @notice Emits an event when the owner sets the allowance back to 0 with the lockdown function.
    event Lockdown(address indexed owner, address token, address spender);

    /// @notice The permit data for a token
    struct PermitDetails {
        // ERC20 token address
        address token;
        // the maximum amount allowed to spend
        uint160 amount;
        // timestamp at which a spender's token allowances become invalid
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice The permit message signed for a single token allowance
    struct PermitSingle {
        // the permit data for a single token alownce
        PermitDetails details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The permit message signed for multiple token allowances
    struct PermitBatch {
        // the permit data for multiple token allowances
        PermitDetails[] details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }

    /// @notice The saved permissions
    /// @dev This info is saved per owner, per token, per spender and all signed over in the permit message
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    struct PackedAllowance {
        // amount allowed
        uint160 amount;
        // permission expiry
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    /// @notice A token spender pair.
    struct TokenSpenderPair {
        // the token the spender is approved
        address token;
        // the spender address
        address spender;
    }

    /// @notice Details for a token transfer.
    struct AllowanceTransferDetails {
        // the owner of the token
        address from;
        // the recipient of the token
        address to;
        // the amount of the token
        uint160 amount;
        // the token to be transferred
        address token;
    }

    /// @notice A mapping from owner address to token address to spender address to PackedAllowance struct, which contains details and conditions of the approval.
    /// @notice The mapping is indexed in the above order see: allowance[ownerAddress][tokenAddress][spenderAddress]
    /// @dev The packed slot holds the allowed amount, expiration at which the allowed amount is no longer valid, and current nonce thats updated on any signature based approvals.
    function allowance(address user, address token, address spender) external view returns (uint160 amount, uint48 expiration, uint48 nonce);

    /// @notice Approves the spender to use up to amount of the specified token up until the expiration
    /// @param token The token to approve
    /// @param spender The spender address to approve
    /// @param amount The approved amount of the token
    /// @param expiration The timestamp at which the approval is no longer valid
    /// @dev The packed allowance also holds a nonce, which will stay unchanged in approve
    /// @dev Setting amount to type(uint160).max sets an unlimited approval
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;

    /// @notice Permit a spender to a given amount of the owners token via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitSingle Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;

    /// @notice Permit a spender to the signed amounts of the owners tokens via the owner's EIP-712 signature
    /// @dev May fail if the owner's nonce was invalidated in-flight by invalidateNonce
    /// @param owner The owner of the tokens being approved
    /// @param permitBatch Data signed over by the owner specifying the terms of approval
    /// @param signature The owner's signature over the permit data
    function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external;

    /// @notice Transfer approved tokens from one address to another
    /// @param from The address to transfer from
    /// @param to The address of the recipient
    /// @param amount The amount of the token to transfer
    /// @param token The token address to transfer
    /// @dev Requires the from address to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(address from, address to, uint160 amount, address token) external;

    /// @notice Transfer approved tokens in a batch
    /// @param transferDetails Array of owners, recipients, amounts, and tokens for the transfers
    /// @dev Requires the from addresses to have approved at least the desired amount
    /// of tokens to msg.sender.
    function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external;

    /// @notice Enables performing a "lockdown" of the sender's Permit2 identity
    /// by batch revoking approvals
    /// @param approvals Array of approvals to revoke.
    function lockdown(TokenSpenderPair[] calldata approvals) external;

    /// @notice Invalidate nonces for a given (token, spender) pair
    /// @param token The token to invalidate nonces for
    /// @param spender The spender to invalidate nonces for
    /// @param newNonce The new nonce to set. Invalidates all nonces less than it.
    /// @dev Can't invalidate more than 2**16 nonces per transaction.
    function invalidateNonces(address token, address spender, uint48 newNonce) external;
}

// File: contracts/interfaces/Permit2/IEIP712.sol



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

interface IEIP712 {
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// File: contracts/interfaces/Permit2/IPermit2.sol



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

import { ISignatureTransfer } from "./ISignatureTransfer.sol";
import { IAllowanceTransfer } from "./IAllowanceTransfer.sol";

/// @notice Permit2 handles signature-based transfers in SignatureTransfer and allowance-based transfers in AllowanceTransfer.
/// @dev Users must approve Permit2 before calling any of the transfer functions.
interface IPermit2 is ISignatureTransfer, IAllowanceTransfer {
    // IPermit2 unifies the two interfaces so users have maximal flexibility with their approval.
}

// File: contracts/interfaces/Permit2/ISignatureTransfer.sol



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

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

/// @title SignatureTransfer
/// @notice Handles ERC20 token transfers through signature based actions
/// @dev Requires user's token approval on the Permit2 contract
interface ISignatureTransfer is IEIP712 {
    /// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
    /// @param maxAmount The maximum amount a spender can request to transfer
    error InvalidAmount(uint256 maxAmount);

    /// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
    /// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
    error LengthMismatch();

    /// @notice Emits an event when the owner successfully invalidates an unordered nonce.
    event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);

    /// @notice The token and amount details for a transfer signed in the permit transfer signature
    struct TokenPermissions {
        // ERC20 token address
        address token;
        // the maximum amount that can be spent
        uint256 amount;
    }

    /// @notice The signed permit message for a single token transfer
    struct PermitTransferFrom {
        TokenPermissions permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice Specifies the recipient address and amount for batched transfers.
    /// @dev Recipients and amounts correspond to the index of the signed token permissions array.
    /// @dev Reverts if the requested amount is greater than the permitted signed amount.
    struct SignatureTransferDetails {
        // recipient address
        address to;
        // spender requested amount
        uint256 requestedAmount;
    }

    /// @notice Used to reconstruct the signed permit message for multiple token transfers
    /// @dev Do not need to pass in spender address as it is required that it is msg.sender
    /// @dev Note that a user still signs over a spender address
    struct PermitBatchTransferFrom {
        // the tokens and corresponding amounts permitted for a transfer
        TokenPermissions[] permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
    /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
    /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
    /// @dev It returns a uint256 bitmap
    /// @dev The index, or wordPosition is capped at type(uint248).max
    function nonceBitmap(address, uint256) external view returns (uint256);

    /// @notice Transfers a token using a signed permit message
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers a token using a signed permit message
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Invalidates the bits specified in mask for the bitmap at the word position
    /// @dev The wordPos is maxed at type(uint248).max
    /// @param wordPos A number to index the nonceBitmap at
    /// @param mask A bitmap masked against msg.sender's current bitmap at the word position
    function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
}

// File: contracts/interfaces/Stargate/IStargateReceiver.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

interface IStargateReceiver {
    function sgReceive(uint16 _chainId, bytes memory _srcAddress, uint256 _nonce, address _token, uint256 amountLD, bytes memory payload) external;
}

// File: contracts/interfaces/Stargate/IStargateRouter.sol



// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

interface IStargateRouter {
    struct lzTxObj {
        uint256 dstGasForCall;
        uint256 dstNativeAmount;
        bytes dstNativeAddr;
    }

    function addLiquidity(uint256 _poolId, uint256 _amountLD, address _to) external;

    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 redeemRemote(
        uint16 _dstChainId,
        uint256 _srcPoolId,
        uint256 _dstPoolId,
        address payable _refundAddress,
        uint256 _amountLP,
        uint256 _minAmountLD,
        bytes calldata _to,
        lzTxObj memory _lzTxParams
    ) external payable;

    function instantRedeemLocal(uint16 _srcPoolId, uint256 _amountLP, address _to) external returns (uint256);

    function redeemLocal(
        uint16 _dstChainId,
        uint256 _srcPoolId,
        uint256 _dstPoolId,
        address payable _refundAddress,
        uint256 _amountLP,
        bytes calldata _to,
        lzTxObj memory _lzTxParams
    ) external payable;

    function sendCredits(uint16 _dstChainId, uint256 _srcPoolId, uint256 _dstPoolId, address payable _refundAddress) external payable;

    function quoteLayerZeroFee(
        uint16 _dstChainId,
        uint8 _functionType,
        bytes calldata _toAddress,
        bytes calldata _transferAndCallPayload,
        lzTxObj memory _lzTxParams
    ) external view returns (uint256, uint256);

    function bridge() external view returns (address);
}

// File: contracts/interfaces/Uniswap/IMulticall.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` should not be trusted for any method callable from multicall.
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}

// File: contracts/interfaces/Uniswap/IMulticallExtended.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

import "./IMulticall.sol";

/// @title MulticallExtended interface
/// @notice Enables calling multiple methods in a single call to the contract with optional validation
interface IMulticallExtended is IMulticall {
    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` should not be trusted for any method callable from multicall.
    /// @param deadline The time by which this function must be called before failing
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(uint256 deadline, bytes[] calldata data) external payable returns (bytes[] memory results);

    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` should not be trusted for any method callable from multicall.
    /// @param previousBlockhash The expected parent blockHash
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(bytes32 previousBlockhash, bytes[] calldata data) external payable returns (bytes[] memory results);
}

// File: contracts/interfaces/Uniswap/ISwapRouter02.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

import "./IV2SwapRouter.sol";
import "./IV3SwapRouter.sol";
import "./IMulticallExtended.sol";

/// @title Router token swapping functionality
interface ISwapRouter02 is IV2SwapRouter, IV3SwapRouter, IMulticallExtended {

}

// File: contracts/interfaces/Uniswap/IUniswapV3SwapCallback.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

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

// File: contracts/interfaces/Uniswap/IV2SwapRouter.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V2
interface IV2SwapRouter {
    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
    /// and swap the entire amount, enabling contracts to send tokens before calling this function.
    /// @param amountIn The amount of token to swap
    /// @param amountOutMin The minimum amount of output that must be received
    /// @param path The ordered list of tokens to swap through
    /// @param to The recipient address
    /// @return amountOut The amount of the received token
    function swapExactTokensForTokens(uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to) external payable returns (uint256 amountOut);

    /// @notice Swaps as little as possible of one token for an exact amount of another token
    /// @param amountOut The amount of token to swap for
    /// @param amountInMax The maximum amount of input that the caller will pay
    /// @param path The ordered list of tokens to swap through
    /// @param to The recipient address
    /// @return amountIn The amount of token to pay
    function swapTokensForExactTokens(uint256 amountOut, uint256 amountInMax, address[] calldata path, address to) external payable returns (uint256 amountIn);
}

// File: contracts/interfaces/Uniswap/IV3SwapRouter.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

import "./IUniswapV3SwapCallback.sol";

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

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
    /// and swap the entire amount, enabling contracts to send tokens before calling this function.
    /// @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 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
    /// and swap the entire amount, enabling contracts to send tokens before calling this function.
    /// @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 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// that may remain in the router after the swap.
    /// @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 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// that may remain in the router after the swap.
    /// @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: contracts/interfaces/Uniswap/IWETH9.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @title Interface for WETH9
interface IWETH9 is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}

// File: contracts/libraries/TransferHelper.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

library TransferHelper {
    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors with 'STF' if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(address token, address from, address to, uint256 value) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), "STF");
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors with ST if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(address token, address to, uint256 value) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), "ST");
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors with 'SA' if transfer fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(address token, address to, uint256 value) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), "SA");
    }

    /// @notice Transfers ETH to the recipient address
    /// @dev Fails with `STE`
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{ value: value }(new bytes(0));
        require(success, "STE");
    }
}

// File: contracts/NativeWrapper.sol



// SPDX-License-Identifier: UNLICENSED
// Zaap.exchange Contracts (NativeWrapper.sol)
pragma solidity ^0.8.19;

import { IWETH9 } from "./interfaces/Uniswap/IWETH9.sol";

abstract contract NativeWrapper {
    address public immutable NATIVE_TOKEN_ADDRESS = address(0x0000000000000000000000000000000000455448);

    IWETH9 public immutable wETH9;

    constructor(IWETH9 wETH9_) {
        wETH9 = wETH9_;
    }
}

// File: contracts/Swapper.sol



// SPDX-License-Identifier: UNLICENSED
// Zaap.exchange Contracts (Swapper.sol)
pragma solidity ^0.8.19;

import { IWETH9 } from "./interfaces/Uniswap/IWETH9.sol";
import { ISwapRouter02 } from "./interfaces/Uniswap/ISwapRouter02.sol";
import { IV3SwapRouter } from "./interfaces/Uniswap/IV3SwapRouter.sol";

import { TransferHelper } from "./libraries/TransferHelper.sol";

abstract contract Swapper {
    ISwapRouter02 public immutable swapRouter02;

    enum RouterVersion {
        v2,
        v3
    }

    struct PathPart {
        address tokenAddress;
        uint24 poolFee;
    }

    struct SwapParams {
        RouterVersion routerVersion;
        uint256 amountIn;
        PathPart[] pathParts;
        uint256 amountOutMin;
    }

    constructor(address swapRouter02Address_) {
        swapRouter02 = ISwapRouter02(swapRouter02Address_);
    }

    function _swapExact(
        uint256 totalAmountIn,
        SwapParams[] memory swapsParams,
        address fromTokenAddress,
        address toTokenAddress,
        bool revertOnError
    ) internal returns (uint256 totalAmountOut, bool errored) {
        totalAmountOut = 0;
        errored = false;

        TransferHelper.safeApprove(fromTokenAddress, address(swapRouter02), totalAmountIn);

        // Ensuring proportional distribution
        uint256 expectedTotalAmountIn = 0;
        for (uint8 swapParamIndex = 0; swapParamIndex < swapsParams.length; ) {
            SwapParams memory swapParams = swapsParams[swapParamIndex];
            expectedTotalAmountIn += swapParams.amountIn;

            unchecked {
                swapParamIndex++;
            }
        }
        uint256 proportionFactor = (totalAmountIn * 1e18) / expectedTotalAmountIn;

        for (uint8 swapParamIndex = 0; swapParamIndex < swapsParams.length; ) {
            SwapParams memory swapParams = swapsParams[swapParamIndex];
            PathPart[] memory pathParts = swapParams.pathParts;

            PathPart memory firstPathPart = pathParts[0];
            if (firstPathPart.tokenAddress != fromTokenAddress) {
                if (revertOnError) {
                    revert("Swapper: `firstPathPart.tokenAddress` != `fromTokenAddress`");
                } else {
                    errored = true;
                    break;
                }
            }

            PathPart memory lastPathPart = pathParts[pathParts.length - 1];
            if (lastPathPart.tokenAddress != toTokenAddress) {
                if (revertOnError) {
                    revert("Swapper: `lastPathPart.tokenAddress` != `toTokenAddress`");
                } else {
                    errored = true;
                    break;
                }
            }

            uint256 amountIn = (swapParams.amountIn * proportionFactor) / 1e18;
            uint256 amountOutMin = (swapParams.amountOutMin * proportionFactor) / 1e18;

            if (swapParams.routerVersion == RouterVersion.v3) {
                bytes memory pathParam;
                for (uint8 pathPartIndex = 0; pathPartIndex < swapParams.pathParts.length; ) {
                    PathPart memory pathPart = swapParams.pathParts[pathPartIndex];
                    if (pathPart.poolFee == uint24(0)) {
                        pathParam = abi.encodePacked(pathParam, pathPart.tokenAddress);
                    } else {
                        pathParam = abi.encodePacked(pathParam, pathPart.poolFee, pathPart.tokenAddress);
                    }

                    unchecked {
                        pathPartIndex++;
                    }
                }

                IV3SwapRouter.ExactInputParams memory inputParams = IV3SwapRouter.ExactInputParams({
                    path: pathParam,
                    recipient: address(this),
                    amountIn: amountIn,
                    amountOutMinimum: amountOutMin
                });

                try swapRouter02.exactInput(inputParams) returns (uint256 amountOut) {
                    totalAmountOut += amountOut;
                } catch Error(string memory reason) {
                    if (revertOnError) {
                        revert(reason);
                    } else {
                        errored = true;
                        break;
                    }
                }
            } else if (swapParams.routerVersion == RouterVersion.v2) {
                address[] memory pathParam = new address[](swapParams.pathParts.length);
                for (uint8 pathPartIndex = 0; pathPartIndex < swapParams.pathParts.length; ) {
                    PathPart memory pathPart = swapParams.pathParts[pathPartIndex];
                    pathParam[pathPartIndex] = pathPart.tokenAddress;

                    unchecked {
                        pathPartIndex++;
                    }
                }

                try swapRouter02.swapExactTokensForTokens(amountIn, amountOutMin, pathParam, address(this)) returns (uint256 amountOut) {
                    totalAmountOut += amountOut;
                } catch Error(string memory reason) {
                    if (revertOnError) {
                        revert(reason);
                    } else {
                        errored = true;
                        break;
                    }
                }
            } else {
                revert("Swapper: `swapParams.routerVersion` must be either 0 or 1");
            }

            unchecked {
                swapParamIndex++;
            }
        }
        if (revertOnError) require(totalAmountOut > 0, "Swapper: `totalAmountOut` must be > 0");
    }
}

// File: contracts/Zaap.sol



// SPDX-License-Identifier: UNLICENSED
// Zaap.exchange Contracts (Zaap.sol)
pragma solidity ^0.8.19;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/security/Pausable.sol";

import { NativeWrapper } from "./NativeWrapper.sol";
import { Swapper } from "./Swapper.sol";
import { ZaapIn } from "./ZaapIn.sol";
import { ZaapOut } from "./ZaapOut.sol";

import { IWETH9 } from "./interfaces/Uniswap/IWETH9.sol";
import { IStargateRouter } from "./interfaces/Stargate/IStargateRouter.sol";
import { IPermit2 } from "./interfaces/Permit2/IPermit2.sol";
import { IAllowanceTransfer } from "./interfaces/Permit2/IAllowanceTransfer.sol";

contract Zaap is NativeWrapper, Swapper, ZaapIn, ZaapOut {
    constructor(
        IWETH9 wETH9_,
        address swapRouter02Address_,
        IStargateRouter stargateRouter_,
        IPermit2 permit2_
    ) NativeWrapper(wETH9_) Swapper(swapRouter02Address_) ZaapIn(stargateRouter_, permit2_) ZaapOut(address(stargateRouter_)) {}
}

// File: contracts/ZaapIn.sol



// SPDX-License-Identifier: UNLICENSED
// Zaap.exchange Contracts (ZaapIn.sol)
pragma solidity ^0.8.19;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/security/Pausable.sol";

import { NativeWrapper } from "./NativeWrapper.sol";
import { Swapper } from "./Swapper.sol";

import { IWETH9 } from "./interfaces/Uniswap/IWETH9.sol";
import { IStargateRouter } from "./interfaces/Stargate/IStargateRouter.sol";
import { IPermit2 } from "./interfaces/Permit2/IPermit2.sol";
import { IAllowanceTransfer } from "./interfaces/Permit2/IAllowanceTransfer.sol";

import { TransferHelper } from "./libraries/TransferHelper.sol";

abstract contract ZaapIn is Ownable, Pausable, NativeWrapper, Swapper {
    IStargateRouter public immutable stargateRouter;
    IPermit2 public immutable permit2;

    address public treasuryAddress;
    uint8 public feeBps;

    struct PartnerConfig {
        address partnerAddress;
        uint8 percentShare;
    }
    mapping(string => PartnerConfig) private partnerIdToPartnerConfig;

    event ZaapedIn(
        address srcSenderAddress,
        address indexed srcTokenAddress,
        uint srcTokenAmountIn,
        uint16 srcPoolId,
        address indexed bridgeTokenAddress,
        uint256 bridgeAmount,
        uint16 dstChainId,
        uint16 dstPoolId,
        address dstZaapAddress,
        address indexed dstTokenAddress,
        address dstRecipientAddress,
        string partnerId
    );

    constructor(IStargateRouter stargateRouter_, IPermit2 permit2_) {
        stargateRouter = stargateRouter_;
        permit2 = permit2_;
    }

    function swap(
        address srcTokenAddress,
        uint160 srcTokenAmountIn,
        SwapParams[] calldata srcSwapsParams,
        uint16 srcPoolId,
        address bridgeTokenAddress,
        uint256 bridgeAmountOutMin,
        uint16 dstChainId,
        uint16 dstPoolId,
        address dstZaapAddress,
        address dstTokenAddress,
        SwapParams[] calldata dstSwapsParams,
        address dstRecipientAddress,
        IAllowanceTransfer.PermitSingle calldata permitSingle,
        bytes calldata signature,
        IStargateRouter.lzTxObj calldata lzTxObj,
        uint256 deadline,
        string calldata partnerId
    ) external payable whenNotPaused {
        require(srcTokenAmountIn > 0, "ZaapIn: `srcTokenAmountIn` must be > 0");
        if (deadline > 0) {
            require(deadline >= block.timestamp, "ZaapIn: `deadline` must be >= block.timestamp");
        }

        bool srcTokenIsNative = srcTokenAddress == NATIVE_TOKEN_ADDRESS;

        if (!srcTokenIsNative && permitSingle.spender == address(this)) {
            permit2.permit(msg.sender, permitSingle, signature);
        }
        if (!srcTokenIsNative) {
            permit2.transferFrom(msg.sender, address(this), srcTokenAmountIn, srcTokenAddress);
        }

        uint256 bridgeAmount = 0;
        if (srcTokenAddress != bridgeTokenAddress) {
            require(srcSwapsParams.length > 0, "ZaapIn: `srcSwapsParams` must not be empty if `srcTokenAddress` != `bridgeTokenAddress`");

            // Wrapping if needed
            if (srcTokenIsNative) {
                require(msg.value >= srcTokenAmountIn, "ZaapIn: `msg.value` must be >= `srcTokenAmountIn`");
                wETH9.deposit{ value: srcTokenAmountIn }();
            }

            (uint256 totalAmountOut, bool errored) = _swapExact(
                srcTokenAmountIn,
                srcSwapsParams,
                srcTokenIsNative ? address(wETH9) : srcTokenAddress,
                bridgeTokenAddress,
                true
            );
            bridgeAmount = totalAmountOut;
        } else {
            bridgeAmount = srcTokenAmountIn;
        }

        if (feeBps > 0 && treasuryAddress != address(0)) {
            uint256 feeAmount = (bridgeAmount / 10000) * feeBps;
            bridgeAmount -= feeAmount;

            if (bytes(partnerId).length > 0) {
                PartnerConfig memory partnerConfig = partnerIdToPartnerConfig[partnerId];
                if (partnerConfig.partnerAddress != address(0) && partnerConfig.percentShare > 0 && partnerConfig.percentShare <= 100) {
                    uint256 partnerFeeAmount = (feeAmount / 100) * partnerConfig.percentShare;
                    feeAmount -= partnerFeeAmount;
                    TransferHelper.safeTransfer(bridgeTokenAddress, partnerConfig.partnerAddress, partnerFeeAmount);
                }
            }
            if (feeAmount > 0) {
                TransferHelper.safeTransfer(bridgeTokenAddress, treasuryAddress, feeAmount);
            }
        }

        TransferHelper.safeApprove(bridgeTokenAddress, address(stargateRouter), bridgeAmount);

        stargateRouter.swap{ value: srcTokenIsNative ? msg.value - srcTokenAmountIn : msg.value }(
            dstChainId,
            srcPoolId,
            dstPoolId,
            payable(msg.sender),
            bridgeAmount,
            bridgeAmountOutMin,
            lzTxObj,
            abi.encodePacked(dstZaapAddress),
            abi.encode(dstSwapsParams, dstTokenAddress, dstRecipientAddress)
        );

        emit ZaapedIn(
            msg.sender,
            srcTokenAddress,
            srcTokenAmountIn,
            srcPoolId,
            bridgeTokenAddress,
            bridgeAmount,
            dstChainId,
            dstPoolId,
            dstZaapAddress,
            dstTokenAddress,
            dstRecipientAddress,
            partnerId
        );
    }

    function setTreasuryAddress(address treasuryAddress_) external onlyOwner {
        treasuryAddress = treasuryAddress_;
    }

    function setFeeBps(uint8 feeBps_) external onlyOwner {
        require(feeBps_ <= 50, "ZaapIn: `feeBps_` must be <= 50");
        feeBps = feeBps_;
    }

    function setPartnerConfigBatch(string[] calldata partnerIds, address[] calldata partnerAddresses, uint8[] calldata percentShares) external onlyOwner {
        require(
            partnerIds.length == partnerAddresses.length && partnerAddresses.length == percentShares.length,
            "ZaapIn: `partnerIds`, `partnerAddresses` and `percentShares` must have the same length"
        );
        for (uint256 i = 0; i < partnerIds.length; i++) {
            setPartnerConfig(partnerIds[i], partnerAddresses[i], percentShares[i]);
        }
    }

    function setPartnerConfig(string calldata partnerId, address partnerAddress, uint8 percentShare) public onlyOwner {
        require(bytes(partnerId).length > 0, "ZaapIn: `partnerId` must not be empty");
        require(partnerAddress != address(0), "ZaapIn: `partnerAddress` must not be address(0)");
        require(percentShare <= 100, "ZaapIn: `percentShare` must be <= 100");
        partnerIdToPartnerConfig[partnerId] = PartnerConfig(partnerAddress, percentShare);
    }

    function deletePartnerConfig(string calldata partnerId) external onlyOwner {
        require(bytes(partnerId).length > 0, "ZaapIn: `partnerId` must not be empty");
        delete partnerIdToPartnerConfig[partnerId];
    }

    function pauseIn() external virtual onlyOwner {
        _pause();
    }

    function unpauseIn() external virtual onlyOwner {
        _unpause();
    }
}

// File: contracts/ZaapOut.sol



// SPDX-License-Identifier: UNLICENSED
// Zaap.exchange Contracts (ZaapOut.sol)
pragma solidity ^0.8.19;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/security/Pausable.sol";

import { NativeWrapper } from "./NativeWrapper.sol";
import { Swapper } from "./Swapper.sol";

import { IStargateReceiver } from "./interfaces/Stargate/IStargateReceiver.sol";
import { IWETH9 } from "./interfaces/Uniswap/IWETH9.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import { TransferHelper } from "./libraries/TransferHelper.sol";

abstract contract ZaapOut is Ownable, Pausable, NativeWrapper, Swapper, IStargateReceiver {
    address public immutable stargateRouterAddress;

    event ZaapErrored(string reason);
    event ZaapedOut(
        uint16 srcChainId,
        bytes srcAddress,
        uint nonce,
        address bridgeTokenAddress,
        uint bridgeAmountIn,
        address dstTokenAddress,
        uint256 dstTokenAmountOut,
        address dstRecipientAddress
    );

    constructor(address stargateRouterAddress_) {
        stargateRouterAddress = stargateRouterAddress_;
    }

    function sgReceive(
        uint16 srcChainId,
        bytes memory srcAddress,
        uint nonce,
        address bridgeTokenAddress,
        uint bridgeAmountIn,
        bytes memory payload
    ) external whenNotPaused {
        require(msg.sender == address(stargateRouterAddress), "ZaapOut: `msg.sender` must be `stargateRouterAddress`");
        require(bridgeAmountIn > 0, "ZaapOut: `bridgeAmountIn` must be > 0");

        (SwapParams[] memory dstSwapsParams, address dstTokenAddress, address dstRecipientAddress) = abi.decode(payload, (SwapParams[], address, address));

        if (bridgeTokenAddress != dstTokenAddress) {
            bool dstTokenIsNative = dstTokenAddress == NATIVE_TOKEN_ADDRESS;

            if (dstSwapsParams.length > 0) {
                (uint256 totalAmountOut, bool errored) = _swapExact(
                    bridgeAmountIn,
                    dstSwapsParams,
                    bridgeTokenAddress,
                    dstTokenIsNative ? address(wETH9) : dstTokenAddress,
                    false
                );
                if (errored == false) {
                    // Unwrapping if needed
                    if (dstTokenIsNative) {
                        wETH9.withdraw(totalAmountOut);
                        TransferHelper.safeTransferETH(dstRecipientAddress, totalAmountOut);
                    } else {
                        TransferHelper.safeTransfer(dstTokenAddress, dstRecipientAddress, totalAmountOut);
                    }
                    emit ZaapedOut(srcChainId, srcAddress, nonce, bridgeTokenAddress, bridgeAmountIn, dstTokenAddress, totalAmountOut, dstRecipientAddress);
                } else {
                    if (totalAmountOut > 0) {
                        // Unwrapping if needed
                        if (dstTokenIsNative) {
                            wETH9.withdraw(totalAmountOut);
                            TransferHelper.safeTransferETH(dstRecipientAddress, totalAmountOut);
                        } else {
                            TransferHelper.safeTransfer(dstTokenAddress, dstRecipientAddress, totalAmountOut);
                        }
                    }
                    uint256 bridgeAmountInLeft = IERC20(bridgeTokenAddress).balanceOf(address(this));
                    if (bridgeAmountInLeft > 0) {
                        TransferHelper.safeTransfer(bridgeTokenAddress, dstRecipientAddress, bridgeAmountInLeft);
                    }
                    emit ZaapErrored("ZaapOut: `_swap` errored");
                }
            } else {
                TransferHelper.safeTransfer(bridgeTokenAddress, dstRecipientAddress, bridgeAmountIn);
                emit ZaapErrored("ZaapOut: `dstSwapsParams` must not be empty if `bridgeTokenAddress` != `dstTokenAddress`");
            }
        } else {
            TransferHelper.safeTransfer(bridgeTokenAddress, dstRecipientAddress, bridgeAmountIn);
            emit ZaapedOut(srcChainId, srcAddress, nonce, bridgeTokenAddress, bridgeAmountIn, dstTokenAddress, bridgeAmountIn, dstRecipientAddress);
        }
    }

    function pauseOut() external virtual onlyOwner {
        _pause();
    }

    function unpauseOut() external virtual onlyOwner {
        _unpause();
    }

    receive() external payable {}
}