GLMR Price: $0.020675 (-2.17%)

Contract

0x37Ff7d6Eb20805f6AbdB10a3De4560E7617cD1B0

Overview

GLMR Balance

Moonbeam Chain LogoMoonbeam Chain LogoMoonbeam Chain Logo0 GLMR

GLMR Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To
Claim53835542024-01-26 13:00:48730 days ago1706274048IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.0125094150
Unstake And Stak...53806532024-01-26 3:06:12731 days ago1706238372IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01739533127.5
Unstake53763712024-01-25 12:27:30731 days ago1706185650IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01895292161
Stake53688392024-01-24 10:52:48732 days ago1706093568IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01555847134.1074385
Claim53026492024-01-15 2:12:00742 days ago1705284720IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.05287766634.05512769
Claim52831452024-01-12 7:57:00744 days ago1705046220IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01240638148.5225
Claim52831022024-01-12 7:48:18744 days ago1705045698IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01057375126.58327752
Unstake And Stak...52809142024-01-12 0:23:24745 days ago1705019004IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.02585567128.32235743
Claim52647452024-01-09 17:28:12747 days ago1704821292IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01296386155.19637661
Claim52639652024-01-09 14:50:36747 days ago1704811836IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01353527162.03702593
Claim52605512024-01-09 3:16:18748 days ago1704770178IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01246591149.23526121
Unstake52605132024-01-09 3:08:36748 days ago1704769716IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.05792093634.05512769
Unstake52600672024-01-09 1:38:00748 days ago1704764280IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01183128126.56897046
Unstake52598722024-01-09 0:58:18748 days ago1704761898IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.0137232126.55576349
Claim52597932024-01-09 0:42:12748 days ago1704760932IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01071099128.2262003
Claim52597702024-01-09 0:37:36748 days ago1704760656IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01162038139.11303222
Claim52596722024-01-09 0:17:30748 days ago1704759450IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01171192140.4374469
Unstake And Stak...52595162024-01-08 23:45:30748 days ago1704757530IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.02058349131.66361233
Unstake52580082024-01-08 18:40:12748 days ago1704739212IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01803232186.65647675
Unstake52484692024-01-07 10:23:54749 days ago1704623034IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01419134149.94127481
Unstake52463882024-01-07 3:20:36750 days ago1704597636IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01150441126.5
Unstake52460502024-01-07 2:12:06750 days ago1704593526IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01436437149.26817057
Unstake52458302024-01-07 1:27:30750 days ago1704590850IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01356545148.5225
Unstake52457372024-01-07 1:08:54750 days ago1704589734IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01726312137.5
Unstake And Stak...52420362024-01-06 12:32:48750 days ago1704544368IN
0x37Ff7d6E...7617cD1B0
0 GLMR0.01831548132.79691646
View all transactions

View more zero value Internal Transactions in Advanced View mode

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
XENBox

Compiler Version
v0.8.17+commit.8df45f5f

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./XENCrypto.sol";

// XENBOX contract
contract XENBox is Context, ReentrancyGuard, Ownable {
    using SafeERC20 for XENCrypto;

    XENCrypto public xen;

    // 辅助计算,解决精度问题
    uint256 public constant DECIMALS = 1e8;
    // 税收
    uint256 public constant TAX = 5;
    // 质押周期时长
    uint256 public constant STAKE_PERIOD = 1;
    // 税收总数
    uint256 public totalTax = 0;
    // 质押的期数,从0开始
    uint256 public STAKE_TERM = 0;
    // 总质押数量
    uint256 public totalStaked = 0;
    // 当前协议质押APY
    uint256 public globalApy = 0;
    // 合约开始质押的时间戳,每次质押都会更新
    uint256 public stakeTs = 0;
    // 申请取回质押的XEN总数
    uint256 public totalUnstake = 0;
    // 记录当前周期的申请取回质押的XEN总数
    uint256 public currentUnstake = 0;

    // 映射地址是否位管理员
    mapping(address => bool) public isAdmin;
    // 记录用户个人质押数量
    mapping(address => uint256) public userStaked;
    // 记录用户开始质押的期数
    mapping(address => uint256) public userStakeTerm;
    // 记录APY对应的持续天数
    mapping(uint256 => uint256) public apyDays;
    // 记录用户申请取回质押的XEN数量
    mapping(address => uint256) public userUnstakeAmount;
    // 记录质押期数对应的APY
    mapping(uint256 => uint256) public stakeTermApy;
    // 记录APY变化的第一个周期
    mapping(uint256 => uint256) public apyTerm;
    // 记录用户申请取回质押的期数
    mapping(address => uint256) public userUnstakeTerm;

    // Constructor to set the owner of the pool
    constructor(address xenAddress) {
        xen = XENCrypto(xenAddress);
    }

    // modifier 验证是否是管理员或者owner
    modifier onlyAdmin() {
        require(
            isAdmin[_msgSender()] || _msgSender() == owner(),
            "Caller is not the admin"
        );
        _;
    }

    // 用户质押XEN进来
    function stake(uint256 amount) external nonReentrant {
        // 验证用户有足够的XEN
        require(xen.balanceOf(msg.sender) >= amount, "Insufficient balance");
        require(amount > 0, "XENBox: insufficient balance");
        // 验证用户没有正在质押的XEN
        require(userStaked[msg.sender] == 0, "You have staked, please unstake");
        // 更新用户总的质押数量
        totalStaked += amount;
        // 记录用户个人质押数量
        userStaked[msg.sender] = amount;
        // 记录用户开始登记质押的期数
        userStakeTerm[msg.sender] = STAKE_TERM;
        // 转移XEN到合约里
        xen.safeTransferFrom(msg.sender, address(this), amount);
    }

    // 用户增加质押XEN进来
    function addStake(uint256 amount) external nonReentrant {
        // 验证用户有足够的XEN
        require(xen.balanceOf(msg.sender) >= amount, "Insufficient balance");
        require(amount > 0, "XENBox: insufficient balance");
        // 验证用户有正在质押的XEN
        require(userStaked[msg.sender] > 0, "You haven't staked yet");
        uint256 stakeReward = getUserStakeReward(msg.sender);
        require(stakeReward > 0, "Reward is 0, please wait for the next term");

        // 更新用户总的质押数量
        totalStaked += amount;
        // 更新用户个人质押数量,把至今为止的质押奖励和增加质押的加进去
        userStaked[msg.sender] += stakeReward + amount;
        // 记录用户开始登记质押的期数
        userStakeTerm[msg.sender] = STAKE_TERM;
        // 转移XEN到合约里
        xen.safeTransferFrom(msg.sender, address(this), amount);
    }

    // 用户申请取回质押的XEN
    function unstake() external nonReentrant {
        require(
            userUnstakeAmount[msg.sender] == 0,
            "You have unstaked, please claim"
        );
        // 验证用户有正在质押的XEN
        require(userStaked[msg.sender] > 0, "You haven't staked yet");
        // 查用户的质押奖励
        uint256 stakeReward = getUserStakeReward(msg.sender);
        // 用户申请取回质押的XEN数量
        uint256 unstakeAmount = userStaked[msg.sender] + stakeReward;
        // 更新用户申请取回质押的XEN数量
        userUnstakeAmount[msg.sender] = unstakeAmount;
        // 更新取回质押的XEN总数
        totalUnstake += unstakeAmount;
        // 更新当前周期的申请取回质押的XEN总数
        currentUnstake += unstakeAmount;
        // 更新用户个人质押数量
        userStaked[msg.sender] = 0;
        // 更新用户申请取回质押的期数
        userUnstakeTerm[msg.sender] = STAKE_TERM;
    }

    // 领取申请取回质押的XEN
    function claim() external nonReentrant {
        // 验证用户申请取回质押的XEN数量
        require(userUnstakeAmount[msg.sender] > 0, "You haven't unstaked yet");
        // 验证用户申请取回质押的期数已经结束
        require(
            userUnstakeTerm[msg.sender] < STAKE_TERM,
            "The staking hasn't reached its expiration yet"
        );
        // 更新申请取回质押的XEN总数
        totalUnstake -= userUnstakeAmount[msg.sender];
        // 转移XEN到用户钱包里
        xen.safeTransfer(msg.sender, userUnstakeAmount[msg.sender]);
        // 更新用户申请取回质押的XEN数量
        userUnstakeAmount[msg.sender] = 0;
    }

    // 把合约里的XEN全部质押到XEN合约里
    function stakeAllToXen() public onlyAdmin {
        // 获取总质押数量
        uint256 amount = totalStaked;
        require(amount > 0, "XENBox: insufficient balance");
        // 查目前的APY
        uint256 currentApy = xen.getCurrentAPY();
        if (globalApy != currentApy) {
            // 如果不一致,更新当前协议质押APY
            globalApy = currentApy;
            // 更新APY变化的第一个周期
            apyTerm[currentApy] = STAKE_TERM + 1;
        }
        // 更新APY对应的持续期数
        apyDays[currentApy] += 1;
        // 更新质押周数
        STAKE_TERM += 1;
        // 更新质押期数对应的APY
        stakeTermApy[STAKE_TERM] = currentApy;
        // 更新合约开始质押的时间戳
        stakeTs = block.timestamp;
        // 质押到XEN合约里
        xen.stake(amount, STAKE_PERIOD);
    }

    // 取回所有质押的XEN
    function unstakeAllToXen() public onlyAdmin {
        // 计算这次取回奖励的XEN数量
        uint256 xenReward = canUnstake(false, 0, 0, 0);
        // 计算税收
        uint256 taxAmount = (xenReward * TAX) / 100;
        // 当前周期的申请取回质押的XEN总数
        uint256 currentUnstakeAmount = currentUnstake;
        require(xenReward > 0, "Reward is 0");

        // 把奖励更新到用户总的质押数量里
        totalStaked += xenReward - taxAmount;

        xen.withdraw();
        if (currentUnstakeAmount > 0) {
            // 把当前周期的申请取回质押的XEN总数更新到用户总的质押数量里
            totalStaked = totalStaked > currentUnstakeAmount
                ? totalStaked - currentUnstakeAmount
                : 0;
            // 更新当前周期的申请取回质押的XEN总数=0
            currentUnstake = 0;
        }
        // 取出税收
        xen.safeTransfer(owner(), taxAmount);
    }

    // 取回所有质押的XEN+质押
    function unstakeAndStakeAll() public nonReentrant onlyAdmin {
        unstakeAllToXen();
        stakeAllToXen();
    }

    // 设置管理员
    function setAdmin(address _admin, bool _isAdmin) external onlyOwner {
        isAdmin[_admin] = _isAdmin;
    }

    // approve最大值给XEN合约
    function approveXen() public onlyOwner {
        xen.approve(address(xen), type(uint256).max);
    }

    // 查看质押是否到期,可以取回XEN
    function canUnstake(
        bool _isAnticipate,
        uint256 _apy,
        uint256 _term,
        uint256 _amount
    ) public view returns (uint256) {
        if (_isAnticipate) {
            uint256 rate = (_apy * _term * 1_000_000) / xen.DAYS_IN_YEAR();
            return (_amount * rate) / 100_000_000;
        }
        // 获取用户质押信息
        XENCrypto.StakeInfo memory stakeInfo = xen.getUserStake();
        // 如果质押周期已经结束,返回可以取回的XEN数量
        if (block.timestamp > stakeInfo.maturityTs) {
            uint256 rate = (stakeInfo.apy * stakeInfo.term * 1_000_000) /
                xen.DAYS_IN_YEAR();
            return (stakeInfo.amount * rate) / 100_000_000;
        }
        return 0;
    }

    // 查询用户的质押奖励
    // 返回质押赚取的XEN数量,税收
    function getUserStakeReward(address _user) public view returns (uint256) {
        if (STAKE_TERM <= 1 || userStakeTerm[_user] == STAKE_TERM) {
            return 0;
        }
        // 验证用户有质押足够的XEN
        require(userStaked[_user] > 0, "You haven't staked");
        // 计算这次取回奖励的XEN数量
        // 计算用户质押期间赚取的XEN数量

        // 用户质押的XEN数量
        uint256 stakeAmount = userStaked[_user];
        // 先查目前的APY
        uint256 currentApy = globalApy;
        // 质押了多少期
        uint256 stakeTerm = 0;
        // 质押赚取的XEN数量
        uint256 stakeReward = 0;
        // 辅助计算变量
        uint256 fixed1 = 8;
        // 看目前的APY和用户开始质押的APY是否一致
        if (currentApy == stakeTermApy[userStakeTerm[_user] + 1]) {
            // 如果一致,计算用户质押期间赚取的XEN数量
            // 计算质押了多少期 = 质押总期数 - 用户开始登记质押的期数
            stakeTerm = STAKE_TERM - userStakeTerm[_user];
            require(
                stakeTerm > 0,
                "The staking hasn't reached its expiration yet"
            );
            // stakeTerm /10 得出商
            uint256 stakeTermQuotient = stakeTerm / fixed1;
            // stakeTerm %10 得出余数
            uint256 stakeTermRemainder = stakeTerm % fixed1;
            if (stakeTermQuotient > 0) {
                // a存储赚了多少XEN
                uint256 a = 0;
                for (uint256 i = 0; i < stakeTermQuotient; i++) {
                    a +=
                        ((stakeAmount + a) *
                            (((1 *
                                DECIMALS +
                                (((currentApy * 100 * DECIMALS) /
                                    (365 * 10000)) * (100 - TAX)) /
                                100) ** fixed1) / DECIMALS ** (fixed1 - 1))) /
                        DECIMALS -
                        (stakeAmount + a);
                }
                if (stakeTermRemainder > 0) {
                    stakeReward =
                        ((stakeAmount + a) *
                            (((1 *
                                DECIMALS +
                                (((currentApy * 100 * DECIMALS) /
                                    (365 * 10000)) * (100 - TAX)) /
                                100) ** stakeTermRemainder) /
                                DECIMALS ** (stakeTermRemainder - 1))) /
                        DECIMALS -
                        stakeAmount;
                } else {
                    stakeReward = a;
                }
            } else {
                // 计算质押赚取的XEN数量
                stakeReward =
                    (stakeAmount *
                        (((1 *
                            DECIMALS +
                            (((currentApy * 100 * DECIMALS) / (365 * 10000)) *
                                (100 - TAX)) /
                            100) ** stakeTerm) / DECIMALS ** (stakeTerm - 1))) /
                    DECIMALS -
                    stakeAmount;
            }
        } else {
            // 计算质押了多少期
            stakeTerm = STAKE_TERM - userStakeTerm[_user];
            require(
                stakeTerm > 0,
                "The staking hasn't reached its expiration yet"
            );
            // 如果不一致,计算用户质押期间赚取的XEN数量
            // 从用户开始质押的APY开始计算
            for (
                uint256 j = stakeTermApy[userStakeTerm[_user] + 1];
                j >= currentApy;
                j--
            ) {
                if (j == stakeTermApy[userStakeTerm[_user] + 1]) {
                    stakeTerm = apyDays[j] - userStakeTerm[_user];
                } else {
                    stakeTerm = apyDays[j];
                }
                // 计算质押赚取的XEN数量
                // stakeTerm /10 得出商
                uint256 stakeTermQuotient = stakeTerm / fixed1;
                // stakeTerm %10 得出余数
                uint256 stakeTermRemainder = stakeTerm % fixed1;
                if (stakeTermQuotient > 0) {
                    // a存储赚了多少XEN
                    uint256 a = 0;
                    for (uint256 i = 0; i < stakeTermQuotient; i++) {
                        a +=
                            ((stakeAmount + a) *
                                (((1 *
                                    DECIMALS +
                                    (((j * 100 * DECIMALS) / (365 * 10000)) *
                                        (100 - TAX)) /
                                    100) ** fixed1) /
                                    DECIMALS ** (fixed1 - 1))) /
                            DECIMALS -
                            (stakeAmount + a);
                    }
                    if (stakeTermRemainder > 0) {
                        stakeReward +=
                            ((stakeAmount + a) *
                                (((1 *
                                    DECIMALS +
                                    (((j * 100 * DECIMALS) / (365 * 10000)) *
                                        (100 - TAX)) /
                                    100) ** stakeTermRemainder) /
                                    DECIMALS ** (stakeTermRemainder - 1))) /
                            DECIMALS -
                            stakeAmount;
                    } else {
                        stakeReward += a;
                    }
                } else {
                    // 计算质押赚取的XEN数量
                    stakeReward +=
                        (stakeAmount *
                            (((1 *
                                DECIMALS +
                                (((j * 100 * DECIMALS) / (365 * 10000)) *
                                    (100 - TAX)) /
                                100) ** stakeTerm) /
                                DECIMALS ** (stakeTerm - 1))) /
                        DECIMALS -
                        stakeAmount;
                }
                stakeAmount = userStaked[_user] + stakeReward;
            }
        }

        return stakeReward;
    }
}

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

