// File: contracts/storage_smart_contract.sol



//SPDX-License-Identifier: UnLicensed
pragma solidity 0.6.6;
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import '@uniswap/v2-periphery/contracts/libraries/UniswapV2Library.sol';

interface IERC20 {
    function allowance(address owner, address spender) external view returns (uint);
    function transfer(address _to, uint _value) external;
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function decimals() external view returns (uint);
}

contract StorageOrder {

    address internal constant UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
    address internal constant CRU_ADDRESS = 0x32a7C02e79c4ea1008dD6564b35F131428673c41;
    address internal constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    IUniswapV2Router02 public uniswapRouter;
    IUniswapV2Factory public uniswapFactory;
    IERC20 public cruToken;
    address payable public owner;
    uint public basePrice;
    uint public bytePrice;
    uint public sizeLimit;
    uint public servicePriceRate;
    mapping(address => bool) public tokens;
    mapping(address => bool) public nodes;
    address[] public tokenArray;
    address[] public nodeArray;

    event Order(address customer, address merchant, string cid, uint size, uint price);
    event OrderInERC20(address customer, address merchant, string cid, uint size, uint price, address token);

    constructor(uint basePrice_, uint bytePrice_, uint servicePriceRate_, uint sizeLimit_) public {
        owner = payable(msg.sender);
        uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
        uniswapFactory = IUniswapV2Factory(uniswapRouter.factory());
        cruToken = IERC20(CRU_ADDRESS);
        tokens[CRU_ADDRESS] = true;
        tokenArray.push(CRU_ADDRESS);
        basePrice = basePrice_;
        bytePrice = bytePrice_;
        servicePriceRate = servicePriceRate_;
        sizeLimit = sizeLimit_;
    }

    modifier onlyOwner {
        require(
            msg.sender == owner,
            "Only owner can call this function"
        );
        _;
    }

    function addSupportedToken(address tokenAddress) public onlyOwner {
        require(tokens[tokenAddress] == false, "Token already added");
        tokens[tokenAddress] = true;
        tokenArray.push(tokenAddress);
    }

    function addOrderNode(address nodeAddress) public onlyOwner {
        require(nodes[nodeAddress] == false, "Node already added");
        nodes[nodeAddress] = true;
        nodeArray.push(nodeAddress);
    }

    function removeSupportedToken(address tokenAddress) public onlyOwner {
        require(tokens[tokenAddress], "Token not exist");
        delete tokens[tokenAddress];
        uint len = tokenArray.length;
        for (uint i = 0; i < len; i++) {
            if (tokenArray[i] == tokenAddress) {
                tokenArray[i] = tokenArray[len-1];
                tokenArray.pop();
                break;
            }
        }
    }
    
    function removeOrderNode(address nodeAddress) public onlyOwner {
        require(nodes[nodeAddress], "Node not exist");
        delete nodes[nodeAddress];
        uint len = nodeArray.length;
        for (uint i = 0; i < len; i++) {
            if (nodeArray[i] == nodeAddress) {
                nodeArray[i] = nodeArray[len-1];
                nodeArray.pop();
                break;
            }
        }
    }

    function setOrderPrice(uint basePrice_, uint bytePrice_) public onlyOwner {
        basePrice = basePrice_;
        bytePrice = bytePrice_;
    }

    function setServicePriceRate(uint servicePriceRate_) public onlyOwner {
        servicePriceRate = servicePriceRate_;
    }

    function setSizeLimit(uint sizeLimit_) public onlyOwner {
        sizeLimit = sizeLimit_;
    }

    function getPrice(uint size) public view returns (uint price) {
        require(sizeLimit >= size, "Size exceeds the limit");
        uint cruAmount = (basePrice + size * bytePrice / (1024**2)) * (servicePriceRate + 100) / 100;
        return getEstimated(cruAmount, WETH_ADDRESS);
    }

    function getPriceInERC20(address tokenAddress, uint size) public view returns (uint price) {
        require(sizeLimit >= size, "Size exceeds the limit");
        require(tokens[tokenAddress], "Unsupported token");
        uint cruAmount = (basePrice + size * bytePrice / (1024**2)) * (servicePriceRate + 100) / 100;
        return getEstimated(cruAmount, tokenAddress);
    }

    function placeOrder(string memory cid, uint size) public payable {
        placeOrderWithNode(cid, size, getRandomNode(cid));
    }

    function placeOrderWithNode(string memory cid, uint size, address nodeAddress) public payable {
        require(sizeLimit >= size, "Size exceeds the limit");
        require(nodes[nodeAddress], "Unsupported node");

        uint price = getPrice(size);
        require(msg.value >= price, "No enough ETH to place order");
        payable(nodeAddress).transfer(price);
        // Refund left ETH
        if (msg.value > price)
            payable(msg.sender).transfer(msg.value - price);
        emit Order(msg.sender, nodeAddress, cid, size, price);
    }

    function placeOrderInERC20(string memory cid, uint size, address tokenAddress) public {
        placeOrderInERC20WithNode(cid, size, tokenAddress, getRandomNode(cid));
    }

    function placeOrderInERC20WithNode(string memory cid, uint size, address tokenAddress, address nodeAddress) public {
        require(sizeLimit >= size, "Size exceeds the limit");
        require(tokens[tokenAddress], "Unsupported token");
        require(nodes[nodeAddress], "Unsupported node");

        uint price = getPriceInERC20(tokenAddress, size);
        IERC20 token = IERC20(tokenAddress);
        require(token.allowance(msg.sender, address(this)) >= price, "No enough token approved");
        token.transferFrom(msg.sender, nodeAddress, price);

        emit OrderInERC20(msg.sender, nodeAddress, cid, size, price, tokenAddress);
    }

    function getEstimated(uint amount, address tokenAddress) internal view returns (uint) {
        (uint val0, bool success0) = getTokenInCRUDirectly(amount, tokenAddress);
        if (success0)
            return val0;

        (uint val1, bool success1) = getTokenInCRUIndirectly(amount, tokenAddress);
        require(success1, "Get price failed");
        return val1;
    }

    function getTokenInCRUDirectly(uint amount, address tokenAddress) internal view returns (uint val, bool success) {
        return getEstimatedTokenforCRU(amount, tokenAddress);
    }

    function getTokenInCRUIndirectly(uint amount, address tokenAddress) internal view returns (uint val, bool success) {
        (uint tokenAmount, bool success0) = getEstimatedETHforUnitToken(tokenAddress);
        require(success0, "Swap token price to ETH failed");
        (uint cruAmount, bool success1) = getEstimatedETHforUnitToken(CRU_ADDRESS);
        require(success1, "Swap CRU price to ETH failed");
        return (amount * cruAmount / tokenAmount, true);
    }

    function getEstimatedTokenforCRU(uint amount, address tokenAddress) internal view returns (uint val, bool success) {
        if (uniswapFactory.getPair(CRU_ADDRESS, tokenAddress) == address(0))
            return (0, false);

        (uint reserve1, uint reserve2) = UniswapV2Library.getReserves(uniswapRouter.factory(), tokenAddress, CRU_ADDRESS);
        IERC20 token1 = IERC20(tokenAddress);
        uint numerator = reserve1 * amount * 1000 * (10**(cruToken.decimals() - token1.decimals()));
        uint denominator = (reserve2 - amount) * 997;
        return ((numerator / denominator) + 1, true);
    }

    function getEstimatedETHforUnitToken(address tokenAddress) internal view returns (uint val, bool success) {
        if (uniswapFactory.getPair(uniswapRouter.WETH(), tokenAddress) == address(0))
            return (0, false);

        (uint reserve1, uint reserve2) = UniswapV2Library.getReserves(uniswapRouter.factory(), uniswapRouter.WETH(), tokenAddress);
        IERC20 token1 = IERC20(uniswapRouter.WETH());
        IERC20 token2 = IERC20(tokenAddress);
        uint amount = 10**token2.decimals();
        uint numerator = reserve1 * amount * 1000 * (10**(token2.decimals() - token1.decimals()));
        uint denominator = (reserve2 - amount) * 997;
        return ((numerator / denominator) + 1, true);
    }

    function getRandomNode(string memory cid) internal view returns (address) {
        require(nodeArray.length > 0, "No node to choose");
        uint nodeID = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, cid))) % nodeArray.length;
        return nodeArray[nodeID];
    }
}
// File: @uniswap/v2-periphery/contracts/libraries/UniswapV2Library.sol



