Contract 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f

 
Txn Hash Method
Block
From
To
Value [Txn Fee]
0x0673106ce37e9560e5f8213d4a8f6f04c34e1b6642382494e640428951d5c8baInitialize53335752022-02-02 1:07:20308 days 15 hrs ago0x420220b72bbd307db8615e7aa0eadca399cf2fc0 IN  0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH0.001042004632 ETH
0x4fc3b2c3c91d049c42c5d49adeb5fc4a77e6a6a8e1f62ed31f106535feba10230x60a0604046290832022-01-14 3:47:29327 days 12 hrs ago0x420220b72bbd307db8615e7aa0eadca399cf2fc0 IN  Create: Treasury0 ETH0.140772621031 ETH
[ Download CSV Export 
Latest 25 internal transaction
Parent Txn Hash Block From To Value
0xc91d2f5c97d2fa735a47dee1aaff17cc499b28b894245f324143e9754fa7c9ba442524992022-12-07 4:30:0511 hrs 51 mins ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0xd1d49348e735abe1fa1367119111b224f281aa17f8de89e235780bf761a92077442502062022-12-07 4:14:4612 hrs 6 mins ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x697245b6ecaa08dd6a65a643a3a2054876aa8a8a060335c03828ca0295cc11f6425982812022-12-01 3:12:256 days 13 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0xb3bfb4fb65e27777df7ac79685829c40caab36255313059841ef8bcd794724b5425975382022-12-01 3:07:586 days 13 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x53a9c9618443a24286673502fb46eb5a3eb5e2ac81f8dada19ea61e740f1d087418724882022-11-28 12:12:059 days 4 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x684d02b71cacde4285a2968ce90909f4fb09ae4792b7f8d0a6b519aa885ea35d418721792022-11-28 12:10:359 days 4 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x6abe31e3c8380abb94f4e3d5bbd6a8b4eb50ba38356d19cd7142f6a6aa174f7d418685872022-11-28 11:52:339 days 4 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x2f383f34ca86fe2dbbc4e1b229ef121e694c0bebe3b0b562917a51b2860df139405111772022-11-23 10:03:3914 days 6 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0xf398d2cc2de03839d763e67743658a45534350d3feefb1216ef3b7b9f4444db8405111472022-11-23 10:03:2914 days 6 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x7086ee40bc2f9b4a9deab818a68bba30814ccc053160083b37e76268c9bc2ee1404942292022-11-23 8:47:4014 days 7 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x22d491c769d2396cefbafca34d24e7ed19db1af7820fad2e0c01495fedc36e78404939522022-11-23 8:46:2614 days 7 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x704296ba27e11753c60c1427af85a777ae8f6b92913608078dbb380fb8f7da8c404932112022-11-23 8:42:5814 days 7 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0xe6d9f1a21413f7b83d7cfa370b58f3b9da4b5e771a1318dc1d77781064c84e60404931342022-11-23 8:42:3914 days 7 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x5ba1a02ee7a7bb03502598f93c4e68988d043594c8a18401c39a021821681a17404930472022-11-23 8:42:1514 days 7 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x0e3c1ed4c1bfd7e727ac44a7b9fe60ebccb628449ea74d943c82e3310454adec404930122022-11-23 8:42:0514 days 7 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x27694071ae8a61bd91cabc5e6271098ae30095bd0be7f2b9a5c860609e4d8b2e404920242022-11-23 8:37:4514 days 7 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x2c4dd84a36c456a73cfbc79558739de7cf8858e744a785ad3c743739151c3094404919312022-11-23 8:37:1914 days 7 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x1d25db07aaa83e2c5ada23f584e426b83a36bbf0de8b48fdbafc7ddd84d9ffb1404901282022-11-23 8:29:1214 days 7 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x5bf3f91fbb0aa10e2325eaf1587aeb4aec0f2595c6f03101f98d41de0623dcdc404237542022-11-23 2:58:3614 days 13 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0xed530d1b479560bd12623b49399ddcd4906103a4e6bd9309e129f1c6eddd828d401479052022-11-22 5:21:3915 days 10 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x725fa9ceb9c11f39d148c1baa90968589abb30a775a8f18d5b624d01d63157d6400382992022-11-21 19:35:3015 days 20 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x725fa9ceb9c11f39d148c1baa90968589abb30a775a8f18d5b624d01d63157d6400382992022-11-21 19:35:3015 days 20 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0xc292afd92508b5e7beb8bc8d2f9b166b6b61a28b50dc68cf548a23aa122ae827399298262022-11-21 11:43:5016 days 4 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x14f0e10d7377daed707d9deae1da7de446257c990728f625747421b1bef50dc0399257902022-11-21 11:26:1816 days 4 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
0x55ba91a0d2b576e6076eb8da28989d4624761f31c61154a8258f95faa5e3b6c5399257282022-11-21 11:26:0116 days 4 hrs ago 0x5710b75a0aa37f4da939a61bb53c519296627994 0x23dda05b0ed06be4b16c311155ec7302b79c6f9f0 ETH
[ Download CSV Export 
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.

Contract Source Code Verified (Exact Match)

Contract Name:
Treasury

Compiler Version
v0.8.3+commit.8d00100c

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 28 : Treasury.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/Bank/ITreasury.sol";
import "../interfaces/IWETH.sol";
import "../interfaces/Bank/IVaultLibrary.sol";
import "../interfaces/Bank/IHandle.sol";
import "../interfaces/Bank/IHandleComponent.sol";
import "../interfaces/Bank/IPCT.sol";
import "../interfaces/Bank/IInterest.sol";
import "../interfaces/Bank/IReferral.sol";
import "../interfaces/rewards/IRewardPool.sol";
import "./Roles.sol";

/**
 * @dev Provides deposit and withdrawal functions for vaults.
        Holds all protocol funds.
 */
contract Treasury is
    ITreasury,
    Initializable,
    UUPSUpgradeable,
    IHandleComponent,
    Roles,
    ReentrancyGuardUpgradeable
{
    using SafeMath for uint256;
    using SafeERC20 for IERC20;

    /** @dev The Handle contract interface */
    IHandle private handle;
    /** @dev The VaultLibrary contract interface */
    IVaultLibrary private vaultLibrary;
    /** @dev The canonical WETH address */
    address private WETH;

    /** @dev Variable to keep track of total deposits, converted to ETH at
             the time of the deposit. Used to limit the max. deposits in the
             contract for safety reasons during the initial deployment to
             mainnet. */
    uint256 public totalCollateralDeposited;
    /** @dev Maximum deposit allowed (in ETH). A value of 0 means no maximum */
    uint256 public maximumTotalDepositAllowed;

    address private self;

    /** @dev Proxy initialisation function */
    function initialize() public initializer {
        __AccessControl_init();
        __ReentrancyGuard_init();
        _setupRole(ADMIN_ROLE, msg.sender);
        _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
        _setRoleAdmin(OPERATOR_ROLE, ADMIN_ROLE);
        self = address(this);
    }

    /**
     * @dev Setter for maximumTotalDepositAllowed
     * @param value The maximum deposit allowed in ETH.
     */
    function setMaximumTotalDepositAllowed(uint256 value)
        external
        override
        onlyAdmin
    {
        maximumTotalDepositAllowed = value;
    }

    /**
     * @dev Setter for Handle contract reference
     * @param _handle The Handle contract address
     */
    function setHandleContract(address _handle) public override onlyAdmin {
        handle = IHandle(_handle);
        WETH = handle.WETH();
        // Grant roles as needed.
        uint256 operatorCount = 3;
        address[] memory operators = new address[](operatorCount);
        operators[0] = handle.comptroller();
        operators[1] = handle.fxKeeperPool();
        operators[2] = handle.liquidator();
        for (uint256 i = 0; i < operatorCount; i++) {
            if (!hasRole(OPERATOR_ROLE, operators[i]))
                grantRole(OPERATOR_ROLE, operators[i]);
        }
        // Update interface references.
        vaultLibrary = IVaultLibrary(handle.vaultLibrary());
    }

    /** @dev Getter for Handle contract address */
    function handleAddress() public view override returns (address) {
        return address(handle);
    }

    /** Allow any incoming ETH transfers. */
    receive() external payable {}

    /**
     * @dev Deposits collateral into a vault.
     * @param to The vault account to deposit into.
     * @param amount The amount to deposit.
     * @param collateralToken The type of collateral to deposit.
     * @param fxToken The vault fxToken.
     * @param referral The referral account.
     */
    function depositCollateral(
        address to,
        uint256 amount,
        address collateralToken,
        address fxToken,
        address referral
    ) external override nonReentrant {
        _trySetReferral(to, referral);
        _depositCollateral(msg.sender, to, amount, collateralToken, fxToken);
    }

    /**
     * @dev Deposits ETH collateral into a vault as WETH.
     * @param to The vault account to deposit into.
     * @param fxToken The vault fxToken.
     * @param referral The referral account.
     */
    function depositCollateralETH(
        address to,
        address fxToken,
        address referral
    ) external payable override nonReentrant {
        require(handle.isCollateralValid(WETH), "IC");
        _trySetReferral(to, referral);
        // Wrap incoming ether into WETH
        IWETH(WETH).deposit{value: msg.value}();
        // Deposit WETH for the user.
        _depositCollateral(self, to, msg.value, WETH, fxToken);
    }

    /**
     * @dev Deposits collateral into a vault.
     * @param from The address to deposit from.
     * @param to The vault account to deposit into.
     * @param depositAmount The amount of collateral to deposit.
     * @param fxToken The vault fxToken.
     */
    function _depositCollateral(
        address from,
        address to,
        uint256 depositAmount,
        address collateralToken,
        address fxToken
    ) private {
        require(handle.isCollateralValid(collateralToken), "IC");

        // Ensure Treasury has self-allowance on ERC20 to wrap for the user.
        // This is needed on Arbitrum for ETH->WETH deposits.
        if (
            from == self &&
            IERC20(collateralToken).allowance(self, self) < depositAmount
        ) {
            IERC20(collateralToken).safeApprove(self, 0);
            IERC20(collateralToken).safeApprove(self, 2**256 - 1);
        }

        // Ensure that this deposit won't result in the total ETH cap being
        uint256 newTotalEthDeposits =
            totalCollateralDeposited.add(
                depositAmount.mul(handle.getTokenPrice(collateralToken)).div(
                    vaultLibrary.getTokenUnit(collateralToken)
                )
            );
        require(
            maximumTotalDepositAllowed == 0 ||
                newTotalEthDeposits <= maximumTotalDepositAllowed,
            "IA"
        );
        totalCollateralDeposited = newTotalEthDeposits;

        // Update interest rates according to cache time.
        IInterest(handle.interest()).tryUpdateRates();

        // Calculate fee and actual deposit amount.
        uint256 fee = depositAmount.mul(handle.depositFeePerMille()).div(1000);
        depositAmount = depositAmount.sub(fee);

        // Transfer collateral into the treasury
        IERC20(collateralToken).safeTransferFrom(from, self, depositAmount);

        handle.updateCollateralBalance(
            to,
            depositAmount,
            fxToken,
            collateralToken,
            true
        );

        // Transfer fee.
        IERC20(collateralToken).safeTransferFrom(
            from,
            handle.FeeRecipient(),
            fee
        );

        // Stake into PCT and RewardPool.
        handleStaking(to, fxToken, collateralToken, depositAmount, true);
    }

    /**
     * @dev Withdraws collateral from the sender's account
     * @param collateralToken The collateral token to withdraw
     * @param to The address to remit to
     * @param amount The amount of collateral to withdraw
     * @param fxToken The vault fxToken
     */
    function withdrawCollateral(
        address collateralToken,
        address to,
        uint256 amount,
        address fxToken
    ) external override nonReentrant {
        // Update interest rates according to cache time.
        IInterest(handle.interest()).tryUpdateRates();
        _withdrawCollateralFrom(
            msg.sender,
            collateralToken,
            to,
            amount,
            fxToken
        );
    }

    /**
     * @dev Withdraws collateral from a vault
     * @param from The vault account to withdraw from
     * @param collateralToken The collateral token to withdraw
     * @param to The address to remit to
     * @param amount The amount of collateral to withdraw
     * @param fxToken The vault fxToken
     */
    function withdrawCollateralFrom(
        address from,
        address collateralToken,
        address to,
        uint256 amount,
        address fxToken
    ) external override onlyAddressOrOperatorExcludeAdmin(from) nonReentrant {
        // Update interest rates according to cache time.
        IInterest(handle.interest()).tryUpdateRates();
        _withdrawCollateralFrom(from, collateralToken, to, amount, fxToken);
    }

    /**
     * @dev Withdraws WETH collateral as ETH
     * @param to The address to remit to
     * @param amount The amount of collateral to withdraw
     * @param fxToken The vault fxToken
     */
    function withdrawCollateralETH(
        address to,
        uint256 amount,
        address fxToken
    ) external override nonReentrant {
        // Update interest rates according to cache time.
        IInterest(handle.interest()).tryUpdateRates();
        _withdrawCollateralFrom(msg.sender, address(0), to, amount, fxToken);
    }

    /**
     * @dev Withdraws collateral from a vault if the resulting CR meets the
            minimum CR required. Can be used for all collateral types
     * @param from The vault account to withdraw from
     * @param collateralToken The vault collateral token to withdraw
     * @param to The address to remit to
     * @param amount The amount of collateral to withdraw
     * @param fxToken The vault fxToken
     */
    function _withdrawCollateralFrom(
        address from,
        address collateralToken,
        address to,
        uint256 amount,
        address fxToken
    ) private {
        address parsedCollateralToken =
            collateralToken == address(0) ? WETH : collateralToken;
        uint256 collateralRate = handle.getTokenPrice(parsedCollateralToken);
        // The available ERC20 amount.
        uint256 available =
            vaultLibrary
                .getFreeCollateralAsEth(from, fxToken)
                .mul(vaultLibrary.getTokenUnit(parsedCollateralToken))
                .div(collateralRate);
        uint256 collateralBalance =
            handle.getCollateralBalance(from, parsedCollateralToken, fxToken);

        if (available > collateralBalance) available = collateralBalance;

        require(available > 0, "CA");

        if (amount > available) amount = available;

        _forceWithdrawCollateral(from, collateralToken, to, amount, fxToken);
    }

    /**
     * @dev Withdraws any collateral type available in a vault.
            Uses the sorted liquidation collateral order from VaultLibrary.
     * @param from The owner of the vault to withdraw from
     * @param to The address to remit to
     * @param amount The amount of collateral to withdraw
     * @param fxToken The vault to withdraw from
     */
    function forceWithdrawAnyCollateral(
        address from,
        address to,
        uint256 amount,
        address fxToken,
        bool requireFullAmount
    )
        external
        override
        onlyOperator
        nonReentrant
        returns (
            address[] memory collateralTypes,
            uint256[] memory collateralAmounts
        )
    {
        bool metAmount;
        (collateralTypes, collateralAmounts, metAmount) = vaultLibrary
            .getCollateralForAmount(from, fxToken, amount);
        if (requireFullAmount && !metAmount) revert("IA");

        uint256 j = collateralTypes.length;
        for (uint256 i = 0; i < j; i++) {
            if (collateralAmounts[i] == 0) continue;
            _forceWithdrawCollateral(
                from,
                collateralTypes[i],
                to,
                collateralAmounts[i],
                fxToken
            );
        }
    }

    /**
     * @dev Forces collateral withdraw, bypassing vault CR checks.
            Can be used for all collateral types.
     * @param from The owner of the vault to withdraw from
     * @param collateralToken The token to withdraw
     * @param to The address to remit to
     * @param amount The amount of collateral to withdraw
     * @param fxToken The vault to withdraw from
     */
    function forceWithdrawCollateral(
        address from,
        address collateralToken,
        address to,
        uint256 amount,
        address fxToken
    ) external override onlyOperator nonReentrant {
        // Require that user has enough collateral.
        require(
            handle.getCollateralBalance(from, collateralToken, fxToken) >=
                amount,
            "CA"
        );
        _forceWithdrawCollateral(from, collateralToken, to, amount, fxToken);
    }

    /**
     * @dev Forces a collateral withdrawal, bypassing minimum CR checks.
     * @param from The vault account to withdraw from
     * @param collateralToken The vault collateral token to withdraw
     * @param to The account to send the funds to
     * @param amount The amount to be withdrawn
     * @param fxToken The vault fxToken
     */
    function _forceWithdrawCollateral(
        address from,
        address collateralToken,
        address to,
        uint256 amount,
        address fxToken
    ) private {
        bool isEth = collateralToken == address(0);
        if (isEth) collateralToken = WETH;

        // Calculate and transfer fee.
        // Set withdraw fee to zero if recipient is FeeRecipient.
        // Send fees as WETH even if ETH in favour of function size.
        address feeRecipient = handle.FeeRecipient();
        uint256 fee =
            to != feeRecipient
                ? amount.mul(handle.withdrawFeePerMille()).div(1000)
                : 0;

        if (fee > 0) IERC20(collateralToken).safeTransfer(feeRecipient, fee);

        handle.updateCollateralBalance(
            from,
            amount,
            fxToken,
            collateralToken,
            false
        );

        // Unstake from PCT and RewardPool.
        handleStaking(from, fxToken, collateralToken, amount, false);

        uint256 withdrawAmount = amount - fee;
        // Remit collateral to the user
        if (!isEth) {
            uint256 balanceBefore = IERC20(collateralToken).balanceOf(to);
            IERC20(collateralToken).safeTransfer(to, withdrawAmount);
            uint256 balanceAfter = IERC20(collateralToken).balanceOf(to);
            assert(balanceBefore + withdrawAmount == balanceAfter);
        } else {
            IWETH(WETH).withdraw(withdrawAmount);
            bool success;
            (success, ) = to.call{value: withdrawAmount}("");
            require(success, "FP");
        }
    }

    /**
     * @dev Stakes or unstakes user collateral into/from the PCT and rewards.
            Keeps track of collateral shares per-user as investments
            are made for the PCT, and FOREX rewards for the RewardPool.
     * @param account The vault account
     * @param fxToken The vault fxToken
     * @param collateralToken The vault collateral token
     * @param amount The amount to stake/unstake
     * @param isStaking Whether staking or otherwise unstaking collateral
     */
    function handleStaking(
        address account,
        address fxToken,
        address collateralToken,
        uint256 amount,
        bool isStaking
    ) private {
        uint256 upperBound = handle.pctCollateralUpperBound();
        IRewardPool rewards = IRewardPool(handle.rewards());
        (bool foundRewardPool, uint256 rewardPoolId) =
            rewards.getPoolIdByAlias(
                rewards.getFxTokenPoolAlias(
                    fxToken,
                    uint256(RewardPoolCategory.Deposit)
                )
            );
        if (upperBound == 0 && !foundRewardPool) return;
        uint256 pctAmount = (amount * upperBound) / (1 ether);
        IPCT pct = IPCT(handle.pct());
        if (isStaking) {
            if (upperBound > 0)
                pct.stake(account, pctAmount, fxToken, collateralToken);
            if (foundRewardPool) rewards.stake(account, amount, rewardPoolId);
        } else {
            if (upperBound > 0)
                pct.unstake(account, pctAmount, fxToken, collateralToken);
            if (foundRewardPool) rewards.unstake(account, amount, rewardPoolId);
        }
    }

    /**
     * @dev Allows the configured PCT contract to request any funds held by
            the Treasury to be invested in external finance protocols.
     * @param token The token requested.
     * @param amount The amount to be transferred.
     */
    function requestFundsPCT(address token, uint256 amount) external override {
        address pct = handle.pct();
        require(msg.sender == pct, "NO");
        IERC20(token).safeTransfer(pct, amount);
    }

    /**
     * @dev Calls the referral function to set a referral if this is the first
            time the user interacts with the protocol.
     * @param user The user address.
     * @param referral The referrer address.
     */
    function _trySetReferral(address user, address referral) private {
        IReferral(handle.referral()).setReferral(user, referral);
    }

    /** @dev Protected UUPS upgrade authorization function */
    function _authorizeUpgrade(address) internal override onlyAdmin {}
}

File 2 of 28 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)

pragma solidity ^0.8.0;

import "../../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
 * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() initializer {}
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     */
    bool private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Modifier to protect an initializer function from being invoked twice.
     */
    modifier initializer() {
        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
        // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
        // contract may have been reentered.
        require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");

        bool isTopLevelCall = !_initializing;
        if (isTopLevelCall) {
            _initializing = true;
            _initialized = true;
        }

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} modifier, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    function _isConstructor() private view returns (bool) {
        return !AddressUpgradeable.isContract(address(this));
    }
}

