// File: SandBox1.sol



// SPDX-License-Identifier: MIT
// SandBox1 
pragma solidity 0.8.21;

import "UBDExchange.sol";
import "MarketConnector.sol";
import "ReentrancyGuard.sol";

/// @title SandBox1 
/// @author UBD Team
/// @notice This contract is main user's entry point in UBD ecosystem
/// @dev  Check deploy params so they are immutable
contract SandBox1 is UBDExchange, MarketConnector, ReentrancyGuard {

    uint256 public constant TREASURY_TOPUP_PERIOD = 1 days;
    uint256 public constant TREASURY_TOPUP_PERCENT = 10000; // 1% - 10000, 13% - 130000, etc 

    uint256 public lastTreasuryTopUp;
    uint256 public MIN_TREASURY_TOPUP_AMOUNT = 1000; // Stable Coin Units (without decimals)

    constructor(address _markets, address _baseAsset)
        UBDExchange(_baseAsset, address(this))
        MarketConnector(_markets)
    {

    }
    
    /// @notice Swap any asset (available at AMM) to UBD
    /// @dev only called from Sandboxes
    /// @param _inAsset - contract address of in asset
    /// @param _inAmount - amount with decimcals
    /// @param _deadline -acceptable time
    /// @param _amountOutMin - min acceptable amount of base 
    function swapExactInput(
        address _inAsset,
        uint256 _inAmount, 
        uint256 _deadline, 
        uint256 _amountOutMin
    ) 
        public
        nonReentrant
        returns (uint256 outAmount)
    {
        
        // Check system balance and redeem sandbox_1 if  need
        if (_inAsset == address(ubdToken) &&
            IERC20(EXCHANGE_BASE_ASSET).balanceOf(address(this)) < _amountOutMin){
            if (_redeemSandbox1() < _amountOutMin ) {
                return 0;
            }
        }

        if (_inAsset != EXCHANGE_BASE_ASSET && _inAsset != address(ubdToken)) {
            address[] memory path = new address[](2);
            
            // Swap any to BASE asset
            uint256 amountBASE = IMarketRegistry(marketRegistry).swapExactInToBASEOut(
                _inAmount,
                _amountOutMin,
                _inAsset,
                msg.sender,
                _deadline
            );
            return super.swapExactInput(EXCHANGE_BASE_ASSET, amountBASE, _deadline, _amountOutMin, msg.sender);
        }
        return super.swapExactInput(_inAsset, _inAmount, _deadline, _amountOutMin, msg.sender);

    }

    /// @notice Check condition and topup Treasury
    /// @dev Revert if no condition yet
    function topupTreasury() external {
        uint256 topupAmount = 
            IERC20(EXCHANGE_BASE_ASSET).balanceOf(address(this)) 
            * TREASURY_TOPUP_PERCENT 
            / (100 * PERCENT_DENOMINATOR);
        require(
            topupAmount 
                >= MIN_TREASURY_TOPUP_AMOUNT * 10**IERC20Metadata(EXCHANGE_BASE_ASSET).decimals(), 
            'Too small topup amount'
        ); 
        require(
            lastTreasuryTopUp + TREASURY_TOPUP_PERIOD < block.timestamp, 
            'Please wait untit TREASURY_TOPUP_PERIOD'
        );
        lastTreasuryTopUp = block.timestamp;
        IERC20(EXCHANGE_BASE_ASSET).approve(marketRegistry, topupAmount);
        IMarketRegistry(marketRegistry).swapExactBASEInToTreasuryAssets(topupAmount, EXCHANGE_BASE_ASSET);
        emit TreasuryTopup(EXCHANGE_BASE_ASSET, topupAmount);
    }
    
    /// @notice Emergency method for  case of Sandbox1 BASE asset.
    /// Call it for  try sell old BASE asset
    /// @dev Revert if use for current BASE asset
    function topupTreasuryEmergency(address _token) external {
        require(_token != EXCHANGE_BASE_ASSET && _token != address(ubdToken), 'Only for other assets');
        uint256 topupAmount = IERC20(_token).balanceOf(address(this));
        IERC20(_token).approve(marketRegistry, topupAmount);
        IMarketRegistry(marketRegistry).swapExactBASEInToTreasuryAssets(topupAmount, _token);
        emit TreasuryTopup(_token, topupAmount);

    }


    ///////////////////////////////////////////////////////////
    ///////    Admin Functions        /////////////////////////
    ///////////////////////////////////////////////////////////
    function setMinTopUp(uint256 _amount) 
        external 
        onlyOwner 
    {
        MIN_TREASURY_TOPUP_AMOUNT = _amount;
    }
    ///////////////////////////////////////////////////////////

    function ubdTokenAddress() external view returns(address) {
        return address(ubdToken);
    }
    
    function _redeemSandbox1() internal returns(uint256 newBASEBalance) {
        if (_getCollateralSystemLevelM10() >= 10) {
            uint256 redeemAmount = IMarketRegistry(marketRegistry).swapTreasuryAssetsPercentToSandboxAsset(); 
            emit Sandbox1Redeem(EXCHANGE_BASE_ASSET,redeemAmount);
        }
        newBASEBalance = IERC20(EXCHANGE_BASE_ASSET).balanceOf(address(this));
    }

}
// File: UBDExchange.sol



