// File: contracts/access/Context.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.1;

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/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.1;

import "./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 anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing 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: contracts/interfaces/IAggregationExecutor.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/// @title Interface for making arbitrary calls during swap
interface IAggregationExecutor {
    /// @notice propagates information about original msg.sender and executes arbitrary data
    function execute(address msgSender) external payable; // 0x4b64e492
}

// File: contracts/interfaces/IAggregationRouterV5.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "./IAggregationExecutor.sol";
import "./IERC20.sol";
import "../libraries/SwapData.sol";

interface IAggregationRouterV5 {
    function swap(
        IAggregationExecutor executor,
        Type.SwapDescription calldata desc,
        bytes calldata permit,
        bytes calldata data
    ) external payable returns (uint256 returnAmount, uint256 spentAmount);
}

// File: contracts/interfaces/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.1;

/**
 * @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: contracts/interfaces/IStargateRouter.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

interface IStargateRouter {
    struct lzTxObj {
        uint256 dstGasForCall;
        uint256 dstNativeAmount;
        bytes dstNativeAddr;
    }

    function quoteLayerZeroFee(
        uint16 _dstChainId,
        uint8 _functionType,
        bytes calldata _toAddress,
        bytes calldata _transferAndCallPayload,
        lzTxObj memory _lzTxParams
    ) external view returns (uint256, uint256);

    function swap(
        uint16 _dstChainId,
        uint256 _srcPoolId,
        uint256 _dstPoolId,
        address payable _refundAddress,
        uint256 _amountLD,
        uint256 _minAmountLD,
        lzTxObj calldata _lzTxParams,
        bytes calldata _to,
        bytes calldata _payload
    ) external payable;
}

// File: contracts/libraries/BytesLib.sol



// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <goncalo.sa@consensys.net>
 * @source: https://github.com/Uniswap/v3-periphery/blob/main/contracts/libraries/BytesLib.sol
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity ^0.8.17;

library BytesLib {
    function slice(
        bytes memory _bytes,
        uint256 _start,
        uint256 _length
    ) internal pure returns (bytes memory) {
        require(_length + 31 >= _length, "slice_overflow");
        require(_start + _length >= _start, "slice_overflow");
        require(_bytes.length >= _start + _length, "slice_outOfBounds");

        bytes memory tempBytes;

        assembly {
            switch iszero(_length)
            case 0 {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                tempBytes := mload(0x40)

                // The first word of the slice result is potentially a partial
                // word read from the original array. To read it, we calculate
                // the length of that partial word and start copying that many
                // bytes into the array. The first word we copy will start with
                // data we don't care about, but the last `lengthmod` bytes will
                // land at the beginning of the contents of the new array. When
                // we're done copying, we overwrite the full first word with
                // the actual length of the slice.
                let lengthmod := and(_length, 31)

                // The multiplication in the next line is necessary
                // because when slicing multiples of 32 bytes (lengthmod == 0)
                // the following copy loop was copying the origin's length
                // and then ending prematurely not copying everything it should.
                let mc := add(
                    add(tempBytes, lengthmod),
                    mul(0x20, iszero(lengthmod))
                )
                let end := add(mc, _length)

                for {
                    // The multiplication in the next line has the same exact purpose
                    // as the one above.
                    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(tempBytes, _length)

                //update free-memory pointer
                //allocating the array padded to 32 bytes like the compiler does now
                mstore(0x40, and(add(mc, 31), not(31)))
            }
            //if we want a zero-length slice let's just return a zero-length array
            default {
                tempBytes := mload(0x40)
                //zero out the 32 bytes slice we are about to return
                //we need to do it because Solidity does not garbage collect
                mstore(tempBytes, 0)

                mstore(0x40, add(tempBytes, 0x20))
            }
        }

        return tempBytes;
    }

    function toAddress(bytes memory _bytes, uint256 _start)
        internal
        pure
        returns (address)
    {
        require(_start + 20 >= _start, "toAddress_overflow");
        require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
        address tempAddress;

        assembly {
            tempAddress := div(
                mload(add(add(_bytes, 0x20), _start)),
                0x1000000000000000000000000
            )
        }

        return tempAddress;
    }

    function toUint24(bytes memory _bytes, uint256 _start)
        internal
        pure
        returns (uint24)
    {
        require(_start + 3 >= _start, "toUint24_overflow");
        require(_bytes.length >= _start + 3, "toUint24_outOfBounds");
        uint24 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x3), _start))
        }

        return tempUint;
    }
}

// File: contracts/libraries/SwapData.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import "../interfaces/IERC20.sol";

library Type {
    struct SwapDescription {
        IERC20 srcToken;
        IERC20 dstToken;
        address payable srcReceiver;
        address payable dstReceiver;
        uint256 amount;
        uint256 minReturnAmount;
        uint256 flags;
    }

    struct StgData {
        uint16 srcChainPoolId;
        uint16 dstChainPoolId;
        uint16 dstChainId;
        uint32 dstChainGasUnit;
        uint256 totalGasFee;
    }

    struct TxData {
        uint32 slippage;
        address receiver;
        uint256 amountIn;
        address dstChainTingMeContract;
    }

    struct PoolData {
        uint16 poolId;
        IERC20 token;
    }
}

// File: contracts/security/Pausable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../access/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: contracts/TingMeSwap.sol



//SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "./interfaces/IERC20.sol";
import "./interfaces/IAggregationRouterV5.sol";
import "./interfaces/IStargateRouter.sol";
import "./access/Ownable.sol";
import "./security/Pausable.sol";
import "./libraries/SwapData.sol";
import "./libraries/BytesLib.sol";

/// This contract combines 1Inch and Stargate
contract TingMeSwap is Ownable, Pausable {
    // Constants
    // Specific address stand for NativeAddress token
    address private constant NativeAddress =
        0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    uint32 private constant MILLION = 1_000_000;

    // Variables
    uint256 tingMeFee; // tingme fees (per 1,000,000)

    address vault; // tingMeFee receiver

    IAggregationRouterV5 oneInchRouter; // 1Inch router
    IStargateRouter stgRouter; // Stargate router
    mapping(uint16 => IERC20) private poolIdToToken; // mapping Stargate poolId to its token
    mapping(uint256 => bool) private isProcessedTx;

    // Events
    event Received(address indexed token, uint256 indexed amount); // emit event when user received destination token

    // Errors
    error Unauthorized();
    error InsufficientBalance(uint256 available, uint256 required);
    error WrongInput();
    error InvalidAction();

    //
    constructor(
        IAggregationRouterV5 _oneInchRouter,
        IStargateRouter _stgRouter,
        uint256 _tingMeFee,
        address _vault
    ) {
        oneInchRouter = _oneInchRouter;
        stgRouter = _stgRouter;
        tingMeFee = _tingMeFee;
        vault = _vault;
    }

    // Controller functions //

    /// @notice This function changes contract's fee
    /// @param _fee: new fee
    function changeTingMeFee(uint256 _fee) external onlyOwner whenPaused {
        tingMeFee = _fee;
    }

    /// @notice This function changes 1Inch router
    /// @param _router: new router address
    function changeOneInchRouter(
        IAggregationRouterV5 _router
    ) external onlyOwner whenPaused {
        oneInchRouter = _router;
    }

    /// @notice This function changes Stargate router
    /// @param _router: new router address
    function changeSTGRouter(
        IStargateRouter _router
    ) external onlyOwner whenPaused {
        stgRouter = _router;
    }

    /// @notice This function changes fee vault address
    /// @param _vault: new vault address
    function changeVault(address _vault) external onlyOwner whenPaused {
        vault = _vault;
    }

    /// @notice This function add new or update token-poolId mapping (based on Stargate)
    function changePoolToken(
        uint16 poolId,
        IERC20 token
    ) external onlyOwner whenPaused {
        poolIdToToken[poolId] = token;
    }

    /// @notice This function add new or update token-poolId mapping in batch (based on Stargate)
    function changeBatchPoolToken(
        Type.PoolData[] calldata pools
    ) external onlyOwner whenPaused {
        for (uint256 i; i < pools.length; ++i) {
            poolIdToToken[pools[i].poolId] = pools[i].token;
        }
    }

    /// @notice Owner can withdraw any tokens from this contract
    function ownerWithdraw(IERC20 token, uint256 amount) external onlyOwner {
        if (address(token) == NativeAddress) {
            if (amount > address(this).balance) {
                revert InsufficientBalance(address(this).balance, amount);
            }
            payable(msg.sender).transfer(amount);
        } else {
            token.transfer(msg.sender, amount);
        }
    }

    /// allow anyone to send native token to this contract
    receive() external payable {}

    function unpause() external onlyOwner {
        _unpause();
    }

    function pause() external onlyOwner {
        _pause();
    }

    function _removeFunctionSelector(
        bytes memory data
    ) internal pure returns (bytes memory) {
        return BytesLib.slice(data, 4, data.length - 4);
    }

    /// @notice This function helps to create a cross chain transaction on Source Chain
    /// @dev call 1Inch API first to give srcChainSwapData and dstChainSwapData
    /// @param txData: basic data to execute tx
    /// @param stgData: data to use stargate
    /// @param srcChainSwapData: 1Inch swap data on source chain (swap from others to stg pool token, from user to this contract)
    /// @param dstChainSwapData: 1Inch swap data on destination chain (swap from stg pool token to destination token. user is receiver)
    function swapCrosschain(
        Type.TxData calldata txData,
        Type.StgData calldata stgData,
        bytes calldata srcChainSwapData,
        bytes calldata dstChainSwapData
    ) external payable whenNotPaused {
        if (txData.slippage > MILLION / 2) {
            revert WrongInput();
        }
        IERC20 dstToken = poolIdToToken[stgData.srcChainPoolId];
        uint256 returnAmount = _singleChainProcess(
            dstToken,
            txData.amountIn,
            stgData.totalGasFee,
            srcChainSwapData
        );
        // approve pool token
        {
            poolIdToToken[stgData.srcChainPoolId].approve(
                address(stgRouter),
                returnAmount
            );
        }

        bytes memory data = abi.encode(
            txData.receiver,
            txData.slippage,
            dstChainSwapData
        );

        stgRouter.swap{value: stgData.totalGasFee}(
            stgData.dstChainId,
            stgData.srcChainPoolId,
            stgData.dstChainPoolId,
            payable(msg.sender),
            returnAmount,
            ((returnAmount * (MILLION - txData.slippage)) / MILLION),
            IStargateRouter.lzTxObj(stgData.dstChainGasUnit, 0, "0x"),
            abi.encodePacked(txData.dstChainTingMeContract),
            data
        );
    }

    /// @param dstToken: destination token
    /// @param amountIn: number of token in
    /// @param fee: fee in native token
    /// @param swapData: 1Inch data
    /// @return amount of token Out
    function _singleChainProcess(
        IERC20 dstToken,
        uint256 amountIn,
        uint256 fee,
        bytes calldata swapData
    ) private returns (uint256) {
        if (swapData.length == 0) {
            // process destination token
            dstToken.transferFrom(msg.sender, address(this), amountIn);
            return amountIn;
        }
        // Process others => use 1inch to swap
        // Decode data, ignore permit //
        (
            IAggregationExecutor executor,
            Type.SwapDescription memory desc,
            ,
            bytes memory executeData
        ) = abi.decode(
                swapData[4:],
                (IAggregationExecutor, Type.SwapDescription, bytes, bytes)
            );
        // scope validating in destination //
        {
            if (
                desc.dstReceiver != address(this) ||
                address(desc.dstToken) != address(dstToken)
            ) revert WrongInput();
        }

        // NativeAddress, ERC20 process //
        uint256 nativeAmount = 0;
        if (address(desc.srcToken) == NativeAddress) {
            nativeAmount = desc.amount;
            if (nativeAmount + fee > msg.value)
                revert InsufficientBalance(msg.value, nativeAmount + fee);
        } else {
            desc.srcToken.transferFrom(msg.sender, address(this), desc.amount);
            desc.srcToken.approve(address(oneInchRouter), desc.amount);
        }
        // Swap source to pool token
        (uint256 returnAmount, ) = oneInchRouter.swap{value: nativeAmount}(
            executor,
            desc,
            "",
            executeData
        );
        return returnAmount;
    }

    /// @param chainId The remote chainId sending the tokens
    /// @param srcAddress The remote Bridge address
    /// @param nonce: The message ordering nonce
    /// @param token: The token contract on the local chain
    /// @param amount: The qty of local token contract tokens
    /// @param payload: The swap call data in bytes
    function sgReceive(
        uint16 chainId,
        bytes calldata srcAddress,
        uint256 nonce,
        address token,
        uint256 amount,
        bytes calldata payload
    ) external payable {
        if (msg.sender != address(stgRouter)) revert Unauthorized();
        if (isProcessedTx[nonce]) revert InvalidAction();
        // Process Fee //
        if (tingMeFee > 0) {
            uint256 fee = (amount / MILLION) * tingMeFee;
            IERC20(token).transfer(vault, fee);
            amount -= fee;
        }

        // decode payload //
        (address to, uint32 slippage, bytes memory callSwapData) = abi.decode(
            payload,
            (address, uint32, bytes)
        );
        // check swap //
        if (callSwapData.length == 0) {
            // transfer directly
            IERC20(token).transfer(to, amount);
            emit Received(token, amount);
        } else {
            // decode data
            (
                IAggregationExecutor executor,
                Type.SwapDescription memory desc,
                ,
                bytes memory executeData
            ) = abi.decode(
                    _removeFunctionSelector(callSwapData),
                    (IAggregationExecutor, Type.SwapDescription, bytes, bytes)
                );
            // if wrong dstChainData -> transfer pool token to receiver
            if (address(desc.srcToken) != token) {
                IERC20(token).transfer(to, amount);
                emit Received(token, amount);
            }
            //
            else {
                desc.dstReceiver = payable(to);
                desc.amount = amount;
                if (slippage > MILLION / 2) slippage = MILLION / 2;
                desc.srcToken.approve(address(oneInchRouter), amount);
                desc.minReturnAmount =
                    (desc.minReturnAmount * (MILLION - slippage)) /
                    MILLION;

                (uint256 returnAmount, ) = oneInchRouter.swap(
                    executor,
                    desc,
                    "",
                    executeData
                );
                emit Received(address(desc.dstToken), returnAmount);
            }
        }
    }
}