pragma solidity >=0.5.0;

import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';

import "./SafeMath.sol";

library UniswapV2Library {
    using SafeMath for uint;

    // returns sorted token addresses, used to handle return values from pairs sorted in this order
    function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
        require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
        (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
    }

    // calculates the CREATE2 address for a pair without making any external calls
    function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
        (address token0, address token1) = sortTokens(tokenA, tokenB);
        pair = address(uint(keccak256(abi.encodePacked(
                hex'ff',
                factory,
                keccak256(abi.encodePacked(token0, token1)),
                hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
            ))));
    }

    // fetches and sorts the reserves for a pair
    function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
        (address token0,) = sortTokens(tokenA, tokenB);
        (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
        (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
    }

    // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
    function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
        require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
        require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
        amountB = amountA.mul(reserveB) / reserveA;
    }

    // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
        require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
        require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
        uint amountInWithFee = amountIn.mul(997);
        uint numerator = amountInWithFee.mul(reserveOut);
        uint denominator = reserveIn.mul(1000).add(amountInWithFee);
        amountOut = numerator / denominator;
    }

    // given an output amount of an asset and pair reserves, returns a required input amount of the other asset
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
        require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
        require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
        uint numerator = reserveIn.mul(amountOut).mul(1000);
        uint denominator = reserveOut.sub(amountOut).mul(997);
        amountIn = (numerator / denominator).add(1);
    }

    // performs chained getAmountOut calculations on any number of pairs
    function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
        require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
        amounts = new uint[](path.length);
        amounts[0] = amountIn;
        for (uint i; i < path.length - 1; i++) {
            (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
            amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
        }
    }

    // performs chained getAmountIn calculations on any number of pairs
    function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
        require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
        amounts = new uint[](path.length);
        amounts[amounts.length - 1] = amountOut;
        for (uint i = path.length - 1; i > 0; i--) {
            (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
            amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
        }
    }
}

// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol



pragma solidity >=0.6.2;

import './IUniswapV2Router01.sol';

interface IUniswapV2Router02 is IUniswapV2Router01 {
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol



pragma solidity >=0.5.0;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

// File: @uniswap/v2-periphery/contracts/libraries/SafeMath.sol



pragma solidity =0.6.6;

// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)

library SafeMath {
    function add(uint x, uint y) internal pure returns (uint z) {
        require((z = x + y) >= x, 'ds-math-add-overflow');
    }

    function sub(uint x, uint y) internal pure returns (uint z) {
        require((z = x - y) <= x, 'ds-math-sub-underflow');
    }

    function mul(uint x, uint y) internal pure returns (uint z) {
        require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
    }
}

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol



pragma solidity >=0.5.0;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol



pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}