File 3 of 28 : ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @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 ReentrancyGuardUpgradeable is Initializable {
    // 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;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _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() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

        _;

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

File 4 of 28 : UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.0;

import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * _Available since v4.1._
 */
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
    function __UUPSUpgradeable_init() internal onlyInitializing {
        __ERC1967Upgrade_init_unchained();
        __UUPSUpgradeable_init_unchained();
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
    address private immutable __self = address(this);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        require(address(this) != __self, "Function must be called through delegatecall");
        require(_getImplementation() == __self, "Function must be called through active proxy");
        _;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     */
    function upgradeTo(address newImplementation) external virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallSecure(newImplementation, new bytes(0), false);
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallSecure(newImplementation, data, true);
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeTo} and {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal override onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;
    uint256[50] private __gap;
}

File 5 of 28 : SafeMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)

pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}

File 6 of 28 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 7 of 28 : ITreasury.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

interface ITreasury {
    function depositCollateral(
        address account,
        uint256 depositAmount,
        address collateralType,
        address fxToken,
        address referral
    ) external;

    function depositCollateralETH(
        address account,
        address fxToken,
        address referral
    ) external payable;

    function withdrawCollateral(
        address collateralToken,
        address to,
        uint256 amount,
        address fxToken
    ) external;

    function withdrawCollateralETH(
        address to,
        uint256 amount,
        address fxToken
    ) external;