// SPDX-License-Identifier: MIT
// UBDExchange 
pragma solidity 0.8.21;


import "TransferHelper.sol";
import "Ownable.sol";
import "IERC20Burn.sol";


contract UBDExchange is Ownable {
    
    struct PaymentTokenInfo {
        uint256 validAfter;
        uint256 feePercent;  
    }

    uint256 constant public FEE_EXCHANGE_DEFAULT = 5000;      // 0.5 %
    uint256 constant public FEE_EXCHANGE_MAX_PERCENT = 10000; // 1% - 10000, 13% - 130000, etc        
    uint256 constant public PERCENT_DENOMINATOR = 10000;
    uint256 constant public ADD_NEW_PAYMENT_TOKEN_TIMELOCK = 48 hours;
    uint256 constant public EMERGENCY_PAYMENT_PAUSE = 1 hours;

    
    address immutable public SANDBOX_1;

    address public FEE_BENEFICIARY;
    address public EXCHANGE_BASE_ASSET;

    IERC20Burn public ubdToken;
    // mapping from token address to timestamp of start validity
    mapping (address => PaymentTokenInfo) public paymentTokens;
    mapping (address => bool) public isGuardian;
    mapping (address => bool) public isStakingContract;

   
    event PaymentTokenStatus(address indexed Token, bool Status, uint256 FeePercent);
    event PaymentTokenPaused(address indexed Token, uint256 Until);

    error NoDirectSwap(string);

    constructor (address _baseAsset, address _sandbox1) {
        require(_baseAsset != address(0) && _sandbox1 != address(0),'No zero address');
        // Add ETH USDT as default payment asset
        EXCHANGE_BASE_ASSET = _baseAsset;
        paymentTokens[_baseAsset] 
            = PaymentTokenInfo(block.timestamp, FEE_EXCHANGE_DEFAULT);
        SANDBOX_1 = _sandbox1;    
    }


    /// @notice SWap exact amount of input token for output
    /// @dev Don't forget approvement(s)
    /// @param _inAsset  UBD or BASE_TOKEN_ADDRESS,
    /// and  the last is the output token (UniswapV2 style)
    /// @param _inAmount amount of stable to spent
    /// @param _deadline Unix timestamp, Swap can't be executed after
    /// @param _amountOutMin minimum amount of output tokens that 
    /// caller want receive. 
    /// received for the transaction not to revert
    function swapExactInput(
        address _inAsset,
        uint256 _inAmount, 
        uint256 _deadline, 
        uint256 _amountOutMin, 
        address _receiver
    ) 
        public
        virtual 
        returns (uint256 outAmount)
    {
        require(address(ubdToken) != address(0), 'UBD address not Define');
        require(_isValidForPayment(_inAsset), 'Token not enabled');

        address receiver = _receiver;
        
        if (receiver == address(0)) {
            receiver = msg.sender;
        }

        
        // Charge fee in inTokenAsset token from sender if enable(FEE_BENEFICIARY != address(0))
        uint256 feeAmount = _getFeeFromInAmount(_inAsset, _inAmount);

        if (FEE_BENEFICIARY != address(0)) {
            TransferHelper.safeTransferFrom(_inAsset, receiver, FEE_BENEFICIARY, feeAmount);
        }

        // Decrease in amount with charged fee(_inAmountPure)
        uint256 inAmountPure = _inAmount - feeAmount;
        address baseAsset = EXCHANGE_BASE_ASSET;
        

        if (_inAsset == address(ubdToken)) {
            // Back swap from UBD to Excange Base Asset
            // Burn UBD for sender
            ubdToken.burn(receiver, inAmountPure);

            // Return BASE ASSET  _inAmountPure to sender
            outAmount = inAmountPure * 10**IERC20Metadata(baseAsset).decimals() / 10**ubdToken.decimals();
            if (SANDBOX_1 == address(this)){
                TransferHelper.safeTransfer(baseAsset,  receiver, outAmount);    
            } else {
                // This branch can be removed if sandbox always is exchange
                TransferHelper.safeTransferFrom(baseAsset, SANDBOX_1, receiver, outAmount);
            }
            
            

        } else if (_inAsset == baseAsset) {
            // Swap from BASE to UBD
            // Take BAse Token _inAmountPure
            TransferHelper.safeTransferFrom(baseAsset, receiver, SANDBOX_1,  inAmountPure);

            // Mint  UBD _inAmountPure to sender
            outAmount = inAmountPure * 10**ubdToken.decimals() / 10**IERC20Metadata(baseAsset).decimals();
            // Below not used because GAS +2K
            //outAmount = _calcOutForExactIn(EXCHANGE_BASE_ASSET, _inAmount);
            ubdToken.mint(receiver, outAmount); 
        }  else {
            revert NoDirectSwap(IERC20Metadata(baseAsset).symbol());
        }
        // Sanity Checks 
        require(outAmount >= _amountOutMin, "Unexpected Out Amount");
        if (_deadline > 0) {
            require(block.timestamp <= _deadline, "Unexpected Transaction time");
        } 
    }

    /// @notice Mint UBD for staking reward
    /// @notice Available only for trusted addresses
    /// @param _for address reward minting for
    /// @param _amount reward amount
    function mintReward(address _for, uint256 _amount) external {
        require(isStakingContract[msg.sender], 'Only for staking reward');
        ubdToken.mint(_for, _amount); 
    }


    /// @notice Temprory disable payments with token
    /// @param _paymentToken stable coin address
    function emergencyPause(address _paymentToken) external {
        require(isGuardian[msg.sender], "Only for approved guardians");
        if (
                paymentTokens[_paymentToken].validAfter > 0 // token enabled 
                && paymentTokens[_paymentToken].validAfter <= block.timestamp // no timelock now
            ) 
        {
            paymentTokens[_paymentToken].validAfter = block.timestamp + EMERGENCY_PAYMENT_PAUSE;
            // TODO Check GAS with block.timestamp + EMERGENCY_PAYMENT_PAUSE below instead of get from mapping
            emit PaymentTokenPaused(_paymentToken, paymentTokens[_paymentToken].validAfter);
        }
    }

    ///////////////////////////////////////////////////////////
    ///////    Admin Functions        /////////////////////////
    ///////////////////////////////////////////////////////////
    function setPaymentTokenStatus(address _token, bool _state, uint256 _feePercent) 
        external 
        onlyOwner 
    {
        if (_state ) {
            require(_feePercent <= FEE_EXCHANGE_MAX_PERCENT, 'Fee is too much');

            // Timelock for all new tokens but exclude UBD 
            // and current EXCHANGE_BASE_ASSET
            uint256 newValidAfter;
            if (_token != address(ubdToken) && _token != EXCHANGE_BASE_ASSET) {
                EXCHANGE_BASE_ASSET = _token;
                newValidAfter = block.timestamp + ADD_NEW_PAYMENT_TOKEN_TIMELOCK;
            } else {
                newValidAfter = block.timestamp;
            }

            paymentTokens[_token] = PaymentTokenInfo(
                newValidAfter,
                _feePercent
            );
                
        } else {
            require (_token != address(ubdToken), "Cant disable UBD");
            paymentTokens[_token] = PaymentTokenInfo(0, 0);
        }
        
        emit PaymentTokenStatus(_token, _state, _feePercent);
    }

    function setUBDToken(address _token) 
        external 
        onlyOwner 
    {
        require(address(ubdToken) == address(0), "Can call only once");
        paymentTokens[_token] 
            = PaymentTokenInfo(block.timestamp, FEE_EXCHANGE_DEFAULT);
        ubdToken = IERC20Burn(_token);
    }

    function setGuardianStatus(address _guardian, bool _state)
        external
        onlyOwner
    {
        isGuardian[_guardian] = _state;
    }

    function setBeneficiary(address _addr)
        external
        onlyOwner
    {
        FEE_BENEFICIARY = _addr;
    }

    function setStakingContract(address _contract, bool _isEnabled) external onlyOwner {
        isStakingContract[_contract] = _isEnabled;
    }

    ///////////////////////////////////////////////////////////

    /// @notice Returns amount of UBD tokens that will be
    /// get by user if he(she) pay given stable coin amount
    /// @dev _inAmount must be with given in wei (eg 1 USDT =1000000)
    /// @param _inAmount stable coin amount that user want to spend
    function calcOutUBDForExactInBASE(uint256 _inAmount) 
        external 
        view 
        returns(uint256) 
    {
        return _calcOutForExactIn(EXCHANGE_BASE_ASSET, _inAmount);
    }

    /// @notice Returns amount of stable coins that must be spent
    /// for user get given  amount of UBD token
    /// @dev _outAmount must be in wei (eg 1 UBD =1e18)
    /// @param _outAmount UBD token amount that user want to get
    function calcInBASEForExactOutUBD(uint256 _outAmount) 
        external 
        view 
        returns(uint256) 
    {
        return _calcInForExactOut(address(ubdToken), _outAmount);
    }

    /// @notice Returns amount of BASE stable that will be
    /// get by user if he(she) pay given UBD amount
    /// @dev _inAmount must be with given in wei (eg 1 USDT =1000000)
    /// @param _inAmount UBD amount that user want to spend
    function calcOutBASEForExactInUBD(uint256 _inAmount) 
        external 
        view 
        returns(uint256) 
    {
        return _calcOutForExactIn(address(ubdToken), _inAmount);
    }

    /// @notice Returns amount of UBD that must be spent
    /// for user get given  amount of BASE token
    /// @dev _outAmount must be in wei (eg 1 UBD =1e18)
    /// @param _outAmount BASE token amount that user want to get
    function calcInUBDForExactOutBASE(uint256 _outAmount) 
        external 
        view 
        returns(uint256) 
    {
        return _calcInForExactOut(EXCHANGE_BASE_ASSET, _outAmount);
    }

    function getFeeFromInAmount(address _inAsset, uint256 _inAmount)
        public
        view
        returns(uint256)
    {
        return _getFeeFromInAmount(_inAsset, _inAmount);
    }
    /////////////////////////////////////////////////////////////////////

    function _getFeeFromInAmount(address _inAsset, uint256 _inAmount)
        internal
        view
        returns(uint256)
    {
        uint256 feeP = paymentTokens[_inAsset].feePercent;
        return _inAmount * feeP / (100 * PERCENT_DENOMINATOR + feeP);
    }

    function _calcOutForExactIn(address _inToken, uint256 _inAmount) 
        internal
        view 
        returns(uint256 outAmount) 
    {
        uint256 inAmountPure = _inAmount - _getFeeFromInAmount(_inToken, _inAmount);
        address outToken;
        if (_inToken == address(ubdToken)){
            outToken = EXCHANGE_BASE_ASSET;
        } else {
            outToken = address(ubdToken);
        }
        outAmount = inAmountPure * 10**IERC20Metadata(outToken).decimals() / 10**IERC20Metadata(_inToken).decimals();
    }

    function _calcInForExactOut(address _outToken, uint256 _outAmount) 
        internal
        view 
        returns(uint256 inAmount) 
    {
       
        address inToken;
        if (_outToken == address(ubdToken)){
            inToken = EXCHANGE_BASE_ASSET;
        } else {
            inToken = address(ubdToken);
        }

         uint256 outAmountWithFee = 
            _outAmount + _outAmount * paymentTokens[inToken].feePercent  
                / (100 * PERCENT_DENOMINATOR);

        inAmount = outAmountWithFee 
            * (10**IERC20Metadata(inToken).decimals())
            / (10**IERC20Metadata(_outToken).decimals()); 
            

    }


    function _isValidForPayment(address _paymentToken) internal view returns(bool){
        uint256 validAfterTime = paymentTokens[_paymentToken].validAfter;
        if ( validAfterTime == 0) {
            return false;
        }
        require( validAfterTime < block.timestamp, "Token paused or timelocked");
        return true; 
    }
}
// File: TransferHelper.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import "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: 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: Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

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. 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: 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: IERC20Burn.sol



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