pragma solidity ^0.8.0;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

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

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

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

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

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

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

File 3 of 19 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)

pragma solidity ^0.8.0;

import "../utils/introspection/IERC165.sol";

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

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

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

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

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

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

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}

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

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.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;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    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));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    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");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
     * 0 before setting it to a non-zero value.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @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");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @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).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // 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 cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

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

pragma solidity ^0.8.1;

/**
 * @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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 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://consensys.net/diligence/blog/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.8.0/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 functionCallWithValue(target, data, 0, "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");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, 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) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, 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) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or 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 {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // 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
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

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

// SPDX-License-Identifier: BSD-4-Clause
/*
 * ABDK Math 64.64 Smart Contract Library.  Copyright © 2019 by ABDK Consulting.
 * Author: Mikhail Vladimirov <[email protected]>
 */
pragma solidity ^0.8.0;

/**
 * Smart contract library of mathematical functions operating with signed
 * 64.64-bit fixed point numbers.  Signed 64.64-bit fixed point number is
 * basically a simple fraction whose numerator is signed 128-bit integer and
 * denominator is 2^64.  As long as denominator is always the same, there is no
 * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
 * represented by int128 type holding only the numerator.
 */
library ABDKMath64x64 {
  /*
   * Minimum value signed 64.64-bit fixed point number may have. 
   */
  int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;

  /*
   * Maximum value signed 64.64-bit fixed point number may have. 
   */
  int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

  /**
   * Convert signed 256-bit integer number into signed 64.64-bit fixed point
   * number.  Revert on overflow.
   *
   * @param x signed 256-bit integer number
   * @return signed 64.64-bit fixed point number
   */
  function fromInt (int256 x) internal pure returns (int128) {
    unchecked {
      require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
      return int128 (x << 64);
    }
  }

  /**
   * Convert signed 64.64 fixed point number into signed 64-bit integer number
   * rounding down.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 64-bit integer number
   */
  function toInt (int128 x) internal pure returns (int64) {
    unchecked {
      return int64 (x >> 64);
    }
  }

  /**
   * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
   * number.  Revert on overflow.
   *
   * @param x unsigned 256-bit integer number
   * @return signed 64.64-bit fixed point number
   */
  function fromUInt (uint256 x) internal pure returns (int128) {
    unchecked {
      require (x <= 0x7FFFFFFFFFFFFFFF);
      return int128 (int256 (x << 64));
    }
  }

  /**
   * Convert signed 64.64 fixed point number into unsigned 64-bit integer
   * number rounding down.  Revert on underflow.
   *
   * @param x signed 64.64-bit fixed point number
   * @return unsigned 64-bit integer number
   */
  function toUInt (int128 x) internal pure returns (uint64) {
    unchecked {
      require (x >= 0);
      return uint64 (uint128 (x >> 64));
    }
  }

  /**
   * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
   * number rounding down.  Revert on overflow.
   *
   * @param x signed 128.128-bin fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function from128x128 (int256 x) internal pure returns (int128) {
    unchecked {
      int256 result = x >> 64;
      require (result >= MIN_64x64 && result <= MAX_64x64);
      return int128 (result);
    }
  }

  /**
   * Convert signed 64.64 fixed point number into signed 128.128 fixed point
   * number.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 128.128 fixed point number
   */
  function to128x128 (int128 x) internal pure returns (int256) {
    unchecked {
      return int256 (x) << 64;
    }
  }

  /**
   * Calculate x + y.  Revert on overflow.
   *
   * @param x signed 64.64-bit fixed point number
   * @param y signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function add (int128 x, int128 y) internal pure returns (int128) {
    unchecked {
      int256 result = int256(x) + y;
      require (result >= MIN_64x64 && result <= MAX_64x64);
      return int128 (result);
    }
  }

  /**
   * Calculate x - y.  Revert on overflow.
   *
   * @param x signed 64.64-bit fixed point number
   * @param y signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function sub (int128 x, int128 y) internal pure returns (int128) {
    unchecked {
      int256 result = int256(x) - y;
      require (result >= MIN_64x64 && result <= MAX_64x64);
      return int128 (result);
    }
  }

  /**
   * Calculate x * y rounding down.  Revert on overflow.
   *
   * @param x signed 64.64-bit fixed point number
   * @param y signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function mul (int128 x, int128 y) internal pure returns (int128) {
    unchecked {
      int256 result = int256(x) * y >> 64;
      require (result >= MIN_64x64 && result <= MAX_64x64);
      return int128 (result);
    }
  }

  /**
   * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
   * number and y is signed 256-bit integer number.  Revert on overflow.
   *
   * @param x signed 64.64 fixed point number
   * @param y signed 256-bit integer number
   * @return signed 256-bit integer number
   */
  function muli (int128 x, int256 y) internal pure returns (int256) {
    unchecked {
      if (x == MIN_64x64) {
        require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
          y <= 0x1000000000000000000000000000000000000000000000000);
        return -y << 63;
      } else {
        bool negativeResult = false;
        if (x < 0) {
          x = -x;
          negativeResult = true;
        }
        if (y < 0) {
          y = -y; // We rely on overflow behavior here
          negativeResult = !negativeResult;
        }
        uint256 absoluteResult = mulu (x, uint256 (y));
        if (negativeResult) {
          require (absoluteResult <=
            0x8000000000000000000000000000000000000000000000000000000000000000);
          return -int256 (absoluteResult); // We rely on overflow behavior here
        } else {
          require (absoluteResult <=
            0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
          return int256 (absoluteResult);
        }
      }
    }
  }

  /**
   * Calculate x * y rounding down, where x is signed 64.64 fixed point number
   * and y is unsigned 256-bit integer number.  Revert on overflow.
   *
   * @param x signed 64.64 fixed point number
   * @param y unsigned 256-bit integer number
   * @return unsigned 256-bit integer number
   */
  function mulu (int128 x, uint256 y) internal pure returns (uint256) {
    unchecked {
      if (y == 0) return 0;

      require (x >= 0);

      uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
      uint256 hi = uint256 (int256 (x)) * (y >> 128);

      require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
      hi <<= 64;

      require (hi <=
        0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
      return hi + lo;
    }
  }

  /**
   * Calculate x / y rounding towards zero.  Revert on overflow or when y is
   * zero.
   *
   * @param x signed 64.64-bit fixed point number
   * @param y signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function div (int128 x, int128 y) internal pure returns (int128) {
    unchecked {
      require (y != 0);
      int256 result = (int256 (x) << 64) / y;
      require (result >= MIN_64x64 && result <= MAX_64x64);
      return int128 (result);
    }
  }

  /**
   * Calculate x / y rounding towards zero, where x and y are signed 256-bit
   * integer numbers.  Revert on overflow or when y is zero.
   *
   * @param x signed 256-bit integer number
   * @param y signed 256-bit integer number
   * @return signed 64.64-bit fixed point number
   */
  function divi (int256 x, int256 y) internal pure returns (int128) {
    unchecked {
      require (y != 0);

      bool negativeResult = false;
      if (x < 0) {
        x = -x; // We rely on overflow behavior here
        negativeResult = true;
      }
      if (y < 0) {
        y = -y; // We rely on overflow behavior here
        negativeResult = !negativeResult;
      }
      uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
      if (negativeResult) {
        require (absoluteResult <= 0x80000000000000000000000000000000);
        return -int128 (absoluteResult); // We rely on overflow behavior here
      } else {
        require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
        return int128 (absoluteResult); // We rely on overflow behavior here
      }
    }
  }

  /**
   * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
   * integer numbers.  Revert on overflow or when y is zero.
   *
   * @param x unsigned 256-bit integer number
   * @param y unsigned 256-bit integer number
   * @return signed 64.64-bit fixed point number
   */
  function divu (uint256 x, uint256 y) internal pure returns (int128) {
    unchecked {
      require (y != 0);
      uint128 result = divuu (x, y);
      require (result <= uint128 (MAX_64x64));
      return int128 (result);
    }
  }

  /**
   * Calculate -x.  Revert on overflow.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function neg (int128 x) internal pure returns (int128) {
    unchecked {
      require (x != MIN_64x64);
      return -x;
    }
  }

  /**
   * Calculate |x|.  Revert on overflow.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function abs (int128 x) internal pure returns (int128) {
    unchecked {
      require (x != MIN_64x64);
      return x < 0 ? -x : x;
    }
  }

  /**
   * Calculate 1 / x rounding towards zero.  Revert on overflow or when x is
   * zero.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function inv (int128 x) internal pure returns (int128) {
    unchecked {
      require (x != 0);
      int256 result = int256 (0x100000000000000000000000000000000) / x;
      require (result >= MIN_64x64 && result <= MAX_64x64);
      return int128 (result);
    }
  }

  /**
   * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
   *
   * @param x signed 64.64-bit fixed point number
   * @param y signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function avg (int128 x, int128 y) internal pure returns (int128) {
    unchecked {
      return int128 ((int256 (x) + int256 (y)) >> 1);
    }
  }

  /**
   * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
   * Revert on overflow or in case x * y is negative.
   *
   * @param x signed 64.64-bit fixed point number
   * @param y signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function gavg (int128 x, int128 y) internal pure returns (int128) {
    unchecked {
      int256 m = int256 (x) * int256 (y);
      require (m >= 0);
      require (m <
          0x4000000000000000000000000000000000000000000000000000000000000000);
      return int128 (sqrtu (uint256 (m)));
    }
  }

  /**
   * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
   * and y is unsigned 256-bit integer number.  Revert on overflow.
   *
   * @param x signed 64.64-bit fixed point number
   * @param y uint256 value
   * @return signed 64.64-bit fixed point number
   */
  function pow (int128 x, uint256 y) internal pure returns (int128) {
    unchecked {
      bool negative = x < 0 && y & 1 == 1;

      uint256 absX = uint128 (x < 0 ? -x : x);
      uint256 absResult;
      absResult = 0x100000000000000000000000000000000;

      if (absX <= 0x10000000000000000) {
        absX <<= 63;
        while (y != 0) {
          if (y & 0x1 != 0) {
            absResult = absResult * absX >> 127;
          }
          absX = absX * absX >> 127;

          if (y & 0x2 != 0) {
            absResult = absResult * absX >> 127;
          }
          absX = absX * absX >> 127;

          if (y & 0x4 != 0) {
            absResult = absResult * absX >> 127;
          }
          absX = absX * absX >> 127;

          if (y & 0x8 != 0) {
            absResult = absResult * absX >> 127;
          }
          absX = absX * absX >> 127;

          y >>= 4;
        }

        absResult >>= 64;
      } else {
        uint256 absXShift = 63;
        if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
        if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
        if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
        if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
        if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
        if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }

        uint256 resultShift = 0;
        while (y != 0) {
          require (absXShift < 64);

          if (y & 0x1 != 0) {
            absResult = absResult * absX >> 127;
            resultShift += absXShift;
            if (absResult > 0x100000000000000000000000000000000) {
              absResult >>= 1;
              resultShift += 1;
            }
          }
          absX = absX * absX >> 127;
          absXShift <<= 1;
          if (absX >= 0x100000000000000000000000000000000) {
              absX >>= 1;
              absXShift += 1;
          }

          y >>= 1;
        }

        require (resultShift < 64);
        absResult >>= 64 - resultShift;
      }
      int256 result = negative ? -int256 (absResult) : int256 (absResult);
      require (result >= MIN_64x64 && result <= MAX_64x64);
      return int128 (result);
    }
  }

  /**
   * Calculate sqrt (x) rounding down.  Revert if x < 0.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function sqrt (int128 x) internal pure returns (int128) {
    unchecked {
      require (x >= 0);
      return int128 (sqrtu (uint256 (int256 (x)) << 64));
    }
  }

  /**
   * Calculate binary logarithm of x.  Revert if x <= 0.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function log_2 (int128 x) internal pure returns (int128) {
    unchecked {
      require (x > 0);

      int256 msb = 0;
      int256 xc = x;
      if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
      if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
      if (xc >= 0x10000) { xc >>= 16; msb += 16; }
      if (xc >= 0x100) { xc >>= 8; msb += 8; }
      if (xc >= 0x10) { xc >>= 4; msb += 4; }
      if (xc >= 0x4) { xc >>= 2; msb += 2; }
      if (xc >= 0x2) msb += 1;  // No need to shift xc anymore

      int256 result = msb - 64 << 64;
      uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb);
      for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
        ux *= ux;
        uint256 b = ux >> 255;
        ux >>= 127 + b;
        result += bit * int256 (b);
      }

      return int128 (result);
    }
  }

  /**
   * Calculate natural logarithm of x.  Revert if x <= 0.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function ln (int128 x) internal pure returns (int128) {
    unchecked {
      require (x > 0);

      return int128 (int256 (
          uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128));
    }
  }

  /**
   * Calculate binary exponent of x.  Revert on overflow.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function exp_2 (int128 x) internal pure returns (int128) {
    unchecked {
      require (x < 0x400000000000000000); // Overflow

      if (x < -0x400000000000000000) return 0; // Underflow

      uint256 result = 0x80000000000000000000000000000000;

      if (x & 0x8000000000000000 > 0)
        result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
      if (x & 0x4000000000000000 > 0)
        result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
      if (x & 0x2000000000000000 > 0)
        result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
      if (x & 0x1000000000000000 > 0)
        result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
      if (x & 0x800000000000000 > 0)
        result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
      if (x & 0x400000000000000 > 0)
        result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
      if (x & 0x200000000000000 > 0)
        result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
      if (x & 0x100000000000000 > 0)
        result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
      if (x & 0x80000000000000 > 0)
        result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
      if (x & 0x40000000000000 > 0)
        result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
      if (x & 0x20000000000000 > 0)
        result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
      if (x & 0x10000000000000 > 0)
        result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
      if (x & 0x8000000000000 > 0)
        result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
      if (x & 0x4000000000000 > 0)
        result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
      if (x & 0x2000000000000 > 0)
        result = result * 0x1000162E525EE054754457D5995292026 >> 128;
      if (x & 0x1000000000000 > 0)
        result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
      if (x & 0x800000000000 > 0)
        result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
      if (x & 0x400000000000 > 0)
        result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
      if (x & 0x200000000000 > 0)
        result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
      if (x & 0x100000000000 > 0)
        result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
      if (x & 0x80000000000 > 0)
        result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
      if (x & 0x40000000000 > 0)
        result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
      if (x & 0x20000000000 > 0)
        result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
      if (x & 0x10000000000 > 0)
        result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
      if (x & 0x8000000000 > 0)
        result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
      if (x & 0x4000000000 > 0)
        result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
      if (x & 0x2000000000 > 0)
        result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
      if (x & 0x1000000000 > 0)
        result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
      if (x & 0x800000000 > 0)
        result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
      if (x & 0x400000000 > 0)
        result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
      if (x & 0x200000000 > 0)
        result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
      if (x & 0x100000000 > 0)
        result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
      if (x & 0x80000000 > 0)
        result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
      if (x & 0x40000000 > 0)
        result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
      if (x & 0x20000000 > 0)
        result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
      if (x & 0x10000000 > 0)
        result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
      if (x & 0x8000000 > 0)
        result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
      if (x & 0x4000000 > 0)
        result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
      if (x & 0x2000000 > 0)
        result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
      if (x & 0x1000000 > 0)
        result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
      if (x & 0x800000 > 0)
        result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
      if (x & 0x400000 > 0)
        result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
      if (x & 0x200000 > 0)
        result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
      if (x & 0x100000 > 0)
        result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
      if (x & 0x80000 > 0)
        result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
      if (x & 0x40000 > 0)
        result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
      if (x & 0x20000 > 0)
        result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
      if (x & 0x10000 > 0)
        result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
      if (x & 0x8000 > 0)
        result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
      if (x & 0x4000 > 0)
        result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
      if (x & 0x2000 > 0)
        result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
      if (x & 0x1000 > 0)
        result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
      if (x & 0x800 > 0)
        result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
      if (x & 0x400 > 0)
        result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
      if (x & 0x200 > 0)
        result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
      if (x & 0x100 > 0)
        result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
      if (x & 0x80 > 0)
        result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
      if (x & 0x40 > 0)
        result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
      if (x & 0x20 > 0)
        result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
      if (x & 0x10 > 0)
        result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
      if (x & 0x8 > 0)
        result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
      if (x & 0x4 > 0)
        result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
      if (x & 0x2 > 0)
        result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
      if (x & 0x1 > 0)
        result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;

      result >>= uint256 (int256 (63 - (x >> 64)));
      require (result <= uint256 (int256 (MAX_64x64)));

      return int128 (int256 (result));
    }
  }

  /**
   * Calculate natural exponent of x.  Revert on overflow.
   *
   * @param x signed 64.64-bit fixed point number
   * @return signed 64.64-bit fixed point number
   */
  function exp (int128 x) internal pure returns (int128) {
    unchecked {
      require (x < 0x400000000000000000); // Overflow

      if (x < -0x400000000000000000) return 0; // Underflow

      return exp_2 (
          int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
    }
  }

  /**
   * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
   * integer numbers.  Revert on overflow or when y is zero.
   *
   * @param x unsigned 256-bit integer number
   * @param y unsigned 256-bit integer number
   * @return unsigned 64.64-bit fixed point number
   */
  function divuu (uint256 x, uint256 y) private pure returns (uint128) {
    unchecked {
      require (y != 0);

      uint256 result;

      if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
        result = (x << 64) / y;
      else {
        uint256 msb = 192;
        uint256 xc = x >> 192;
        if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
        if (xc >= 0x10000) { xc >>= 16; msb += 16; }
        if (xc >= 0x100) { xc >>= 8; msb += 8; }
        if (xc >= 0x10) { xc >>= 4; msb += 4; }
        if (xc >= 0x4) { xc >>= 2; msb += 2; }
        if (xc >= 0x2) msb += 1;  // No need to shift xc anymore

        result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
        require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);

        uint256 hi = result * (y >> 128);
        uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);

        uint256 xh = x >> 192;
        uint256 xl = x << 64;

        if (xl < lo) xh -= 1;
        xl -= lo; // We rely on overflow behavior here
        lo = hi << 128;
        if (xl < lo) xh -= 1;
        xl -= lo; // We rely on overflow behavior here

        assert (xh == hi >> 128);

        result += xl / y;
      }

      require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
      return uint128 (result);
    }
  }

  /**
   * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
   * number.
   *
   * @param x unsigned 256-bit integer number
   * @return unsigned 128-bit integer number
   */
  function sqrtu (uint256 x) private pure returns (uint128) {
    unchecked {
      if (x == 0) return 0;
      else {
        uint256 xx = x;
        uint256 r = 1;
        if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
        if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
        if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
        if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
        if (xx >= 0x100) { xx >>= 8; r <<= 4; }
        if (xx >= 0x10) { xx >>= 4; r <<= 2; }
        if (xx >= 0x4) { r <<= 1; }
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1;
        r = (r + x / r) >> 1; // Seven iterations should be enough
        uint256 r1 = x / r;
        return uint128 (r < r1 ? r : r1);
      }
    }
  }
}

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