    function withdrawCollateralFrom(
        address from,
        address collateralToken,
        address to,
        uint256 amount,
        address fxToken
    ) external;

    function forceWithdrawCollateral(
        address from,
        address collateralToken,
        address to,
        uint256 amount,
        address fxToken
    ) external;

    function forceWithdrawAnyCollateral(
        address from,
        address to,
        uint256 amount,
        address fxToken,
        bool requireFullAmount
    )
        external
        returns (
            address[] memory collateralTypes,
            uint256[] memory collateralAmounts
        );

    function requestFundsPCT(address token, uint256 amount) external;

    function setMaximumTotalDepositAllowed(uint256 value) external;
}

File 8 of 28 : IWETH.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

interface IWETH {
    function deposit() external payable;

    function transfer(address to, uint256 value) external returns (bool);

    function withdraw(uint256) external;
}

File 9 of 28 : IVaultLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

interface IVaultLibrary {
    function doesMeetRatio(address account, address fxToken)
        external
        view
        returns (bool);

    function getFreeCollateralAsEth(address account, address fxToken)
        external
        view
        returns (uint256);

    function getFreeCollateralAsEthFromMinimumRatio(
        address account,
        address fxToken,
        uint256 minimumRatio
    ) external view returns (uint256);

    function getMinimumRatio(address account, address fxToken)
        external
        view
        returns (uint256 ratio);

    function getMinimumCollateral(
        uint256 tokenAmount,
        uint256 ratio,
        uint256 unitPrice
    ) external view returns (uint256 minimum);

    function getDebtAsEth(address account, address fxToken)
        external
        view
        returns (uint256 debt);

    function getTotalCollateralBalanceAsEth(address account, address fxToken)
        external
        view
        returns (uint256 balance);

    function getCurrentRatio(address account, address fxToken)
        external
        view
        returns (uint256 ratio);

    function getCollateralForAmount(
        address account,
        address fxToken,
        uint256 amountEth
    )
        external
        view
        returns (
            address[] memory collateralTypes,
            uint256[] memory collateralAmounts,
            bool metAmount
        );

    function getDecimalsAmount(
        uint256 amount,
        uint8 fromDecimals,
        uint8 toDecimals
    ) external pure returns (uint256);

    function calculateInterest(address account, address fxToken)
        external
        view
        returns (uint256 interest);

    function getInterestRate(address account, address fxToken)
        external
        view
        returns (uint256 rate);

    function getInterestDeltaR(address account, address fxToken)
        external
        view
        returns (uint256 dR);

    function getLiquidationFee(address account, address fxToken)
        external
        view
        returns (uint256 fee);

    function getCollateralShares(address account, address fxToken)
        external
        view
        returns (uint256[] memory shares);

    function getCollateralTypesSortedByLiquidationRank()
        external
        view
        returns (address[] memory sortedCollateralTypes);

    function getNewMinimumRatio(
        address account,
        address fxToken,
        address collateralToken,
        uint256 collateralAmount,
        uint256 collateralQuote,
        bool isDeposit
    ) external view returns (uint256 ratio, uint256 newCollateralAsEther);

    function canMint(
        address account,
        address fxToken,
        address collateralToken,
        uint256 collateralAmount,
        uint256 tokenAmount,
        uint256 fxQuote,
        uint256 collateralQuote
    ) external view returns (bool);

    function quickSort(
        uint256[] memory array,
        int256 left,
        int256 right
    ) external pure;

    function getTokenUnit(address token) external view returns (uint256);
}

File 10 of 28 : IHandle.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

pragma abicoder v2;

interface IHandle {
    struct Vault {
        // Collateral token address => balance
        mapping(address => uint256) collateralBalance;
        uint256 debt;
        // Collateral token address => R0
        mapping(address => uint256) R0;
    }

    struct CollateralData {
        uint256 mintCR;
        uint256 liquidationFee;
        uint256 interestRate;
    }

    event UpdateDebt(address indexed account, address indexed fxToken);

    event UpdateCollateral(
        address indexed account,
        address indexed fxToken,
        address indexed collateralToken
    );

    event ConfigureCollateralToken(address indexed collateralToken);

    event ConfigureFxToken(address indexed fxToken, bool removed);

    function setCollateralUpperBoundPCT(uint256 ratio) external;

    function setPaused(bool value) external;

    function setFxToken(address token) external;

    function removeFxToken(address token) external;

    function setCollateralToken(
        address token,
        uint256 mintCR,
        uint256 liquidationFee,
        uint256 interestRatePerMille
    ) external;

    function removeCollateralToken(address token) external;

    function getAllCollateralTypes()
        external
        view
        returns (address[] memory collateral);