import "IERC20Mint.sol";

interface IERC20Burn is IERC20Mint {
    function burn(address _burnFor, uint256 _amount) external;
}
// File: IERC20Mint.sol



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

import "IERC20Metadata.sol";

interface IERC20Mint is IERC20Metadata {
    function mint(address _for, uint256 _amount) external;
}
// File: IERC20Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: MarketConnector.sol



// SPDX-License-Identifier: MIT
// MarketConnector 
pragma solidity 0.8.21;

import "IMarketRegistry.sol";

abstract contract MarketConnector {

    address immutable public marketRegistry;
	constructor(address _markets)
    {
        marketRegistry = _markets;

    }

    event TreasuryTopup(address Asset, uint256 TopupAmount);
    event Sandbox2Topup(address Asset, uint256 TopupAmount);
    event Sandbox1Redeem(address Asset, uint256 TopupAmount);


    function _getCollateralSystemLevelM10() internal view returns(uint256) {
        return  IMarketRegistry(marketRegistry).getCollateralLevelM10();
    }
    
    function _getBalanceInStableUnits(address _holder, address[] memory _assets) 
        internal 
        view 
        returns(uint256)
    {
        return IMarketRegistry(marketRegistry).getBalanceInStableUnits(_holder, _assets);
    }
}
// File: IMarketRegistry.sol



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