interface IBurnableToken {
    function burn(address user, uint256 amount) external;
}

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

interface IBurnRedeemable {
    event Redeemed(
        address indexed user,
        address indexed xenContract,
        address indexed tokenContract,
        uint256 xenAmount,
        uint256 tokenAmount
    );

    function onTokenBurned(address user, uint256 amount) external;
}

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

interface IRankedMintingToken {
    event RankClaimed(address indexed user, uint256 term, uint256 rank);

    event MintClaimed(address indexed user, uint256 rewardAmount);

    function claimRank(uint256 term) external;

    function claimMintReward() external;
}

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

interface IStakingToken {
    event Staked(address indexed user, uint256 amount, uint256 term);

    event Withdrawn(address indexed user, uint256 amount, uint256 reward);

    function stake(uint256 amount, uint256 term) external;

    function withdraw() external;
}

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

import "abdk-libraries-solidity/ABDKMath64x64.sol";

library MathX {
    function min(uint256 a, uint256 b) external pure returns (uint256) {
        if (a > b) return b;
        return a;
    }

    function max(uint256 a, uint256 b) external pure returns (uint256) {
        if (a > b) return a;
        return b;
    }

    function logX64(uint256 x) external pure returns (int128) {
        return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));
    }
}

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

import "./MathX.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "abdk-libraries-solidity/ABDKMath64x64.sol";
import "./interfaces/IStakingToken.sol";
import "./interfaces/IRankedMintingToken.sol";
import "./interfaces/IBurnableToken.sol";
import "./interfaces/IBurnRedeemable.sol";