    function getCollateralDetails(address collateral)
        external
        view
        returns (CollateralData memory);

    function WETH() external view returns (address);

    function treasury() external view returns (address payable);

    function comptroller() external view returns (address);

    function vaultLibrary() external view returns (address);

    function fxKeeperPool() external view returns (address);

    function pct() external view returns (address);

    function liquidator() external view returns (address);

    function interest() external view returns (address);

    function referral() external view returns (address);

    function forex() external view returns (address);

    function rewards() external view returns (address);

    function pctCollateralUpperBound() external view returns (uint256);

    function isFxTokenValid(address fxToken) external view returns (bool);

    function isCollateralValid(address collateral) external view returns (bool);

    function setComponents(address[] memory components) external;

    function updateDebtPosition(
        address account,
        uint256 amount,
        address fxToken,
        bool increase
    ) external;

    function updateCollateralBalance(
        address account,
        uint256 amount,
        address fxToken,
        address collateralToken,
        bool increase
    ) external;

    function setFeeRecipient(address feeRecipient) external;

    function setFees(
        uint256 withdrawFeePerMille,
        uint256 depositFeePerMille,
        uint256 mintFeePerMille,
        uint256 burnFeePerMille
    ) external;

    function getCollateralBalance(
        address account,
        address collateralType,
        address fxToken
    ) external view returns (uint256 balance);

    function getBalance(address account, address fxToken)
        external
        view
        returns (address[] memory collateral, uint256[] memory balances);

    function getDebt(address owner, address fxToken)
        external
        view
        returns (uint256 _debt);

    function getPrincipalDebt(address owner, address fxToken)
        external
        view
        returns (uint256 _debt);

    function getCollateralR0(
        address account,
        address fxToken,
        address collateral
    ) external view returns (uint256 R0);

    function getTokenPrice(address token) external view returns (uint256 quote);

    function setOracle(address fxToken, address oracle) external;

    function FeeRecipient() external view returns (address);

    function mintFeePerMille() external view returns (uint256);

    function burnFeePerMille() external view returns (uint256);

    function withdrawFeePerMille() external view returns (uint256);

    function depositFeePerMille() external view returns (uint256);

    function isPaused() external view returns (bool);
}

File 11 of 28 : IHandleComponent.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
pragma abicoder v2;

interface IHandleComponent {
    function setHandleContract(address hanlde) external;

    function handleAddress() external view returns (address);
}

File 12 of 28 : IPCT.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
pragma abicoder v2;

interface IPCT {
    struct Pool {
        // account -> fxToken -> Deposit
        mapping(address => mapping(address => Deposit)) deposits;
        // Protocol interface address => whether protocol is valid
        mapping(address => bool) protocolInterfaces;
        // Protocol interface address => invested amount
        mapping(address => uint256) protocolInvestments;
        // Deposits that are either flagged (not confirmed) or confirmed and not invested.
        uint256 totalDeposits;
        // Total deposit amount during last investment round, including invested amount.
        uint256 totalDepositsAtInvestment;
        // Amount of deposits that have been invested (<= totalDepositsAtInvestment).
        uint256 totalInvestments;
        // Total accrued interest from investments.
        uint256 totalAccrued;
        // Current pool reward ratio over total deposits.
        uint256 S;
        // Current investment round number.
        uint256 N;
    }

    struct Deposit {
        uint256 amount_flagged;
        uint256 amount_confirmed;
        uint256 S;
        uint256 N;
    }

    event Stake(
        address indexed account,
        address indexed fxToken,
        address indexed collateralToken,
        uint256 amount
    );

    event Unstake(
        address indexed account,
        address indexed fxToken,
        address indexed collateralToken,
        uint256 amount
    );

    event ClaimInterest(
        address indexed acount,
        address indexed collateralToken,
        uint256 amount
    );

    event SetProtocolInterface(
        address indexed protocolInterfaceAddress,
        address indexed collateralToken
    );

    event UnsetProtocolInterface(
        address indexed protocolInterfaceAddress,
        address indexed collateralToken
    );

    event ProtocolClaimInterest(
        address indexed protocolInterfaceAddress,
        address indexed collateralToken,
        uint256 amount
    );

    event ProtocolReturnFunds(
        address indexed protocolInterfaceAddress,
        address indexed collateralToken,
        uint256 amount
    );

    event ProtocolDepositFunds(
        address indexed protocolInterfaceAddress,
        address indexed collateralToken,
        uint256 amount
    );

    function stake(
        address account,
        uint256 amount,
        address fxToken,
        address collateralToken
    ) external returns (uint256 errorCode);

    function unstake(
        address account,
        uint256 amount,
        address fxToken,
        address collateralToken
    ) external returns (uint256 errorCode);

    function claimInterest(address fxToken, address collateralToken) external;

    function setProtocolInterface(
        address collateralToken,
        address protocolInterfaceAddress
    ) external;

    function unsetProtocolInterface(
        address collateralToken,
        address protocolInterfaceAddress
    ) external;

    function claimProtocolInterest(
        address collateralToken,
        address protocolInterfaceAddress
    ) external;

    function depositProtocolFunds(
        address collateralToken,
        address protocolInterfaceAddress,
        uint256 ratio
    ) external;

    function withdrawProtocolFunds(
        address collateralToken,
        address protocolInterfaceAddress,
        uint256 amount
    ) external;

    function requestTreasuryFunds(
        address collateralToken,
        address requestedToken,
        uint256 amount
    ) external;

    function returnTreasuryFunds(
        address collateralToken,
        address returnedToken,
        uint256 amount
    ) external;

    function setProtocolFee(uint256 ratio) external;

    function protocolFee() external view returns (uint256);

    function balanceOfStake(
        address account,
        address fxToken,
        address collateralToken
    ) external view returns (uint256 amount);

    function balanceOfClaimableInterest(
        address account,
        address fxToken,
        address collateralToken
    ) external view returns (uint256 amount);

    function getTotalDeposits(address collateralToken)
        external
        view
        returns (uint256 amount);

    function getTotalInvestments(address collateralToken)
        external
        view
        returns (uint256 amount);

    function getProtocolInvestments(
        address collateralToken,
        address protocolInterfaceAddress
    ) external view returns (uint256 amount);

    function getTotalAccruedInterest(address collateralToken)
        external
        view
        returns (uint256 amount);
}

File 13 of 28 : IInterest.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
pragma abicoder v2;

interface IInterest {
    struct ExternalAssetData {
        bytes32 makerDaoCollateralIlk;
    }

    function setCollateralExternalAssetData(
        address collateral,
        bytes32 makerDaoCollateralIlk
    ) external;

    function unsetCollateralExternalAssetData(address collateral) external;

    function setMaxExternalSourceInterest(uint256 interestPerMille) external;

    function charge() external;

    function getCurrentR()
        external
        view
        returns (uint256[] memory R, address[] memory collateralTokens);

    function setDataSource(address source) external;

    function tryUpdateRates() external;

    function updateRates() external;

    function fetchRate(address token) external view returns (uint256);
}

File 14 of 28 : IReferral.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
pragma abicoder v2;

interface IReferral {
    function setReferral(address userAccount, address referralAccount) external;

    function getReferral(address userAccount) external view returns (address);
}

File 15 of 28 : IRewardPool.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
pragma abicoder v2;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

/**
 * @dev Established pool categories to be used internally by the
 * protocol for the users.
 * This enum is used to get the correct pool ID from the pool alias
 * which consists of an fxToken address and a category number.
 */
enum RewardPoolCategory {Mint, Deposit, Keeper}

interface IRewardPool {
    /** Reward category e.g. Keepers or Liquidity Providers */
    struct Pool {
        // Pool reward weight. The amount of FOREX allocated to this
        // category is given by the ratio of this weight to the sum of all
        // weights for enabled pools.
        // A category is enabled if the weight is not zero.
        uint256 weight;
        // Asset is used for pools that require token staking,
        // such as LP tokens. Could be e.g. None, ERC20 or ERC721.
        AssetType assetType;
        // For pools with no token (AssetType::None), this value is zero.
        address assetAddress;
        // If AssetType == None, whitelist with this map from staker address.
        mapping(address => bool) stakerWhitelist;
        // Account -> Deposit
        mapping(address => Deposit) deposits;
        // Total amount deposited, which may be boosted.
        uint256 totalDeposits;
        // Current pool reward ratio over total deposits.
        uint256 S;
        // Total real value deposited (excluding boosts).
        uint256 totalRealDeposits;
    }

    /** Reward pool deposit for tracking user contributions */
    struct Deposit {
        // Amount contributed.
        // e.g. for Keepers, the total amount staked.
        //      for minters, the total amount minted.
        //      for LPs, the total liquidity provided.
        uint256 amount;
        // Reward ratio over total deposits during deposit.
        uint256 S;
        // The weight (gFOREX balance) by which the boost is
        // calculated from during claim.
        uint256 boostWeight;
    }

    enum AssetType {None, ERC20, ERC721}