interface IMarketRegistry  {

    struct AsssetShare {
        address asset;
        uint8 percent;
    }

    struct UBDNetwork {
        address sandbox1;
        address treasury;
        address sandbox2;
        AsssetShare[] treasuryERC20Assets;

    }

    struct Market {
        address marketAdapter;
        address oracleAdapter;
        uint256 slippage;
    }

    struct ActualShares{
        address asset;
        uint256 actualPercentPoint;
        uint256 excessAmount;
    } 
    
    function swapExactInToBASEOut(
        uint256 amountIn,
        uint256 amountOutMin,
        address assetIn,
        address to,
        uint deadline
    ) external returns (uint256 amountOut);


    function swapExactBASEInToTreasuryAssets(uint256 _amountIn, address _baseAsset) external;

    function swapTreasuryAssetsPercentToSandboxAsset() 
        external 
        returns(uint256 totalStableAmount);

    function getAmountOut(
        uint amountIn, 
        address[] memory path
    ) external view returns (uint256 amountOut);
    function getCollateralLevelM10() external view returns(uint256);
    function getBalanceInStableUnits(address _holder, address[] memory _assets) external view returns(uint256);
    function treasuryERC20Assets() external view returns(address[] memory assets);
    function getUBDNetworkTeamAddress() external view returns(address);
    function getUBDNetworkInfo() external view returns(UBDNetwork memory);
}
// File: ReentrancyGuard.sol



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

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}