contract XENCrypto is
    Context,
    IRankedMintingToken,
    IStakingToken,
    IBurnableToken,
    ERC20("XEN Crypto", "XEN")
{
    using MathX for uint256;
    using ABDKMath64x64 for int128;
    using ABDKMath64x64 for uint256;

    // INTERNAL TYPE TO DESCRIBE A XEN MINT INFO
    struct MintInfo {
        address user;
        uint256 term;
        uint256 maturityTs;
        uint256 rank;
        uint256 amplifier;
        uint256 eaaRate;
    }

    // INTERNAL TYPE TO DESCRIBE A XEN STAKE
    struct StakeInfo {
        uint256 term;
        uint256 maturityTs;
        uint256 amount;
        uint256 apy;
    }

    // PUBLIC CONSTANTS

    uint256 public constant SECONDS_IN_DAY = 3_600 * 24;
    uint256 public constant DAYS_IN_YEAR = 365;

    uint256 public constant GENESIS_RANK = 1;

    uint256 public constant MIN_TERM = 1 * SECONDS_IN_DAY - 1;
    uint256 public constant MAX_TERM_START = 100 * SECONDS_IN_DAY;
    uint256 public constant MAX_TERM_END = 1_000 * SECONDS_IN_DAY;
    uint256 public constant TERM_AMPLIFIER = 15;
    uint256 public constant TERM_AMPLIFIER_THRESHOLD = 5_000;
    uint256 public constant REWARD_AMPLIFIER_START = 3_000;
    uint256 public constant REWARD_AMPLIFIER_END = 1;
    uint256 public constant EAA_PM_START = 100;
    uint256 public constant EAA_PM_STEP = 1;
    uint256 public constant EAA_RANK_STEP = 100_000;
    uint256 public constant WITHDRAWAL_WINDOW_DAYS = 7;
    uint256 public constant MAX_PENALTY_PCT = 99;

    uint256 public constant XEN_MIN_STAKE = 0;

    uint256 public constant XEN_MIN_BURN = 0;

    uint256 public constant XEN_APY_START = 20;
    uint256 public constant XEN_APY_DAYS_STEP = 90;
    uint256 public constant XEN_APY_END = 2;

    string public constant AUTHORS = "@MrJackLevin @lbelyaev faircrypto.org";

    // PUBLIC STATE, READABLE VIA NAMESAKE GETTERS

    uint256 public immutable genesisTs;
    uint256 public globalRank = GENESIS_RANK;
    uint256 public activeMinters;
    uint256 public activeStakes;
    uint256 public totalXenStaked;
    // user address => XEN mint info
    mapping(address => MintInfo) public userMints;
    // user address => XEN stake info
    mapping(address => StakeInfo) public userStakes;
    // user address => XEN burn amount
    mapping(address => uint256) public userBurns;

    // CONSTRUCTOR
    constructor() {
        genesisTs = block.timestamp;
    }

    // PRIVATE METHODS

    /**
     * @dev calculates current MaxTerm based on Global Rank
     *      (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)
     */
    function _calculateMaxTerm() private view returns (uint256) {
        if (globalRank > TERM_AMPLIFIER_THRESHOLD) {
            uint256 delta = globalRank
                .fromUInt()
                .log_2()
                .mul(TERM_AMPLIFIER.fromUInt())
                .toUInt();
            uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;
            return MathX.min(newMax, MAX_TERM_END);
        }
        return MAX_TERM_START;
    }

    /**
     * @dev calculates Withdrawal Penalty depending on lateness
     */
    function _penalty(uint256 secsLate) private pure returns (uint256) {
        // =MIN(2^(daysLate+3)/window-1,99)
        uint256 daysLate = secsLate / SECONDS_IN_DAY;
        if (daysLate > WITHDRAWAL_WINDOW_DAYS - 1) return MAX_PENALTY_PCT;
        uint256 penalty = (uint256(1) << (daysLate + 3)) /
            WITHDRAWAL_WINDOW_DAYS -
            1;
        return MathX.min(penalty, MAX_PENALTY_PCT);
    }

    /**
     * @dev calculates net Mint Reward (adjusted for Penalty)
     */
    function _calculateMintReward(
        uint256 cRank,
        uint256 term,
        uint256 maturityTs,
        uint256 amplifier,
        uint256 eeaRate
    ) private view returns (uint256) {
        uint256 secsLate = block.timestamp - maturityTs;
        uint256 penalty = _penalty(secsLate);
        uint256 rankDelta = MathX.max(globalRank - cRank, 2);
        uint256 EAA = (1_000 + eeaRate);
        uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);
        return (reward * (100 - penalty)) / 100;
    }

    /**
     * @dev cleans up User Mint storage (gets some Gas credit;))
     */
    function _cleanUpUserMint() private {
        delete userMints[_msgSender()];
        activeMinters--;
    }

    /**
     * @dev calculates XEN Stake Reward
     */
    function _calculateStakeReward(
        uint256 amount,
        uint256 term,
        uint256 maturityTs,
        uint256 apy
    ) private view returns (uint256) {
        if (block.timestamp > maturityTs) {
            uint256 rate = (apy * term * 1_000_000) / DAYS_IN_YEAR;
            return (amount * rate) / 100_000_000;
        }
        return 0;
    }

    /**
     * @dev calculates Reward Amplifier
     */
    function _calculateRewardAmplifier() private view returns (uint256) {
        uint256 amplifierDecrease = (block.timestamp - genesisTs) /
            SECONDS_IN_DAY;
        if (amplifierDecrease < REWARD_AMPLIFIER_START) {
            return
                MathX.max(
                    REWARD_AMPLIFIER_START - amplifierDecrease,
                    REWARD_AMPLIFIER_END
                );
        } else {
            return REWARD_AMPLIFIER_END;
        }
    }

    /**
     * @dev calculates Early Adopter Amplifier Rate (in 1/000ths)
     *      actual EAA is (1_000 + EAAR) / 1_000
     */
    function _calculateEAARate() private view returns (uint256) {
        uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;
        if (decrease > EAA_PM_START) return 0;
        return EAA_PM_START - decrease;
    }

    /**
     * @dev calculates APY (in %)
     */
    function _calculateAPY() private view returns (uint256) {
        uint256 decrease = (block.timestamp - genesisTs) /
            (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);
        if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;
        return XEN_APY_START - decrease;
    }

    /**
     * @dev creates User Stake
     */
    function _createStake(uint256 amount, uint256 term) private {
        userStakes[_msgSender()] = StakeInfo({
            term: term,
            maturityTs: block.timestamp + term * SECONDS_IN_DAY,
            amount: amount,
            apy: _calculateAPY()
        });
        activeStakes++;
        totalXenStaked += amount;
    }

    // PUBLIC CONVENIENCE GETTERS

    /**
     * @dev calculates gross Mint Reward
     */
    function getGrossReward(
        uint256 rankDelta,
        uint256 amplifier,
        uint256 term,
        uint256 eaa
    ) public pure returns (uint256) {
        int128 log128 = rankDelta.fromUInt().log_2();
        int128 reward128 = log128
            .mul(amplifier.fromUInt())
            .mul(term.fromUInt())
            .mul(eaa.fromUInt());
        return reward128.div(uint256(1_000).fromUInt()).toUInt();
    }

    /**
     * @dev returns User Mint object associated with User account address
     */
    function getUserMint() external view returns (MintInfo memory) {
        return userMints[_msgSender()];
    }

    /**
     * @dev returns XEN Stake object associated with User account address
     */
    function getUserStake() external view returns (StakeInfo memory) {
        return userStakes[_msgSender()];
    }

    /**
     * @dev returns current AMP
     */
    function getCurrentAMP() external view returns (uint256) {
        return _calculateRewardAmplifier();
    }

    /**
     * @dev returns current EAA Rate
     */
    function getCurrentEAAR() external view returns (uint256) {
        return _calculateEAARate();
    }

    /**
     * @dev returns current APY
     */
    function getCurrentAPY() external view returns (uint256) {
        return _calculateAPY();
    }

    /**
     * @dev returns current MaxTerm
     */
    function getCurrentMaxTerm() external view returns (uint256) {
        return _calculateMaxTerm();
    }

    // PUBLIC STATE-CHANGING METHODS

    /**
     * @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)
     */
    function claimRank(uint256 term) external {
        uint256 termSec = term * SECONDS_IN_DAY;
        require(termSec > MIN_TERM, "CRank: Term less than min");
        require(
            termSec < _calculateMaxTerm() + 1,
            "CRank: Term more than current max term"
        );
        require(
            userMints[_msgSender()].rank == 0,
            "CRank: Mint already in progress"
        );

        // create and store new MintInfo
        MintInfo memory mintInfo = MintInfo({
            user: _msgSender(),
            term: term,
            maturityTs: block.timestamp + termSec,
            rank: globalRank,
            amplifier: _calculateRewardAmplifier(),
            eaaRate: _calculateEAARate()
        });
        userMints[_msgSender()] = mintInfo;
        activeMinters++;
        emit RankClaimed(_msgSender(), term, globalRank++);
    }

    /**
     * @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN
     */
    function claimMintReward() external {
        MintInfo memory mintInfo = userMints[_msgSender()];
        require(mintInfo.rank > 0, "CRank: No mint exists");
        require(
            block.timestamp > mintInfo.maturityTs,
            "CRank: Mint maturity not reached"
        );

        // calculate reward and mint tokens
        uint256 rewardAmount = _calculateMintReward(
            mintInfo.rank,
            mintInfo.term,
            mintInfo.maturityTs,
            mintInfo.amplifier,
            mintInfo.eaaRate
        ) * 1 ether;
        _mint(_msgSender(), rewardAmount);

        _cleanUpUserMint();
        emit MintClaimed(_msgSender(), rewardAmount);
    }

    /**
     * @dev  ends minting upon maturity (and within permitted Withdrawal time Window)
     *       mints XEN coins and splits them between User and designated other address
     */
    function claimMintRewardAndShare(address other, uint256 pct) external {
        MintInfo memory mintInfo = userMints[_msgSender()];
        require(other != address(0), "CRank: Cannot share with zero address");
        require(pct > 0, "CRank: Cannot share zero percent");
        require(pct < 101, "CRank: Cannot share 100+ percent");
        require(mintInfo.rank > 0, "CRank: No mint exists");
        require(
            block.timestamp > mintInfo.maturityTs,
            "CRank: Mint maturity not reached"
        );

        // calculate reward
        uint256 rewardAmount = _calculateMintReward(
            mintInfo.rank,
            mintInfo.term,
            mintInfo.maturityTs,
            mintInfo.amplifier,
            mintInfo.eaaRate
        ) * 1 ether;
        uint256 sharedReward = (rewardAmount * pct) / 100;
        uint256 ownReward = rewardAmount - sharedReward;

        // mint reward tokens
        _mint(_msgSender(), ownReward);
        _mint(other, sharedReward);

        _cleanUpUserMint();
        emit MintClaimed(_msgSender(), rewardAmount);
    }

    /**
     * @dev  ends minting upon maturity (and within permitted Withdrawal time Window)
     *       mints XEN coins and stakes 'pct' of it for 'term'
     */
    function claimMintRewardAndStake(uint256 pct, uint256 term) external {
        MintInfo memory mintInfo = userMints[_msgSender()];
        // require(pct > 0, "CRank: Cannot share zero percent");
        require(pct < 101, "CRank: Cannot share >100 percent");
        require(mintInfo.rank > 0, "CRank: No mint exists");
        require(
            block.timestamp > mintInfo.maturityTs,
            "CRank: Mint maturity not reached"
        );

        // calculate reward
        uint256 rewardAmount = _calculateMintReward(
            mintInfo.rank,
            mintInfo.term,
            mintInfo.maturityTs,
            mintInfo.amplifier,
            mintInfo.eaaRate
        ) * 1 ether;
        uint256 stakedReward = (rewardAmount * pct) / 100;
        uint256 ownReward = rewardAmount - stakedReward;

        // mint reward tokens part
        _mint(_msgSender(), ownReward);
        _cleanUpUserMint();
        emit MintClaimed(_msgSender(), rewardAmount);

        // nothing to burn since we haven't minted this part yet
        // stake extra tokens part
        require(stakedReward > XEN_MIN_STAKE, "XEN: Below min stake");
        require(term * SECONDS_IN_DAY > MIN_TERM, "XEN: Below min stake term");
        require(
            term * SECONDS_IN_DAY < MAX_TERM_END + 1,
            "XEN: Above max stake term"
        );
        require(userStakes[_msgSender()].amount == 0, "XEN: stake exists");

        _createStake(stakedReward, term);
        emit Staked(_msgSender(), stakedReward, term);
    }

    /**
     * @dev initiates XEN Stake in amount for a term (days)
     */
    function stake(uint256 amount, uint256 term) external {
        require(balanceOf(_msgSender()) >= amount, "XEN: not enough balance");
        require(amount > XEN_MIN_STAKE, "XEN: Below min stake");
        require(term * SECONDS_IN_DAY > MIN_TERM, "XEN: Below min stake term");
        require(
            term * SECONDS_IN_DAY < MAX_TERM_END + 1,
            "XEN: Above max stake term"
        );
        require(userStakes[_msgSender()].amount == 0, "XEN: stake exists");

        // burn staked XEN
        _burn(_msgSender(), amount);
        // create XEN Stake
        _createStake(amount, term);
        emit Staked(_msgSender(), amount, term);
    }

    /**
     * @dev ends XEN Stake and gets reward if the Stake is mature
     */
    function withdraw() external {
        StakeInfo memory userStake = userStakes[_msgSender()];
        require(userStake.amount > 0, "XEN: no stake exists");

        uint256 xenReward = _calculateStakeReward(
            userStake.amount,
            userStake.term,
            userStake.maturityTs,
            userStake.apy
        );
        activeStakes--;
        totalXenStaked -= userStake.amount;

        // mint staked XEN (+ reward)
        _mint(_msgSender(), userStake.amount + xenReward);
        emit Withdrawn(_msgSender(), userStake.amount, xenReward);
        delete userStakes[_msgSender()];
    }

    /**
     * @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services
     */
    function burn(address user, uint256 amount) public {
        require(amount > XEN_MIN_BURN, "Burn: Below min limit");
        require(
            IERC165(_msgSender()).supportsInterface(
                type(IBurnRedeemable).interfaceId
            ),
            "Burn: not a supported contract"
        );

        _spendAllowance(user, _msgSender(), amount);
        _burn(user, amount);
        userBurns[user] += amount;
        IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);
    }
}

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

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"xenAddress","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"DECIMALS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"STAKE_PERIOD","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"STAKE_TERM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TAX","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"addStake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"approveXen","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"apyDays","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"apyTerm","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_isAnticipate","type":"bool"},{"internalType":"uint256","name":"_apy","type":"uint256"},{"internalType":"uint256","name":"_term","type":"uint256"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"canUnstake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"claim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"currentUnstake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"getUserStakeReward","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"globalApy","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isAdmin","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_admin","type":"address"},{"internalType":"bool","name":"_isAdmin","type":"bool"}],"name":"setAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"stake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakeAllToXen","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"stakeTermApy","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stakeTs","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalStaked","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalTax","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalUnstake","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unstake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unstakeAllToXen","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unstakeAndStakeAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userStakeTerm","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userStaked","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userUnstakeAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userUnstakeTerm","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"xen","outputs":[{"internalType":"contract XENCrypto","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

608060405260006003556000600455600060055560006006556000600755600060085560006009553480156200003457600080fd5b50604051620022ac380380620022ac8339810160408190526200005791620000df565b600160005562000067336200008d565b600280546001600160a01b0319166001600160a01b039290921691909117905562000111565b600180546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600060208284031215620000f257600080fd5b81516001600160a01b03811681146200010a57600080fd5b9392505050565b61218b80620001216000396000f3fe608060405234801561001057600080fd5b50600436106101fb5760003560e01c8063715018a61161011a578063a694fc3a116100ad578063dd4b18231161007c578063dd4b18231461040d578063eb4f16b514610415578063f2fde38b14610428578063f51751fb1461043b578063fe85b42b1461045b57600080fd5b8063a694fc3a1461039a578063a97f9ecb146103ad578063acc3a939146103cd578063d3f41ad3146103ed57600080fd5b80638da5cb5b116100e95780638da5cb5b146103465780639055c5151461036b5780639a4ecc831461037e578063a15c970d1461038757600080fd5b8063715018a61461030d5780637fac564e146103155780638148b0fc14610335578063817b1cd21461033d57600080fd5b8063346e7d7d1161019257806351ac695f1161016157806351ac695f146102d357806368f58b03146102dc5780636ba9168f146102e4578063711ffae4146102ed57600080fd5b8063346e7d7d146102a75780634af4d063146102af5780634b0bddd2146102b85780634e71d92d146102cb57600080fd5b8063299c66da116101ce578063299c66da146102835780632def66201461028c5780632df4f6d3146102945780632e0f26251461029c57600080fd5b8063020e78c414610200578063084e2f4a1461022657806324d7806c1461024657806325f9d1ef14610279575b600080fd5b61021361020e366004611cfd565b610464565b6040519081526020015b60405180910390f35b610213610234366004611d54565b600c6020526000908152604090205481565b610269610254366004611d54565b600a6020526000908152604090205460ff1681565b604051901515815260200161021d565b610281610668565b005b61021360065481565b6102816106ea565b610281610848565b6102136305f5e10081565b6102816108ae565b61021360085481565b6102816102c6366004611d76565b610a39565b610281610a6c565b61021360045481565b610213600581565b61021360095481565b6102136102fb366004611dad565b600f6020526000908152604090205481565b610281610b6a565b610213610323366004611dad565b60106020526000908152604090205481565b610281610b7c565b61021360055481565b6001546001600160a01b03165b6040516001600160a01b03909116815260200161021d565b600254610353906001600160a01b031681565b61021360075481565b610213610395366004611d54565b610d3a565b6102816103a8366004611dad565b61152a565b6102136103bb366004611dad565b600d6020526000908152604090205481565b6102136103db366004611d54565b600b6020526000908152604090205481565b6102136103fb366004611d54565b60116020526000908152604090205481565b610213600181565b610281610423366004611dad565b6116bc565b610281610436366004611d54565b6118db565b610213610449366004611d54565b600e6020526000908152604090205481565b61021360035481565b6000841561051e576002546040805163011bc49960e11b815290516000926001600160a01b03169163023789329160048083019260209291908290030181865afa1580156104b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104da9190611dc6565b6104e48587611df5565b6104f190620f4240611df5565b6104fb9190611e28565b90506305f5e10061050c8285611df5565b6105169190611e28565b915050610660565b600254604080516316f9c8fd60e01b815290516000926001600160a01b0316916316f9c8fd9160048083019260809291908290030181865afa158015610568573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061058c9190611e3c565b9050806020015142111561065a576002546040805163011bc49960e11b815290516000926001600160a01b03169163023789329160048083019260209291908290030181865afa1580156105e4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106089190611dc6565b825160608401516106199190611df5565b61062690620f4240611df5565b6106309190611e28565b90506305f5e1008183604001516106479190611df5565b6106519190611e28565b92505050610660565b60009150505b949350505050565b610670611951565b60025460405163095ea7b360e01b81526001600160a01b039091166004820181905260001960248301529063095ea7b3906044016020604051808303816000875af11580156106c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106e79190611eb0565b50565b6106f26119ab565b336000908152600e6020526040902054156107545760405162461bcd60e51b815260206004820152601f60248201527f596f75206861766520756e7374616b65642c20706c6561736520636c61696d0060448201526064015b60405180910390fd5b336000908152600b60205260409020546107a95760405162461bcd60e51b8152602060048201526016602482015275165bdd481a185d995b89dd081cdd185ad959081e595d60521b604482015260640161074b565b60006107b433610d3a565b336000908152600b6020526040812054919250906107d3908390611ecd565b336000908152600e602052604081208290556008805492935083929091906107fc908490611ecd565b9250508190555080600960008282546108159190611ecd565b9091555050336000908152600b60209081526040808320839055600454601190925282205560019055506108469050565b565b6108506119ab565b336000908152600a602052604090205460ff168061087857506001546001600160a01b031633145b6108945760405162461bcd60e51b815260040161074b90611ee0565b61089c6108ae565b6108a4610b7c565b6108466001600055565b336000908152600a602052604090205460ff16806108d657506001546001600160a01b031633145b6108f25760405162461bcd60e51b815260040161074b90611ee0565b6000610902600080600080610464565b905060006064610913600584611df5565b61091d9190611e28565b6009549091508261095e5760405162461bcd60e51b815260206004820152600b60248201526a052657761726420697320360ac1b604482015260640161074b565b6109688284611f17565b600560008282546109799190611ecd565b909155505060025460408051633ccfd60b60e01b815290516001600160a01b0390921691633ccfd60b9160048082019260009290919082900301818387803b1580156109c457600080fd5b505af11580156109d8573d6000803e3d6000fd5b505050506000811115610a0c5780600554116109f5576000610a03565b80600554610a039190611f17565b60055560006009555b610a34610a216001546001600160a01b031690565b6002546001600160a01b03169084611a04565b505050565b610a41611951565b6001600160a01b03919091166000908152600a60205260409020805460ff1916911515919091179055565b610a746119ab565b336000908152600e6020526040902054610ad05760405162461bcd60e51b815260206004820152601860248201527f596f7520686176656e277420756e7374616b6564207965740000000000000000604482015260640161074b565b6004543360009081526011602052604090205410610b005760405162461bcd60e51b815260040161074b90611f2a565b336000908152600e60205260408120546008805491929091610b23908490611f17565b9091555050336000818152600e6020526040902054600254610b50926001600160a01b0390911691611a04565b336000908152600e60205260408120556108466001600055565b610b72611951565b6108466000611a67565b336000908152600a602052604090205460ff1680610ba457506001546001600160a01b031633145b610bc05760405162461bcd60e51b815260040161074b90611ee0565b60055480610be05760405162461bcd60e51b815260040161074b90611f77565b60025460408051634b16524b60e11b815290516000926001600160a01b03169163962ca4969160048083019260209291908290030181865afa158015610c2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c4e9190611dc6565b90508060065414610c7c576006819055600454610c6c906001611ecd565b6000828152601060205260409020555b6000818152600d60205260408120805460019290610c9b908490611ecd565b92505081905550600160046000828254610cb59190611ecd565b9091555050600480546000908152600f6020526040908190208390554260075560025490516307b0472f60e41b8152918201849052600160248301526001600160a01b031690637b0472f090604401600060405180830381600087803b158015610d1e57600080fd5b505af1158015610d32573d6000803e3d6000fd5b505050505050565b60006001600454111580610d6757506004546001600160a01b0383166000908152600c6020526040902054145b15610d7457506000919050565b6001600160a01b0382166000908152600b6020526040902054610dce5760405162461bcd60e51b8152602060048201526012602482015271165bdd481a185d995b89dd081cdd185ad95960721b604482015260640161074b565b6001600160a01b0382166000908152600b6020908152604080832054600654600c909352908320549092908190600890600f908390610e0e906001611ecd565b8152602001908152602001600020548403611114576001600160a01b0387166000908152600c6020526040902054600454610e499190611f17565b925060008311610e6b5760405162461bcd60e51b815260040161074b90611f2a565b6000610e778285611e28565b90506000610e858386611fae565b90508115611056576000805b83811015610f8057610ea3828a611ecd565b6305f5e100610eb3600188611f17565b610ec1906305f5e1006120a6565b876064610ecf600582611f17565b6237b1d06305f5e1008f6064610ee59190611df5565b610eef9190611df5565b610ef99190611e28565b610f039190611df5565b610f0d9190611e28565b610f1c6305f5e1006001611df5565b610f269190611ecd565b610f3091906120a6565b610f3a9190611e28565b610f44858d611ecd565b610f4e9190611df5565b610f589190611e28565b610f629190611f17565b610f6c9083611ecd565b915080610f78816120b2565b915050610e91565b50811561104c57876305f5e100610f98600185611f17565b610fa6906305f5e1006120a6565b846064610fb4600582611f17565b6237b1d06305f5e100610fc88f6064611df5565b610fd29190611df5565b610fdc9190611e28565b610fe69190611df5565b610ff09190611e28565b610fff6305f5e1006001611df5565b6110099190611ecd565b61101391906120a6565b61101d9190611e28565b611027848c611ecd565b6110319190611df5565b61103b9190611e28565b6110459190611f17565b9450611050565b8094505b5061110d565b866305f5e100611067600188611f17565b611075906305f5e1006120a6565b876064611083600582611f17565b6237b1d06305f5e1006110978e6064611df5565b6110a19190611df5565b6110ab9190611e28565b6110b59190611df5565b6110bf9190611e28565b6110ce6305f5e1006001611df5565b6110d89190611ecd565b6110e291906120a6565b6110ec9190611e28565b6110f6908a611df5565b6111009190611e28565b61110a9190611f17565b93505b5050611520565b6001600160a01b0387166000908152600c602052604090205460045461113a9190611f17565b92506000831161115c5760405162461bcd60e51b815260040161074b90611f2a565b6001600160a01b0387166000908152600c6020526040812054600f908290611185906001611ecd565b81526020019081526020016000205490505b84811061151e576001600160a01b0388166000908152600c6020526040812054600f91906111c6906001611ecd565b8152602001908152602001600020548103611214576001600160a01b0388166000908152600c6020908152604080832054848452600d9092529091205461120d9190611f17565b9350611226565b6000818152600d602052604090205493505b60006112328386611e28565b905060006112408487611fae565b90508115611422576000805b838110156113395761125e828b611ecd565b6305f5e10061126e600189611f17565b61127c906305f5e1006120a6565b88606461128a600582611f17565b6237b1d06305f5e10061129e8d6064611df5565b6112a89190611df5565b6112b29190611e28565b6112bc9190611df5565b6112c69190611e28565b6112d56305f5e1006001611df5565b6112df9190611ecd565b6112e991906120a6565b6112f39190611e28565b6112fd858e611ecd565b6113079190611df5565b6113119190611e28565b61131b9190611f17565b6113259083611ecd565b915080611331816120b2565b91505061124c565b50811561140f57886305f5e100611351600185611f17565b61135f906305f5e1006120a6565b84606461136d600582611f17565b6237b1d06305f5e1006113818c6064611df5565b61138b9190611df5565b6113959190611e28565b61139f9190611df5565b6113a99190611e28565b6113b86305f5e1006001611df5565b6113c29190611ecd565b6113cc91906120a6565b6113d69190611e28565b6113e0848d611ecd565b6113ea9190611df5565b6113f49190611e28565b6113fe9190611f17565b6114089087611ecd565b955061141c565b6114198187611ecd565b95505b506114e3565b876305f5e100611433600189611f17565b611441906305f5e1006120a6565b88606461144f600582611f17565b6237b1d06305f5e1006114638b6064611df5565b61146d9190611df5565b6114779190611e28565b6114819190611df5565b61148b9190611e28565b61149a6305f5e1006001611df5565b6114a49190611ecd565b6114ae91906120a6565b6114b89190611e28565b6114c2908b611df5565b6114cc9190611e28565b6114d69190611f17565b6114e09086611ecd565b94505b6001600160a01b038a166000908152600b6020526040902054611507908690611ecd565b975050508080611516906120cb565b915050611197565b505b5095945050505050565b6115326119ab565b6002546040516370a0823160e01b815233600482015282916001600160a01b0316906370a0823190602401602060405180830381865afa15801561157a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061159e9190611dc6565b10156115e35760405162461bcd60e51b8152602060048201526014602482015273496e73756666696369656e742062616c616e636560601b604482015260640161074b565b600081116116035760405162461bcd60e51b815260040161074b90611f77565b336000908152600b6020526040902054156116605760405162461bcd60e51b815260206004820152601f60248201527f596f752068617665207374616b65642c20706c6561736520756e7374616b6500604482015260640161074b565b80600560008282546116729190611ecd565b9091555050336000818152600b60209081526040808320859055600454600c909252909120556002546116b2916001600160a01b03909116903084611ab9565b6106e76001600055565b6116c46119ab565b6002546040516370a0823160e01b815233600482015282916001600160a01b0316906370a0823190602401602060405180830381865afa15801561170c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117309190611dc6565b10156117755760405162461bcd60e51b8152602060048201526014602482015273496e73756666696369656e742062616c616e636560601b604482015260640161074b565b600081116117955760405162461bcd60e51b815260040161074b90611f77565b336000908152600b60205260409020546117ea5760405162461bcd60e51b8152602060048201526016602482015275165bdd481a185d995b89dd081cdd185ad959081e595d60521b604482015260640161074b565b60006117f533610d3a565b90506000811161185a5760405162461bcd60e51b815260206004820152602a60248201527f52657761726420697320302c20706c65617365207761697420666f7220746865604482015269206e657874207465726d60b01b606482015260840161074b565b816005600082825461186c9190611ecd565b9091555061187c90508282611ecd565b336000908152600b60205260408120805490919061189b908490611ecd565b9091555050600454336000818152600c60205260409020919091556002546118d0916001600160a01b03909116903085611ab9565b506106e76001600055565b6118e3611951565b6001600160a01b0381166119485760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161074b565b6106e781611a67565b6001546001600160a01b031633146108465760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161074b565b6002600054036119fd5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015260640161074b565b6002600055565b6040516001600160a01b038316602482015260448101829052610a3490849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152611af7565b600180546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6040516001600160a01b0380851660248301528316604482015260648101829052611af19085906323b872dd60e01b90608401611a30565b50505050565b6000611b4c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611bcc9092919063ffffffff16565b9050805160001480611b6d575080806020019051810190611b6d9190611eb0565b610a345760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161074b565b6060610660848460008585600080866001600160a01b03168587604051611bf39190612106565b60006040518083038185875af1925050503d8060008114611c30576040519150601f19603f3d011682016040523d82523d6000602084013e611c35565b606091505b5091509150611c4687838387611c51565b979650505050505050565b60608315611cc0578251600003611cb9576001600160a01b0385163b611cb95760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161074b565b5081610660565b6106608383815115611cd55781518083602001fd5b8060405162461bcd60e51b815260040161074b9190612122565b80151581146106e757600080fd5b60008060008060808587031215611d1357600080fd5b8435611d1e81611cef565b966020860135965060408601359560600135945092505050565b80356001600160a01b0381168114611d4f57600080fd5b919050565b600060208284031215611d6657600080fd5b611d6f82611d38565b9392505050565b60008060408385031215611d8957600080fd5b611d9283611d38565b91506020830135611da281611cef565b809150509250929050565b600060208284031215611dbf57600080fd5b5035919050565b600060208284031215611dd857600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b8082028115828204841417611e0c57611e0c611ddf565b92915050565b634e487b7160e01b600052601260045260246000fd5b600082611e3757611e37611e12565b500490565b600060808284031215611e4e57600080fd5b6040516080810181811067ffffffffffffffff82111715611e7f57634e487b7160e01b600052604160045260246000fd5b8060405250825181526020830151602082015260408301516040820152606083015160608201528091505092915050565b600060208284031215611ec257600080fd5b8151611d6f81611cef565b80820180821115611e0c57611e0c611ddf565b60208082526017908201527f43616c6c6572206973206e6f74207468652061646d696e000000000000000000604082015260600190565b81810381811115611e0c57611e0c611ddf565b6020808252602d908201527f546865207374616b696e67206861736e2774207265616368656420697473206560408201526c1e1c1a5c985d1a5bdb881e595d609a1b606082015260800190565b6020808252601c908201527f58454e426f783a20696e73756666696369656e742062616c616e636500000000604082015260600190565b600082611fbd57611fbd611e12565b500690565b600181815b80851115611ffd578160001904821115611fe357611fe3611ddf565b80851615611ff057918102915b93841c9390800290611fc7565b509250929050565b60008261201457506001611e0c565b8161202157506000611e0c565b816001811461203757600281146120415761205d565b6001915050611e0c565b60ff84111561205257612052611ddf565b50506001821b611e0c565b5060208310610133831016604e8410600b8410161715612080575081810a611e0c565b61208a8383611fc2565b806000190482111561209e5761209e611ddf565b029392505050565b6000611d6f8383612005565b6000600182016120c4576120c4611ddf565b5060010190565b6000816120da576120da611ddf565b506000190190565b60005b838110156120fd5781810151838201526020016120e5565b50506000910152565b600082516121188184602087016120e2565b9190910192915050565b60208152600082518060208401526121418160408501602087016120e2565b601f01601f1916919091016040019291505056fea264697066735822122041ab2cb492618e108ffb85fbded1f1a770f4c78c1cf3e8d551c868300563181964736f6c63430008110033000000000000000000000000b564a5767a00ee9075cac561c427643286f8f4e1

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101fb5760003560e01c8063715018a61161011a578063a694fc3a116100ad578063dd4b18231161007c578063dd4b18231461040d578063eb4f16b514610415578063f2fde38b14610428578063f51751fb1461043b578063fe85b42b1461045b57600080fd5b8063a694fc3a1461039a578063a97f9ecb146103ad578063acc3a939146103cd578063d3f41ad3146103ed57600080fd5b80638da5cb5b116100e95780638da5cb5b146103465780639055c5151461036b5780639a4ecc831461037e578063a15c970d1461038757600080fd5b8063715018a61461030d5780637fac564e146103155780638148b0fc14610335578063817b1cd21461033d57600080fd5b8063346e7d7d1161019257806351ac695f1161016157806351ac695f146102d357806368f58b03146102dc5780636ba9168f146102e4578063711ffae4146102ed57600080fd5b8063346e7d7d146102a75780634af4d063146102af5780634b0bddd2146102b85780634e71d92d146102cb57600080fd5b8063299c66da116101ce578063299c66da146102835780632def66201461028c5780632df4f6d3146102945780632e0f26251461029c57600080fd5b8063020e78c414610200578063084e2f4a1461022657806324d7806c1461024657806325f9d1ef14610279575b600080fd5b61021361020e366004611cfd565b610464565b6040519081526020015b60405180910390f35b610213610234366004611d54565b600c6020526000908152604090205481565b610269610254366004611d54565b600a6020526000908152604090205460ff1681565b604051901515815260200161021d565b610281610668565b005b61021360065481565b6102816106ea565b610281610848565b6102136305f5e10081565b6102816108ae565b61021360085481565b6102816102c6366004611d76565b610a39565b610281610a6c565b61021360045481565b610213600581565b61021360095481565b6102136102fb366004611dad565b600f6020526000908152604090205481565b610281610b6a565b610213610323366004611dad565b60106020526000908152604090205481565b610281610b7c565b61021360055481565b6001546001600160a01b03165b6040516001600160a01b03909116815260200161021d565b600254610353906001600160a01b031681565b61021360075481565b610213610395366004611d54565b610d3a565b6102816103a8366004611dad565b61152a565b6102136103bb366004611dad565b600d6020526000908152604090205481565b6102136103db366004611d54565b600b6020526000908152604090205481565b6102136103fb366004611d54565b60116020526000908152604090205481565b610213600181565b610281610423366004611dad565b6116bc565b610281610436366004611d54565b6118db565b610213610449366004611d54565b600e6020526000908152604090205481565b61021360035481565b6000841561051e576002546040805163011bc49960e11b815290516000926001600160a01b03169163023789329160048083019260209291908290030181865afa1580156104b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104da9190611dc6565b6104e48587611df5565b6104f190620f4240611df5565b6104fb9190611e28565b90506305f5e10061050c8285611df5565b6105169190611e28565b915050610660565b600254604080516316f9c8fd60e01b815290516000926001600160a01b0316916316f9c8fd9160048083019260809291908290030181865afa158015610568573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061058c9190611e3c565b9050806020015142111561065a576002546040805163011bc49960e11b815290516000926001600160a01b03169163023789329160048083019260209291908290030181865afa1580156105e4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106089190611dc6565b825160608401516106199190611df5565b61062690620f4240611df5565b6106309190611e28565b90506305f5e1008183604001516106479190611df5565b6106519190611e28565b92505050610660565b60009150505b949350505050565b610670611951565b60025460405163095ea7b360e01b81526001600160a01b039091166004820181905260001960248301529063095ea7b3906044016020604051808303816000875af11580156106c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106e79190611eb0565b50565b6106f26119ab565b336000908152600e6020526040902054156107545760405162461bcd60e51b815260206004820152601f60248201527f596f75206861766520756e7374616b65642c20706c6561736520636c61696d0060448201526064015b60405180910390fd5b336000908152600b60205260409020546107a95760405162461bcd60e51b8152602060048201526016602482015275165bdd481a185d995b89dd081cdd185ad959081e595d60521b604482015260640161074b565b60006107b433610d3a565b336000908152600b6020526040812054919250906107d3908390611ecd565b336000908152600e602052604081208290556008805492935083929091906107fc908490611ecd565b9250508190555080600960008282546108159190611ecd565b9091555050336000908152600b60209081526040808320839055600454601190925282205560019055506108469050565b565b6108506119ab565b336000908152600a602052604090205460ff168061087857506001546001600160a01b031633145b6108945760405162461bcd60e51b815260040161074b90611ee0565b61089c6108ae565b6108a4610b7c565b6108466001600055565b336000908152600a602052604090205460ff16806108d657506001546001600160a01b031633145b6108f25760405162461bcd60e51b815260040161074b90611ee0565b6000610902600080600080610464565b905060006064610913600584611df5565b61091d9190611e28565b6009549091508261095e5760405162461bcd60e51b815260206004820152600b60248201526a052657761726420697320360ac1b604482015260640161074b565b6109688284611f17565b600560008282546109799190611ecd565b909155505060025460408051633ccfd60b60e01b815290516001600160a01b0390921691633ccfd60b9160048082019260009290919082900301818387803b1580156109c457600080fd5b505af11580156109d8573d6000803e3d6000fd5b505050506000811115610a0c5780600554116109f5576000610a03565b80600554610a039190611f17565b60055560006009555b610a34610a216001546001600160a01b031690565b6002546001600160a01b03169084611a04565b505050565b610a41611951565b6001600160a01b03919091166000908152600a60205260409020805460ff1916911515919091179055565b610a746119ab565b336000908152600e6020526040902054610ad05760405162461bcd60e51b815260206004820152601860248201527f596f7520686176656e277420756e7374616b6564207965740000000000000000604482015260640161074b565b6004543360009081526011602052604090205410610b005760405162461bcd60e51b815260040161074b90611f2a565b336000908152600e60205260408120546008805491929091610b23908490611f17565b9091555050336000818152600e6020526040902054600254610b50926001600160a01b0390911691611a04565b336000908152600e60205260408120556108466001600055565b610b72611951565b6108466000611a67565b336000908152600a602052604090205460ff1680610ba457506001546001600160a01b031633145b610bc05760405162461bcd60e51b815260040161074b90611ee0565b60055480610be05760405162461bcd60e51b815260040161074b90611f77565b60025460408051634b16524b60e11b815290516000926001600160a01b03169163962ca4969160048083019260209291908290030181865afa158015610c2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c4e9190611dc6565b90508060065414610c7c576006819055600454610c6c906001611ecd565b6000828152601060205260409020555b6000818152600d60205260408120805460019290610c9b908490611ecd565b92505081905550600160046000828254610cb59190611ecd565b9091555050600480546000908152600f6020526040908190208390554260075560025490516307b0472f60e41b8152918201849052600160248301526001600160a01b031690637b0472f090604401600060405180830381600087803b158015610d1e57600080fd5b505af1158015610d32573d6000803e3d6000fd5b505050505050565b60006001600454111580610d6757506004546001600160a01b0383166000908152600c6020526040902054145b15610d7457506000919050565b6001600160a01b0382166000908152600b6020526040902054610dce5760405162461bcd60e51b8152602060048201526012602482015271165bdd481a185d995b89dd081cdd185ad95960721b604482015260640161074b565b6001600160a01b0382166000908152600b6020908152604080832054600654600c909352908320549092908190600890600f908390610e0e906001611ecd565b8152602001908152602001600020548403611114576001600160a01b0387166000908152600c6020526040902054600454610e499190611f17565b925060008311610e6b5760405162461bcd60e51b815260040161074b90611f2a565b6000610e778285611e28565b90506000610e858386611fae565b90508115611056576000805b83811015610f8057610ea3828a611ecd565b6305f5e100610eb3600188611f17565b610ec1906305f5e1006120a6565b876064610ecf600582611f17565b6237b1d06305f5e1008f6064610ee59190611df5565b610eef9190611df5565b610ef99190611e28565b610f039190611df5565b610f0d9190611e28565b610f1c6305f5e1006001611df5565b610f269190611ecd565b610f3091906120a6565b610f3a9190611e28565b610f44858d611ecd565b610f4e9190611df5565b610f589190611e28565b610f629190611f17565b610f6c9083611ecd565b915080610f78816120b2565b915050610e91565b50811561104c57876305f5e100610f98600185611f17565b610fa6906305f5e1006120a6565b846064610fb4600582611f17565b6237b1d06305f5e100610fc88f6064611df5565b610fd29190611df5565b610fdc9190611e28565b610fe69190611df5565b610ff09190611e28565b610fff6305f5e1006001611df5565b6110099190611ecd565b61101391906120a6565b61101d9190611e28565b611027848c611ecd565b6110319190611df5565b61103b9190611e28565b6110459190611f17565b9450611050565b8094505b5061110d565b866305f5e100611067600188611f17565b611075906305f5e1006120a6565b876064611083600582611f17565b6237b1d06305f5e1006110978e6064611df5565b6110a19190611df5565b6110ab9190611e28565b6110b59190611df5565b6110bf9190611e28565b6110ce6305f5e1006001611df5565b6110d89190611ecd565b6110e291906120a6565b6110ec9190611e28565b6110f6908a611df5565b6111009190611e28565b61110a9190611f17565b93505b5050611520565b6001600160a01b0387166000908152600c602052604090205460045461113a9190611f17565b92506000831161115c5760405162461bcd60e51b815260040161074b90611f2a565b6001600160a01b0387166000908152600c6020526040812054600f908290611185906001611ecd565b81526020019081526020016000205490505b84811061151e576001600160a01b0388166000908152600c6020526040812054600f91906111c6906001611ecd565b8152602001908152602001600020548103611214576001600160a01b0388166000908152600c6020908152604080832054848452600d9092529091205461120d9190611f17565b9350611226565b6000818152600d602052604090205493505b60006112328386611e28565b905060006112408487611fae565b90508115611422576000805b838110156113395761125e828b611ecd565b6305f5e10061126e600189611f17565b61127c906305f5e1006120a6565b88606461128a600582611f17565b6237b1d06305f5e10061129e8d6064611df5565b6112a89190611df5565b6112b29190611e28565b6112bc9190611df5565b6112c69190611e28565b6112d56305f5e1006001611df5565b6112df9190611ecd565b6112e991906120a6565b6112f39190611e28565b6112fd858e611ecd565b6113079190611df5565b6113119190611e28565b61131b9190611f17565b6113259083611ecd565b915080611331816120b2565b91505061124c565b50811561140f57886305f5e100611351600185611f17565b61135f906305f5e1006120a6565b84606461136d600582611f17565b6237b1d06305f5e1006113818c6064611df5565b61138b9190611df5565b6113959190611e28565b61139f9190611df5565b6113a99190611e28565b6113b86305f5e1006001611df5565b6113c29190611ecd565b6113cc91906120a6565b6113d69190611e28565b6113e0848d611ecd565b6113ea9190611df5565b6113f49190611e28565b6113fe9190611f17565b6114089087611ecd565b955061141c565b6114198187611ecd565b95505b506114e3565b876305f5e100611433600189611f17565b611441906305f5e1006120a6565b88606461144f600582611f17565b6237b1d06305f5e1006114638b6064611df5565b61146d9190611df5565b6114779190611e28565b6114819190611df5565b61148b9190611e28565b61149a6305f5e1006001611df5565b6114a49190611ecd565b6114ae91906120a6565b6114b89190611e28565b6114c2908b611df5565b6114cc9190611e28565b6114d69190611f17565b6114e09086611ecd565b94505b6001600160a01b038a166000908152600b6020526040902054611507908690611ecd565b975050508080611516906120cb565b915050611197565b505b5095945050505050565b6115326119ab565b6002546040516370a0823160e01b815233600482015282916001600160a01b0316906370a0823190602401602060405180830381865afa15801561157a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061159e9190611dc6565b10156115e35760405162461bcd60e51b8152602060048201526014602482015273496e73756666696369656e742062616c616e636560601b604482015260640161074b565b600081116116035760405162461bcd60e51b815260040161074b90611f77565b336000908152600b6020526040902054156116605760405162461bcd60e51b815260206004820152601f60248201527f596f752068617665207374616b65642c20706c6561736520756e7374616b6500604482015260640161074b565b80600560008282546116729190611ecd565b9091555050336000818152600b60209081526040808320859055600454600c909252909120556002546116b2916001600160a01b03909116903084611ab9565b6106e76001600055565b6116c46119ab565b6002546040516370a0823160e01b815233600482015282916001600160a01b0316906370a0823190602401602060405180830381865afa15801561170c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117309190611dc6565b10156117755760405162461bcd60e51b8152602060048201526014602482015273496e73756666696369656e742062616c616e636560601b604482015260640161074b565b600081116117955760405162461bcd60e51b815260040161074b90611f77565b336000908152600b60205260409020546117ea5760405162461bcd60e51b8152602060048201526016602482015275165bdd481a185d995b89dd081cdd185ad959081e595d60521b604482015260640161074b565b60006117f533610d3a565b90506000811161185a5760405162461bcd60e51b815260206004820152602a60248201527f52657761726420697320302c20706c65617365207761697420666f7220746865604482015269206e657874207465726d60b01b606482015260840161074b565b816005600082825461186c9190611ecd565b9091555061187c90508282611ecd565b336000908152600b60205260408120805490919061189b908490611ecd565b9091555050600454336000818152600c60205260409020919091556002546118d0916001600160a01b03909116903085611ab9565b506106e76001600055565b6118e3611951565b6001600160a01b0381166119485760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161074b565b6106e781611a67565b6001546001600160a01b031633146108465760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161074b565b6002600054036119fd5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015260640161074b565b6002600055565b6040516001600160a01b038316602482015260448101829052610a3490849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152611af7565b600180546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6040516001600160a01b0380851660248301528316604482015260648101829052611af19085906323b872dd60e01b90608401611a30565b50505050565b6000611b4c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611bcc9092919063ffffffff16565b9050805160001480611b6d575080806020019051810190611b6d9190611eb0565b610a345760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161074b565b6060610660848460008585600080866001600160a01b03168587604051611bf39190612106565b60006040518083038185875af1925050503d8060008114611c30576040519150601f19603f3d011682016040523d82523d6000602084013e611c35565b606091505b5091509150611c4687838387611c51565b979650505050505050565b60608315611cc0578251600003611cb9576001600160a01b0385163b611cb95760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161074b565b5081610660565b6106608383815115611cd55781518083602001fd5b8060405162461bcd60e51b815260040161074b9190612122565b80151581146106e757600080fd5b60008060008060808587031215611d1357600080fd5b8435611d1e81611cef565b966020860135965060408601359560600135945092505050565b80356001600160a01b0381168114611d4f57600080fd5b919050565b600060208284031215611d6657600080fd5b611d6f82611d38565b9392505050565b60008060408385031215611d8957600080fd5b611d9283611d38565b91506020830135611da281611cef565b809150509250929050565b600060208284031215611dbf57600080fd5b5035919050565b600060208284031215611dd857600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b8082028115828204841417611e0c57611e0c611ddf565b92915050565b634e487b7160e01b600052601260045260246000fd5b600082611e3757611e37611e12565b500490565b600060808284031215611e4e57600080fd5b6040516080810181811067ffffffffffffffff82111715611e7f57634e487b7160e01b600052604160045260246000fd5b8060405250825181526020830151602082015260408301516040820152606083015160608201528091505092915050565b600060208284031215611ec257600080fd5b8151611d6f81611cef565b80820180821115611e0c57611e0c611ddf565b60208082526017908201527f43616c6c6572206973206e6f74207468652061646d696e000000000000000000604082015260600190565b81810381811115611e0c57611e0c611ddf565b6020808252602d908201527f546865207374616b696e67206861736e2774207265616368656420697473206560408201526c1e1c1a5c985d1a5bdb881e595d609a1b606082015260800190565b6020808252601c908201527f58454e426f783a20696e73756666696369656e742062616c616e636500000000604082015260600190565b600082611fbd57611fbd611e12565b500690565b600181815b80851115611ffd578160001904821115611fe357611fe3611ddf565b80851615611ff057918102915b93841c9390800290611fc7565b509250929050565b60008261201457506001611e0c565b8161202157506000611e0c565b816001811461203757600281146120415761205d565b6001915050611e0c565b60ff84111561205257612052611ddf565b50506001821b611e0c565b5060208310610133831016604e8410600b8410161715612080575081810a611e0c565b61208a8383611fc2565b806000190482111561209e5761209e611ddf565b029392505050565b6000611d6f8383612005565b6000600182016120c4576120c4611ddf565b5060010190565b6000816120da576120da611ddf565b506000190190565b60005b838110156120fd5781810151838201526020016120e5565b50506000910152565b600082516121188184602087016120e2565b9190910192915050565b60208152600082518060208401526121418160408501602087016120e2565b601f01601f1916919091016040019291505056fea264697066735822122041ab2cb492618e108ffb85fbded1f1a770f4c78c1cf3e8d551c868300563181964736f6c63430008110033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000b564a5767a00ee9075cac561c427643286f8f4e1

-----Decoded View---------------
Arg [0] : xenAddress (address): 0xb564A5767A00Ee9075cAC561c427643286F8F4E1

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000b564a5767a00ee9075cac561c427643286f8f4e1


Block Transaction Gas Used Reward
view all blocks collator

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.