    event Stake(address indexed account, uint256 poolId, uint256 amount);

    event Unstake(address indexed account, uint256 poolId, uint256 amount);

    event CreatePool(
        uint256 id,
        AssetType assetType,
        address asset,
        uint256 weight
    );

    event SetPoolWeights(uint256[] poolIds, uint256[] weights);

    event SetFxTokenWeights(address[] fxTokens, uint256[] weights);

    event ForexDistributed(
        uint256 duration,
        uint256 rate,
        uint256 totalAmount,
        uint256[] poolIds,
        uint256[] amounts
    );

    event SetForexDistributionRate(uint256 ratePerSecond);

    event Claim(
        address indexed acount,
        uint256 amount,
        uint256[] poolIds,
        uint256[] amounts
    );

    event WhitelistChanged(address staker, uint256 poolId, bool whitelisted);

    event PoolAliasChanged(uint256 poolId, bytes32 aliasHash);

    function stake(
        address account,
        uint256 value,
        uint256 poolId
    ) external returns (uint256 errorCode);

    function unstake(
        address account,
        uint256 value,
        uint256 poolId
    ) external returns (uint256 errorCode);

    function claim() external;

    function distribute() external;

    function createPool(
        uint256 weight,
        AssetType assetType,
        address assetAddress,
        uint256[] memory poolIds,
        uint256[] memory weights
    ) external;

    function setupPools(
        AssetType[] memory assetTypes,
        address[] memory assetAddresses,
        uint256[] memory weights,
        bytes32[] memory aliases
    ) external;

    // Used to enable and disable pools.
    // To disable, a weight must be set to zero.
    // Will emit events accordingly.
    function setPools(uint256[] memory poolIds, uint256[] memory weights)
        external;

    function setWhitelistedStaker(
        address staker,
        uint256 poolId,
        bool isWhitelisted
    ) external;

    function setForexDistributionRate(uint256 rate) external;

    function setPoolAlias(bytes32 hash, uint256 poolId) external;

    function getPoolsData()
        external
        view
        returns (
            uint256[] memory poolRatios,
            uint256[] memory accruedAmounts,
            uint256[] memory deltaS
        );

    function getPoolIdByAlias(bytes32 hash)
        external
        view
        returns (bool found, uint256 poolId);

    function getFxTokenPoolAlias(address token, uint256 category)
        external
        view
        returns (bytes32);

    // Return allowed parameters only (no mappings)
    // because Solidity is a Special Snowflake (tm)
    function getPool(uint256 poolId)
        external
        view
        returns (
            uint256 weight,
            AssetType assetType,
            address assetAddress,
            uint256 totalDeposits,
            uint256 S,
            uint256 totalRealDeposits
        );

    function getDeposit(address account, uint256 poolId)
        external
        view
        returns (Deposit memory);

    function balanceOf(address account) external view returns (uint256 balance);

    function getUserBoostedStake(
        address account,
        uint256 value,
        uint256 poolId,
        uint256 boostWeight
    ) external view returns (uint256);

    function forex() external view returns (IERC20);
}

File 16 of 28 : Roles.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";

abstract contract Roles is AccessControlUpgradeable {
    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");

    modifier onlyOperator() {
        require(hasRole(OPERATOR_ROLE, msg.sender), "NO");
        _;
    }

    modifier onlyAdmin() {
        require(hasRole(ADMIN_ROLE, msg.sender), "NA");
        _;
    }

    modifier onlyOperatorOrAdmin() {
        require(
            hasRole(OPERATOR_ROLE, msg.sender) ||
                hasRole(ADMIN_ROLE, msg.sender),
            "NW"
        );
        _;
    }

    modifier onlyAddressOrOperatorExcludeAdmin(address addressAllowed) {
        // Protect user deposits from abuse
        require(
            msg.sender == addressAllowed ||
                (hasRole(OPERATOR_ROLE, msg.sender) &&
                    !hasRole(ADMIN_ROLE, msg.sender)),
            "NW"
        );
        _;
    }
}

File 17 of 28 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)

pragma solidity ^0.8.0;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 18 of 28 : ERC1967UpgradeUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)

pragma solidity ^0.8.2;

import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 *
 * @custom:oz-upgrades-unsafe-allow delegatecall
 */
abstract contract ERC1967UpgradeUpgradeable is Initializable {
    function __ERC1967Upgrade_init() internal onlyInitializing {
        __ERC1967Upgrade_init_unchained();
    }

    function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
    }
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(
        address newImplementation,
        bytes memory data,
        bool forceCall
    ) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            _functionDelegateCall(newImplementation, data);
        }
    }

    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallSecure(
        address newImplementation,
        bytes memory data,
        bool forceCall
    ) internal {
        address oldImplementation = _getImplementation();

        // Initial upgrade and setup call
        _setImplementation(newImplementation);
        if (data.length > 0 || forceCall) {
            _functionDelegateCall(newImplementation, data);
        }

        // Perform rollback test if not already in progress
        StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
        if (!rollbackTesting.value) {
            // Trigger rollback using upgradeTo from the new implementation
            rollbackTesting.value = true;
            _functionDelegateCall(
                newImplementation,
                abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
            );
            rollbackTesting.value = false;
            // Check rollback was effective
            require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
            // Finally reset to the new implementation and log the upgrade
            _upgradeTo(newImplementation);
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {AdminChanged} event.
     */
    function _changeAdmin(address newAdmin) internal {
        emit AdminChanged(_getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Emitted when the beacon is upgraded.
     */
    event BeaconUpgraded(address indexed beacon);

    /**
     * @dev Returns the current beacon.
     */
    function _getBeacon() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }

    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(
        address newBeacon,
        bytes memory data,
        bool forceCall
    ) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
        require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
    }
    uint256[50] private __gap;
}

File 19 of 28 : IBeaconUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeaconUpgradeable {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {BeaconProxy} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

File 20 of 28 : StorageSlotUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
 */
library StorageSlotUpgradeable {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly {
            r.slot := slot
        }
    }
}

File 21 of 28 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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 `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

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

File 22 of 28 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)

pragma solidity ^0.8.0;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 23 of 28 : AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
    function __AccessControl_init() internal onlyInitializing {
        __Context_init_unchained();
        __ERC165_init_unchained();
        __AccessControl_init_unchained();
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role, _msgSender());
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(uint160(account), 20),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
    uint256[49] private __gap;
}

File 24 of 28 : IAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

File 25 of 28 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
        __Context_init_unchained();
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
    uint256[50] private __gap;
}

File 26 of 28 : StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}

File 27 of 28 : ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
        __ERC165_init_unchained();
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }
    uint256[50] private __gap;
}

File 28 of 28 : IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165Upgradeable {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"beacon","type":"address"}],"name":"BeaconUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"OPERATOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"address","name":"fxToken","type":"address"},{"internalType":"address","name":"referral","type":"address"}],"name":"depositCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"address","name":"fxToken","type":"address"},{"internalType":"address","name":"referral","type":"address"}],"name":"depositCollateralETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"fxToken","type":"address"},{"internalType":"bool","name":"requireFullAmount","type":"bool"}],"name":"forceWithdrawAnyCollateral","outputs":[{"internalType":"address[]","name":"collateralTypes","type":"address[]"},{"internalType":"uint256[]","name":"collateralAmounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"fxToken","type":"address"}],"name":"forceWithdrawCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"handleAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"maximumTotalDepositAllowed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"requestFundsPCT","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_handle","type":"address"}],"name":"setHandleContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"setMaximumTotalDepositAllowed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalCollateralDeposited","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"}],"name":"upgradeTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"fxToken","type":"address"}],"name":"withdrawCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"fxToken","type":"address"}],"name":"withdrawCollateralETH","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"fxToken","type":"address"}],"name":"withdrawCollateralFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

60a06040523060601b60805234801561001757600080fd5b5060805160601c613eb161004b60003960008181610597015281816105d70152818161066001526106a00152613eb16000f3fe60806040526004361061016a5760003560e01c80637d694f15116100d1578063a9de31491161008a578063eb2266fc11610064578063eb2266fc14610414578063f5b541a614610442578063fd58a30114610464578063ffda4da41461048457610171565b8063a9de3149146103ca578063d547741f146103e1578063d811b9bd1461040157610171565b80637d694f15146103205780638129fc1c146103405780638c6d4c471461035557806391d14854146103755780639b1c414f14610395578063a217fddf146103b557610171565b806358166d241161012357806358166d241461025e5780635a6f45de1461027e57806364cfc1ad1461029e5780636c7ca871146102be57806374bf578b146102d557806375b238fc146102fe57610171565b806301ffc9a714610176578063248a9ca3146101ab5780632f2ff15d146101e957806336568abe1461020b5780633659cfe61461022b5780634f1ef2861461024b57610171565b3661017157005b600080fd5b34801561018257600080fd5b506101966101913660046139f0565b6104a4565b60405190151581526020015b60405180910390f35b3480156101b757600080fd5b506101db6101c6366004613991565b600090815260c9602052604090206001015490565b6040519081526020016101a2565b3480156101f557600080fd5b506102096102043660046139c1565b6104dd565b005b34801561021757600080fd5b506102096102263660046139c1565b610509565b34801561023757600080fd5b50610209610246366004613582565b61058c565b610209610259366004613716565b610655565b34801561026a57600080fd5b50610209610279366004613604565b61070b565b34801561028a57600080fd5b5061020961029936600461366b565b610841565b3480156102aa57600080fd5b506102096102b9366004613604565b610951565b3480156102ca57600080fd5b506101db6101315481565b3480156102e157600080fd5b5061012d546040516001600160a01b0390911681526020016101a2565b34801561030a57600080fd5b506101db600080516020613e5c83398151915281565b34801561032c57600080fd5b5061020961033b366004613991565b610ae0565b34801561034c57600080fd5b50610209610b1a565b34801561036157600080fd5b506102096103703660046137b8565b610c4b565b34801561038157600080fd5b506101966103903660046139c1565b610d07565b3480156103a157600080fd5b506102096103b0366004613582565b610d32565b3480156103c157600080fd5b506101db600081565b3480156103d657600080fd5b506101db6101305481565b3480156103ed57600080fd5b506102096103fc3660046139c1565b61119f565b61020961040f3660046135ba565b6111c5565b34801561042057600080fd5b5061043461042f3660046136bd565b611340565b6040516101a2929190613aa9565b34801561044e57600080fd5b506101db600080516020613e1583398151915281565b34801561047057600080fd5b5061020961047f3660046137e3565b611538565b34801561049057600080fd5b5061020961049f366004613819565b61163e565b60006001600160e01b03198216637965db0b60e01b14806104d557506301ffc9a760e01b6001600160e01b03198316145b90505b919050565b600082815260c960205260409020600101546104fa81335b61167d565b61050483836116e1565b505050565b6001600160a01b038116331461057e5760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084015b60405180910390fd5b6105888282611767565b5050565b306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614156105d55760405162461bcd60e51b815260040161057590613b6e565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166106076117ce565b6001600160a01b03161461062d5760405162461bcd60e51b815260040161057590613bba565b610636816117fc565b6040805160008082526020820190925261065291839190611830565b50565b306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016141561069e5760405162461bcd60e51b815260040161057590613b6e565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166106d06117ce565b6001600160a01b0316146106f65760405162461bcd60e51b815260040161057590613bba565b6106ff826117fc565b61058882826001611830565b610723600080516020613e1583398151915233610d07565b61073f5760405162461bcd60e51b815260040161057590613b52565b600260fb5414156107625760405162461bcd60e51b815260040161057590613c6d565b600260fb5561012d5460405163062315a960e51b81526001600160a01b038781166004830152868116602483015283811660448301528492169063c462b5209060640160206040518083038186803b1580156107bd57600080fd5b505afa1580156107d1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107f591906139a9565b10156108285760405162461bcd60e51b8152602060048201526002602482015261434160f01b6044820152606401610575565b610835858585858561197b565b5050600160fb55505050565b600260fb5414156108645760405162461bcd60e51b815260040161057590613c6d565b600260fb5561012d54604080516361c97bb360e11b815290516001600160a01b039092169163c392f76691600480820192602092909190829003018186803b1580156108af57600080fd5b505afa1580156108c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108e7919061359e565b6001600160a01b0316634342fef56040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561092157600080fd5b505af1158015610935573d6000803e3d6000fd5b505050506109463385858585611dcc565b5050600160fb555050565b84336001600160a01b038216148061099d575061097c600080516020613e1583398151915233610d07565b801561099d575061099b600080516020613e5c83398151915233610d07565b155b6109ce5760405162461bcd60e51b81526020600482015260026024820152614e5760f01b6044820152606401610575565b600260fb5414156109f15760405162461bcd60e51b815260040161057590613c6d565b600260fb5561012d54604080516361c97bb360e11b815290516001600160a01b039092169163c392f76691600480820192602092909190829003018186803b158015610a3c57600080fd5b505afa158015610a50573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a74919061359e565b6001600160a01b0316634342fef56040518163ffffffff1660e01b8152600401600060405180830381600087803b158015610aae57600080fd5b505af1158015610ac2573d6000803e3d6000fd5b50505050610ad38686868686611dcc565b5050600160fb5550505050565b610af8600080516020613e5c83398151915233610d07565b610b145760405162461bcd60e51b815260040161057590613c06565b61013155565b600054610100900460ff16610b355760005460ff1615610b39565b303b155b610b9c5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610575565b600054610100900460ff16158015610bbe576000805461ffff19166101011790555b610bc661207f565b610bce6120c0565b610be6600080516020613e5c833981519152336120ef565b610bfe600080516020613e5c833981519152806120f9565b610c24600080516020613e15833981519152600080516020613e5c8339815191526120f9565b61013280546001600160a01b031916301790558015610652576000805461ff001916905550565b61012d5460408051639cfd966960e01b815290516000926001600160a01b031691639cfd9669916004808301926020929190829003018186803b158015610c9157600080fd5b505afa158015610ca5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cc9919061359e565b9050336001600160a01b03821614610cf35760405162461bcd60e51b815260040161057590613b52565b6105046001600160a01b0384168284612144565b600091825260c9602090815260408084206001600160a01b0393909316845291905290205460ff1690565b610d4a600080516020613e5c83398151915233610d07565b610d665760405162461bcd60e51b815260040161057590613c06565b61012d80546001600160a01b0319166001600160a01b038316908117909155604080516315ab88c960e31b8152905163ad5c464891600480820192602092909190829003018186803b158015610dbb57600080fd5b505afa158015610dcf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610df3919061359e565b61012f80546001600160a01b0319166001600160a01b0392909216919091179055604080516003808252608082019092526000908260208201606080368337505061012d5460408051635fe3b56760e01b815290519394506001600160a01b0390911692635fe3b56792506004808301926020929190829003018186803b158015610e7d57600080fd5b505afa158015610e91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eb5919061359e565b81600081518110610ed657634e487b7160e01b600052603260045260246000fd5b6001600160a01b0392831660209182029290920181019190915261012d54604080516327ab02b960e01b8152905191909316926327ab02b9926004808301939192829003018186803b158015610f2b57600080fd5b505afa158015610f3f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f63919061359e565b81600181518110610f8457634e487b7160e01b600052603260045260246000fd5b6001600160a01b0392831660209182029290920181019190915261012d546040805163202375d760e11b815290519190931692634046ebae926004808301939192829003018186803b158015610fd957600080fd5b505afa158015610fed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611011919061359e565b8160028151811061103257634e487b7160e01b600052603260045260246000fd5b60200260200101906001600160a01b031690816001600160a01b03168152505060005b828110156110f15761109c600080516020613e1583398151915283838151811061108f57634e487b7160e01b600052603260045260246000fd5b6020026020010151610d07565b6110df576110df600080516020613e158339815191528383815181106110d257634e487b7160e01b600052603260045260246000fd5b60200260200101516104dd565b806110e981613daa565b915050611055565b5061012d60009054906101000a90046001600160a01b03166001600160a01b031663eb0a8b916040518163ffffffff1660e01b815260040160206040518083038186803b15801561114157600080fd5b505afa158015611155573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611179919061359e565b61012e80546001600160a01b0319166001600160a01b0392909216919091179055505050565b600082815260c960205260409020600101546111bb81336104f5565b6105048383611767565b600260fb5414156111e85760405162461bcd60e51b815260040161057590613c6d565b600260fb5561012d5461012f5460405163803c97b360e01b81526001600160a01b03918216600482015291169063803c97b39060240160206040518083038186803b15801561123657600080fd5b505afa15801561124a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061126e9190613948565b61129f5760405162461bcd60e51b8152602060048201526002602482015261494360f01b6044820152606401610575565b6112a983826121a7565b61012f60009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b1580156112fa57600080fd5b505af115801561130e573d6000803e3d6000fd5b50506101325461012f5461133694506001600160a01b03918216935087925034911686612297565b5050600160fb5550565b60608061135b600080516020613e1583398151915233610d07565b6113775760405162461bcd60e51b815260040161057590613b52565b600260fb54141561139a5760405162461bcd60e51b815260040161057590613c6d565b600260fb5561012e546040516311a559f160e11b81526001600160a01b038981166004830152868116602483015260448201889052600092169063234ab3e29060640160006040518083038186803b1580156113f557600080fd5b505afa158015611409573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526114319190810190613872565b91945092509050838015611443575080155b156114755760405162461bcd60e51b8152602060048201526002602482015261494160f01b6044820152606401610575565b825160005b81811015611524578381815181106114a257634e487b7160e01b600052603260045260246000fd5b6020026020010151600014156114b757611512565b6115128a8683815181106114db57634e487b7160e01b600052603260045260246000fd5b60200260200101518b87858151811061150457634e487b7160e01b600052603260045260246000fd5b60200260200101518b61197b565b8061151c81613daa565b91505061147a565b5050600160fb555090969095509350505050565b600260fb54141561155b5760405162461bcd60e51b815260040161057590613c6d565b600260fb5561012d54604080516361c97bb360e11b815290516001600160a01b039092169163c392f76691600480820192602092909190829003018186803b1580156115a657600080fd5b505afa1580156115ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115de919061359e565b6001600160a01b0316634342fef56040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561161857600080fd5b505af115801561162c573d6000803e3d6000fd5b50505050611336336000858585611dcc565b600260fb5414156116615760405162461bcd60e51b815260040161057590613c6d565b600260fb5561167085826121a7565b6108353386868686612297565b6116878282610d07565b6105885761169f816001600160a01b031660146127d6565b6116aa8360206127d6565b6040516020016116bb929190613a34565b60408051601f198184030181529082905262461bcd60e51b825261057591600401613b1f565b6116eb8282610d07565b61058857600082815260c9602090815260408083206001600160a01b03851684529091529020805460ff191660011790556117233390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6117718282610d07565b1561058857600082815260c9602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b611814600080516020613e5c83398151915233610d07565b6106525760405162461bcd60e51b815260040161057590613c06565b600061183a6117ce565b9050611845846129bf565b6000835111806118525750815b15611863576118618484612a64565b505b7f4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143805460ff1661197457805460ff191660011781556040516001600160a01b03831660248201526118e290869060440160408051601f198184030181529190526020810180516001600160e01b0316631b2ce7f360e11b179052612a64565b50805460ff191681556118f36117ce565b6001600160a01b0316826001600160a01b03161461196b5760405162461bcd60e51b815260206004820152602f60248201527f45524331393637557067726164653a207570677261646520627265616b73206660448201526e75727468657220757067726164657360881b6064820152608401610575565b61197485612b4f565b5050505050565b6001600160a01b03841615801561199c5761012f546001600160a01b031694505b61012d546040805163764a2bc760e11b815290516000926001600160a01b03169163ec94578e916004808301926020929190829003018186803b1580156119e257600080fd5b505afa1580156119f6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a1a919061359e565b90506000816001600160a01b0316866001600160a01b03161415611a3f576000611adc565b611adc6103e8611ad661012d60009054906101000a90046001600160a01b03166001600160a01b03166341e3f2816040518163ffffffff1660e01b815260040160206040518083038186803b158015611a9757600080fd5b505afa158015611aab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611acf91906139a9565b8890612b8f565b90612b9b565b90508015611af857611af86001600160a01b0388168383612144565b61012d5460405163181e20a760e01b81526001600160a01b038a811660048301526024820188905286811660448301528981166064830152600060848301529091169063181e20a79060a401600060405180830381600087803b158015611b5e57600080fd5b505af1158015611b72573d6000803e3d6000fd5b50505050611b84888589886000612ba7565b6000611b908287613d50565b905083611cd6576040516370a0823160e01b81526001600160a01b038881166004830152600091908a16906370a082319060240160206040518083038186803b158015611bdc57600080fd5b505afa158015611bf0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c1491906139a9565b9050611c2a6001600160a01b038a168984612144565b6040516370a0823160e01b81526001600160a01b038981166004830152600091908b16906370a082319060240160206040518083038186803b158015611c6f57600080fd5b505afa158015611c83573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ca791906139a9565b905080611cb48484613cf9565b14611ccf57634e487b7160e01b600052600160045260246000fd5b5050611dc1565b61012f54604051632e1a7d4d60e01b8152600481018390526001600160a01b0390911690632e1a7d4d90602401600060405180830381600087803b158015611d1d57600080fd5b505af1158015611d31573d6000803e3d6000fd5b505050506000876001600160a01b03168260405160006040518083038185875af1925050503d8060008114611d82576040519150601f19603f3d011682016040523d82523d6000602084013e611d87565b606091505b50508091505080611dbf5760405162461bcd60e51b8152602060048201526002602482015261046560f41b6044820152606401610575565b505b505050505050505050565b60006001600160a01b03851615611de35784611df1565b61012f546001600160a01b03165b61012d54604051630681320d60e51b81526001600160a01b0380841660048301529293506000929091169063d02641a09060240160206040518083038186803b158015611e3d57600080fd5b505afa158015611e51573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e7591906139a9565b61012e546040516380ef72a960e01b81526001600160a01b038581166004830152929350600092611f8f928592611ad692909116906380ef72a99060240160206040518083038186803b158015611ecb57600080fd5b505afa158015611edf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f0391906139a9565b61012e5460405163e76ab23960e01b81526001600160a01b038e811660048301528a811660248301529091169063e76ab2399060440160206040518083038186803b158015611f5157600080fd5b505afa158015611f65573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f8991906139a9565b90612b8f565b61012d5460405163062315a960e51b81526001600160a01b038b81166004830152868116602483015287811660448301529293506000929091169063c462b5209060640160206040518083038186803b158015611feb57600080fd5b505afa158015611fff573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061202391906139a9565b905080821115612031578091505b600082116120665760405162461bcd60e51b8152602060048201526002602482015261434160f01b6044820152606401610575565b81861115612072578195505b611dc1898989898961197b565b600054610100900460ff166120a65760405162461bcd60e51b815260040161057590613c22565b6120ae6130ef565b6120b66130ef565b6120be6130ef565b565b600054610100900460ff166120e75760405162461bcd60e51b815260040161057590613c22565b6120be613116565b61058882826116e1565b600082815260c96020526040808220600101805490849055905190918391839186917fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9190a4505050565b6040516001600160a01b03831660248201526044810182905261050490849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152613144565b61012d60009054906101000a90046001600160a01b03166001600160a01b0316631441a5a96040518163ffffffff1660e01b815260040160206040518083038186803b1580156121f657600080fd5b505afa15801561220a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061222e919061359e565b6040516307543e3f60e41b81526001600160a01b03848116600483015283811660248301529190911690637543e3f090604401600060405180830381600087803b15801561227b57600080fd5b505af115801561228f573d6000803e3d6000fd5b505050505050565b61012d5460405163803c97b360e01b81526001600160a01b0384811660048301529091169063803c97b39060240160206040518083038186803b1580156122dd57600080fd5b505afa1580156122f1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123159190613948565b6123465760405162461bcd60e51b8152602060048201526002602482015261494360f01b6044820152606401610575565b610132546001600160a01b0386811691161480156123e7575061013254604051636eb1769f60e11b81526001600160a01b03918216600482018190526024820152849184169063dd62ed3e9060440160206040518083038186803b1580156123ad57600080fd5b505afa1580156123c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123e591906139a9565b105b156124255761013254612408906001600160a01b0384811691166000613216565b61013254612425906001600160a01b038481169116600019613216565b61012e546040516380ef72a960e01b81526001600160a01b038481166004830152600092612500926124f692909116906380ef72a99060240160206040518083038186803b15801561247657600080fd5b505afa15801561248a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124ae91906139a9565b61012d54604051630681320d60e51b81526001600160a01b038881166004830152611ad692169063d02641a09060240160206040518083038186803b158015611a9757600080fd5b610130549061333a565b905061013154600014806125175750610131548111155b6125485760405162461bcd60e51b8152602060048201526002602482015261494160f01b6044820152606401610575565b61013081905561012d54604080516361c97bb360e11b815290516001600160a01b039092169163c392f76691600480820192602092909190829003018186803b15801561259457600080fd5b505afa1580156125a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125cc919061359e565b6001600160a01b0316634342fef56040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561260657600080fd5b505af115801561261a573d6000803e3d6000fd5b5050505060006126786103e8611ad661012d60009054906101000a90046001600160a01b03166001600160a01b0316639df5138a6040518163ffffffff1660e01b815260040160206040518083038186803b158015611a9757600080fd5b90506126848582613346565b610132549095506126a4906001600160a01b03868116918a911688613352565b61012d5460405163181e20a760e01b81526001600160a01b0388811660048301526024820188905285811660448301528681166064830152600160848301529091169063181e20a79060a401600060405180830381600087803b15801561270a57600080fd5b505af115801561271e573d6000803e3d6000fd5b505050506127bf8761012d60009054906101000a90046001600160a01b03166001600160a01b031663ec94578e6040518163ffffffff1660e01b815260040160206040518083038186803b15801561277557600080fd5b505afa158015612789573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127ad919061359e565b6001600160a01b038716919084613352565b6127cd868486886001612ba7565b50505050505050565b606060006127e5836002613d31565b6127f0906002613cf9565b67ffffffffffffffff81111561281657634e487b7160e01b600052604160045260246000fd5b6040519080825280601f01601f191660200182016040528015612840576020820181803683370190505b509050600360fc1b8160008151811061286957634e487b7160e01b600052603260045260246000fd5b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106128a657634e487b7160e01b600052603260045260246000fd5b60200101906001600160f81b031916908160001a90535060006128ca846002613d31565b6128d5906001613cf9565b90505b6001811115612969576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061291757634e487b7160e01b600052603260045260246000fd5b1a60f81b82828151811061293b57634e487b7160e01b600052603260045260246000fd5b60200101906001600160f81b031916908160001a90535060049490941c9361296281613d93565b90506128d8565b5083156129b85760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610575565b9392505050565b803b612a235760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b6064820152608401610575565b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b6060823b612ac35760405162461bcd60e51b815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f6044820152651b9d1c9858dd60d21b6064820152608401610575565b600080846001600160a01b031684604051612ade9190613a18565b600060405180830381855af49150503d8060008114612b19576040519150601f19603f3d011682016040523d82523d6000602084013e612b1e565b606091505b5091509150612b468282604051806060016040528060278152602001613e3560279139613390565b95945050505050565b612b58816129bf565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b60006129b88284613d31565b60006129b88284613d11565b61012d546040805162cb279b60e11b815290516000926001600160a01b0316916301964f36916004808301926020929190829003018186803b158015612bec57600080fd5b505afa158015612c00573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c2491906139a9565b9050600061012d60009054906101000a90046001600160a01b03166001600160a01b0316639ec5a8946040518163ffffffff1660e01b815260040160206040518083038186803b158015612c7757600080fd5b505afa158015612c8b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612caf919061359e565b90506000806001600160a01b03831663db86b79981636de6d5ec8b60016040516001600160e01b031960e085901b1681526001600160a01b039092166004830152602482015260440160206040518083038186803b158015612d1057600080fd5b505afa158015612d24573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d4891906139a9565b6040518263ffffffff1660e01b8152600401612d6691815260200190565b604080518083038186803b158015612d7d57600080fd5b505afa158015612d91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612db59190613964565b91509150836000148015612dc7575081155b15612dd55750505050611974565b6000670de0b6b3a7640000612dea8689613d31565b612df49190613d11565b9050600061012d60009054906101000a90046001600160a01b03166001600160a01b0316639cfd96696040518163ffffffff1660e01b815260040160206040518083038186803b158015612e4757600080fd5b505afa158015612e5b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e7f919061359e565b90508615612fb7578515612f21576040516325073c0760e11b81526001600160a01b038c81166004830152602482018490528b811660448301528a81166064830152821690634a0e780e90608401602060405180830381600087803b158015612ee757600080fd5b505af1158015612efb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f1f91906139a9565b505b8315612fb257604051630c51b88f60e01b81526001600160a01b038c81166004830152602482018a905260448201859052861690630c51b88f90606401602060405180830381600087803b158015612f7857600080fd5b505af1158015612f8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fb091906139a9565b505b6130e2565b851561305157604051635aa347c760e01b81526001600160a01b038c81166004830152602482018490528b811660448301528a81166064830152821690635aa347c790608401602060405180830381600087803b15801561301757600080fd5b505af115801561302b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061304f91906139a9565b505b83156130e25760405163515e335f60e11b81526001600160a01b038c81166004830152602482018a90526044820185905286169063a2bc66be90606401602060405180830381600087803b1580156130a857600080fd5b505af11580156130bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130e091906139a9565b505b5050505050505050505050565b600054610100900460ff166120be5760405162461bcd60e51b815260040161057590613c22565b600054610100900460ff1661313d5760405162461bcd60e51b815260040161057590613c22565b600160fb55565b6000613199826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166133c99092919063ffffffff16565b80519091501561050457808060200190518101906131b79190613948565b6105045760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610575565b80158061329f5750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e9060440160206040518083038186803b15801561326557600080fd5b505afa158015613279573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061329d91906139a9565b155b61330a5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610575565b6040516001600160a01b03831660248201526044810182905261050490849063095ea7b360e01b90606401612170565b60006129b88284613cf9565b60006129b88284613d50565b6040516001600160a01b038085166024830152831660448201526064810182905261338a9085906323b872dd60e01b90608401612170565b50505050565b6060831561339f5750816129b8565b8251156133af5782518084602001fd5b8160405162461bcd60e51b81526004016105759190613b1f565b60606133d884846000856133e0565b949350505050565b6060824710156134415760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610575565b843b61348f5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610575565b600080866001600160a01b031685876040516134ab9190613a18565b60006040518083038185875af1925050503d80600081146134e8576040519150601f19603f3d011682016040523d82523d6000602084013e6134ed565b606091505b50915091506134fd828286613390565b979650505050505050565b600082601f830112613518578081fd5b8151602061352d61352883613cd5565b613ca4565b80838252828201915082860187848660051b890101111561354c578586fd5b855b8581101561356a5781518452928401929084019060010161354e565b5090979650505050505050565b80516104d881613e06565b600060208284031215613593578081fd5b81356129b881613df1565b6000602082840312156135af578081fd5b81516129b881613df1565b6000806000606084860312156135ce578182fd5b83356135d981613df1565b925060208401356135e981613df1565b915060408401356135f981613df1565b809150509250925092565b600080600080600060a0868803121561361b578081fd5b853561362681613df1565b9450602086013561363681613df1565b9350604086013561364681613df1565b925060608601359150608086013561365d81613df1565b809150509295509295909350565b60008060008060808587031215613680578384fd5b843561368b81613df1565b9350602085013561369b81613df1565b92506040850135915060608501356136b281613df1565b939692955090935050565b600080600080600060a086880312156136d4578081fd5b85356136df81613df1565b945060208601356136ef81613df1565b935060408601359250606086013561370681613df1565b9150608086013561365d81613e06565b60008060408385031215613728578182fd5b823561373381613df1565b915060208381013567ffffffffffffffff80821115613750578384fd5b818601915086601f830112613763578384fd5b81358181111561377557613775613ddb565b613787601f8201601f19168501613ca4565b9150808252878482850101111561379c578485fd5b8084840185840137810190920192909252919491935090915050565b600080604083850312156137ca578182fd5b82356137d581613df1565b946020939093013593505050565b6000806000606084860312156137f7578081fd5b833561380281613df1565b92506020840135915060408401356135f981613df1565b600080600080600060a08688031215613830578283fd5b853561383b81613df1565b945060208601359350604086013561385281613df1565b9250606086013561386281613df1565b9150608086013561365d81613df1565b600080600060608486031215613886578081fd5b835167ffffffffffffffff8082111561389d578283fd5b818601915086601f8301126138b0578283fd5b815160206138c061352883613cd5565b8083825282820191508286018b848660051b89010111156138df578788fd5b8796505b8487101561390a5780516138f681613df1565b8352600196909601959183019183016138e3565b5091890151919750909350505080821115613923578283fd5b5061393086828701613508565b92505061393f60408501613577565b90509250925092565b600060208284031215613959578081fd5b81516129b881613e06565b60008060408385031215613976578182fd5b825161398181613e06565b6020939093015192949293505050565b6000602082840312156139a2578081fd5b5035919050565b6000602082840312156139ba578081fd5b5051919050565b600080604083850312156139d3578182fd5b8235915060208301356139e581613df1565b809150509250929050565b600060208284031215613a01578081fd5b81356001600160e01b0319811681146129b8578182fd5b60008251613a2a818460208701613d67565b9190910192915050565b60007f416363657373436f6e74726f6c3a206163636f756e742000000000000000000082528351613a6c816017850160208801613d67565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351613a9d816028840160208801613d67565b01602801949350505050565b604080825283519082018190526000906020906060840190828701845b82811015613aeb5781516001600160a01b031684529284019290840190600101613ac6565b50505083810382850152845180825285830191830190845b8181101561356a57835183529284019291840191600101613b03565b6000602082528251806020840152613b3e816040850160208701613d67565b601f01601f19169190910160400192915050565b6020808252600290820152614e4f60f01b604082015260600190565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b19195b1959d85d1958d85b1b60a21b606082015260800190565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b6163746976652070726f787960a01b606082015260800190565b6020808252600290820152614e4160f01b604082015260600190565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b604051601f8201601f1916810167ffffffffffffffff81118282101715613ccd57613ccd613ddb565b604052919050565b600067ffffffffffffffff821115613cef57613cef613ddb565b5060051b60200190565b60008219821115613d0c57613d0c613dc5565b500190565b600082613d2c57634e487b7160e01b81526012600452602481fd5b500490565b6000816000190483118215151615613d4b57613d4b613dc5565b500290565b600082821015613d6257613d62613dc5565b500390565b60005b83811015613d82578181015183820152602001613d6a565b8381111561338a5750506000910152565b600081613da257613da2613dc5565b506000190190565b6000600019821415613dbe57613dbe613dc5565b5060010190565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052604160045260246000fd5b6001600160a01b038116811461065257600080fd5b801515811461065257600080fdfe97667070c54ef182b0f5858b034beac1b6f3089aa2d3188bb1e8929f4fa9b929416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c21775a26469706673582212208c8c7765bba900bea6dde7d0521dcf54563ab0501c2375d1435a448a5bb71b5764736f6c63430008030033

Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.