APE Price: $1.21 (-0.83%)

Contract

0xD9D99813ED4aBfFCe83277884162b47aF878cb8F

Overview

APE Balance

Apechain LogoApechain LogoApechain Logo0 APE

APE Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Parent Transaction Hash Block From To
View All Internal Transactions

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
CyanPaymentPlanV2

Compiler Version
v0.8.19+commit.7dd6d404

Optimization Enabled:
Yes with 500 runs

Other Settings:
default evmVersion
File 1 of 36 : CyanPaymentPlanV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

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

import "../../interfaces/core/IFactory.sol";
import "../../interfaces/main/ICyanVaultV2.sol";
import "../../interfaces/main/ICyanPaymentPlanV2.sol";
import "../../interfaces/conduit/ICyanConduit.sol";

import "../AddressProvider.sol";
import "./PaymentPlanV2Logic.sol";
import "../CyanWalletLogic.sol";

/// @title Cyan Payment Plan - Main logic of BNPL and Pawn plan
/// @author Bulgantamir Gankhuyag - <[email protected]>
/// @author Naranbayar Uuganbayar - <[email protected]>
contract CyanPaymentPlanV2 is ICyanPaymentPlanV2, AccessControlUpgradeable, ReentrancyGuardUpgradeable {
    AddressProvider private constant addressProvider = AddressProvider(0xCF9A19D879769aDaE5e4f31503AAECDa82568E55);

    using SafeERC20Upgradeable for IERC20Upgradeable;

    event CreatedBNPL(uint256 indexed planId);
    event CreatedPawn(uint256 indexed planId, PawnCreateType createType);
    event UpdatedBNPL(uint256 indexed planId, PaymentPlanStatus indexed planStatus);
    event LiquidatedPaymentPlan(uint256 indexed planId, uint256 indexed estimatedPrice, uint256 indexed unpaidAmount);
    event Paid(uint256 indexed planId);
    event Completed(uint256 indexed planId);
    event CompletedByRevival(uint256 indexed planId, uint256 penaltyAmount);
    event CompletedEarly(uint256 indexed planId, uint8 indexed paidNumOfPayment);
    event EarlyUnwind(uint256 indexed planId);
    event Revived(uint256 indexed planId, uint256 penaltyAmount);
    event UpdatedCyanSigner(address indexed signer);
    event ClaimedServiceFee(address indexed currency, uint256 indexed amount);
    event UpdatedWalletFactory(address indexed factory);
    event SetAutoRepayStatus(uint256 indexed planId, uint8 indexed autoRepayStatus);

    mapping(uint256 => Item) public items;
    mapping(uint256 => PaymentPlan) public paymentPlan;
    mapping(address => uint256) public claimableServiceFee;

    bytes32 private constant CYAN_ROLE = keccak256("CYAN_ROLE");
    bytes32 private constant CYAN_AUTO_OPERATOR_ROLE = keccak256("CYAN_AUTO_OPERATOR_ROLE");
    bytes32 private constant CYAN_CONDUIT = "CYAN_CONDUIT";
    address private cyanSigner;
    address private walletFactory;
    uint256 private __unused; // unused variable to prevent storage slot collision

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize(
        address _cyanSigner,
        address _cyanSuperAdmin,
        address _walletFactory
    ) external initializer {
        if (_cyanSigner == address(0) || _cyanSuperAdmin == address(0) || _walletFactory == address(0)) {
            revert InvalidAddress();
        }

        cyanSigner = _cyanSigner;
        walletFactory = _walletFactory;
        _setupRole(DEFAULT_ADMIN_ROLE, _cyanSuperAdmin);

        __AccessControl_init();
        __ReentrancyGuard_init();

        emit UpdatedCyanSigner(_cyanSigner);
        emit UpdatedWalletFactory(_walletFactory);
    }

    /**
     * @notice Creating a BNPL plan
     * @param item Item detail to BNPL
     * @param plan BNPL plan detail
     * @param planId Plan ID
     * @param signedBlockNum Signed block number
     * @param signature Signature from Cyan
     */
    function createBNPL(
        Item calldata item,
        Plan calldata plan,
        uint256 planId,
        uint256 signedBlockNum,
        bytes memory signature
    ) external payable nonReentrant {
        PaymentPlanV2Logic.requireCorrectPlanParams(true, item, plan, signedBlockNum);
        PaymentPlanV2Logic.verifySignature(item, plan, planId, signedBlockNum, block.chainid, cyanSigner, signature);

        if (paymentPlan[planId].plan.totalNumberOfPayments != 0) revert PaymentPlanAlreadyExists();

        (PaymentAmountInfo memory singleAmounts, , uint256 downPaymentAmount, ) = PaymentPlanV2Logic
            .calculatePaymentInfo(plan);

        address currencyAddress = PaymentPlanV2Logic.getCurrencyAddressByVaultAddress(item.cyanVaultAddress);
        receiveCurrency(currencyAddress, singleAmounts.serviceAmount + downPaymentAmount, msg.sender);

        address cyanWalletAddress = IFactory(walletFactory).getOrDeployWallet(msg.sender);
        paymentPlan[planId] = PaymentPlan(plan, block.timestamp, cyanWalletAddress, PaymentPlanStatus.BNPL_CREATED);
        items[planId] = item;
        emit CreatedBNPL(planId);
    }

    /**
     * @notice Lending loaned currency from Vault for BNPL payment plan
     * @param planIds Payment plan IDs
     */
    function fundBNPL(uint256[] calldata planIds) external nonReentrant onlyRole(CYAN_ROLE) {
        for (uint256 i; i < planIds.length; ++i) {
            uint256 planId = planIds[i];
            PaymentPlan storage _paymentPlan = paymentPlan[planId];
            ICyanVaultV2(payable(items[planId].cyanVaultAddress)).lend(msg.sender, _paymentPlan.plan.amount);

            if (_paymentPlan.plan.counterPaidPayments != 1) revert InvalidPaidCount();
            if (_paymentPlan.status != PaymentPlanStatus.BNPL_CREATED) revert InvalidStage();

            _paymentPlan.status = PaymentPlanStatus.BNPL_FUNDED;
            emit UpdatedBNPL(planId, PaymentPlanStatus.BNPL_FUNDED);
        }
    }

    /**
     * @notice Activate BNPL payment plan
     * @param planIds Payment plan IDs
     */
    function activateBNPL(uint256[] calldata planIds) external nonReentrant onlyRole(CYAN_ROLE) {
        for (uint256 i; i < planIds.length; ++i) {
            uint256 planId = planIds[i];
            PaymentPlan storage _paymentPlan = paymentPlan[planId];
            Item memory item = items[planId];

            uint256 serviceAmount = PaymentPlanV2Logic.activate(_paymentPlan, item);
            address currencyAddress = PaymentPlanV2Logic.getCurrencyAddressByVaultAddress(item.cyanVaultAddress);
            claimableServiceFee[currencyAddress] += serviceAmount;

            CyanWalletLogic.transferItemAndLock(msg.sender, _paymentPlan.cyanWalletAddress, item);
            emit UpdatedBNPL(planId, PaymentPlanStatus.BNPL_ACTIVE);
        }
    }

    /**
     * @notice Rejecting a BNPL payment plan
     * @param planId Payment Plan ID
     */
    function rejectBNPL(uint256 planId) external payable nonReentrant onlyRole(CYAN_ROLE) {
        PaymentPlan storage _paymentPlan = paymentPlan[planId];
        if (_paymentPlan.plan.counterPaidPayments != 1) revert InvalidPaidCount();
        if (
            _paymentPlan.status != PaymentPlanStatus.BNPL_CREATED &&
            _paymentPlan.status != PaymentPlanStatus.BNPL_FUNDED
        ) {
            revert InvalidStage();
        }

        (PaymentAmountInfo memory singleAmounts, , uint256 downPaymentAmount, ) = PaymentPlanV2Logic
            .calculatePaymentInfo(_paymentPlan.plan);

        // Returning downpayment to created user address
        address currencyAddress = getCurrencyAddressByPlanId(planId);
        address createdUserAddress = getMainWalletAddress(_paymentPlan.cyanWalletAddress);
        sendCurrency(currencyAddress, downPaymentAmount + singleAmounts.serviceAmount, createdUserAddress);
        if (_paymentPlan.status == PaymentPlanStatus.BNPL_FUNDED) {
            receiveCurrency(currencyAddress, _paymentPlan.plan.amount, msg.sender);

            // Returning funded amount back to Vault
            PaymentPlanV2Logic.transferEarnedAmountToCyanVault(
                items[planId].cyanVaultAddress,
                _paymentPlan.plan.amount,
                0
            );
        } else if (msg.value > 0) {
            revert InvalidAmount();
        }
        _paymentPlan.status = PaymentPlanStatus.BNPL_REJECTED;
        emit UpdatedBNPL(planId, PaymentPlanStatus.BNPL_REJECTED);
    }

    function createPawn(
        Item calldata item,
        Plan calldata plan,
        uint256 planId,
        uint256 signedBlockNum,
        bytes memory signature
    ) external nonReentrant {
        createPawn(item, plan, planId, PawnCreateType.REGULAR, signedBlockNum, signature);
    }

    function createPawnFromBendDao(
        Item calldata item,
        Plan calldata plan,
        uint256 planId,
        uint256 signedBlockNum,
        bytes memory signature
    ) external nonReentrant {
        createPawn(item, plan, planId, PawnCreateType.BEND_DAO, signedBlockNum, signature);
    }

    function createPawnByRefinance(
        Item calldata item,
        Plan calldata plan,
        uint256 planId,
        uint256 existingPlanId,
        uint256 signedBlockNum,
        bytes memory signature
    ) external payable nonReentrant {
        requireActivePlan(existingPlanId);
        PaymentPlan storage existingPaymentPlan = paymentPlan[existingPlanId];

        address lenderMainWalletAddress = checkIsPlanOwner(msg.sender, existingPaymentPlan.cyanWalletAddress);

        // check item and current plan's item
        Item memory existingPlanItem = items[existingPlanId];
        if (
            !(existingPlanItem.tokenId == item.tokenId &&
                existingPlanItem.contractAddress == item.contractAddress &&
                existingPlanItem.itemType == item.itemType &&
                existingPlanItem.amount == item.amount)
        ) revert InvalidItem();

        // check current plan currency and requested loan currency
        address currencyAddress = PaymentPlanV2Logic.getCurrencyAddressByVaultAddress(item.cyanVaultAddress);
        if (currencyAddress != getCurrencyAddressByPlanId(existingPlanId)) revert InvalidCurrency();

        (
            uint256 payAmountForCollateral,
            uint256 payAmountForInterest,
            uint256 payAmountForService,
            uint256 currentPayment,

        ) = getPaymentInfoByPlanId(existingPlanId, true);

        // creating new plan and lending requested loan amount to payment plan
        createPawn(item, plan, planId, PawnCreateType.REFINANCE, signedBlockNum, signature);

        // completing previous active plan
        if (plan.amount < currentPayment) {
            receiveCurrency(currencyAddress, currentPayment - plan.amount, msg.sender);
        } else {
            uint256 transferAmountToUser = plan.amount - currentPayment;
            if (transferAmountToUser > 0) {
                sendCurrency(currencyAddress, transferAmountToUser, lenderMainWalletAddress);
            }
        }

        claimableServiceFee[currencyAddress] += payAmountForService;
        PaymentPlanV2Logic.transferEarnedAmountToCyanVault(
            existingPlanItem.cyanVaultAddress,
            payAmountForCollateral,
            payAmountForInterest
        );

        emit CompletedEarly(
            existingPlanId,
            existingPaymentPlan.plan.totalNumberOfPayments - existingPaymentPlan.plan.counterPaidPayments
        );

        completePaymentPlan(existingPaymentPlan);
    }

    /**
     * @notice Internal function that creates a pawn plan
     * @param item Item detail to pawn
     * @param plan Pawn plan detail
     * @param planId Plan ID
     * @param signedBlockNum Signed block number
     * @param signature Signature from Cyan
     */
    function createPawn(
        Item calldata item,
        Plan calldata plan,
        uint256 planId,
        PawnCreateType createType,
        uint256 signedBlockNum,
        bytes memory signature
    ) private {
        if (paymentPlan[planId].plan.totalNumberOfPayments != 0) revert PaymentPlanAlreadyExists();
        address cyanWalletAddress = IFactory(walletFactory).getOrDeployWallet(msg.sender);
        address mainAddress = msg.sender;
        if (cyanWalletAddress == msg.sender) {
            mainAddress = getMainWalletAddress(cyanWalletAddress);
        }

        bool isTransferRequired = PaymentPlanV2Logic.createPawn(
            item,
            plan,
            planId,
            createType,
            signedBlockNum,
            mainAddress,
            cyanWalletAddress,
            cyanSigner,
            signature
        );

        if (createType != PawnCreateType.REFINANCE) {
            if (isTransferRequired) {
                CyanWalletLogic.transferItemAndLock(mainAddress, cyanWalletAddress, item);
            } else {
                CyanWalletLogic.setLockState(cyanWalletAddress, item, true);
            }
        }

        items[planId] = item;
        paymentPlan[planId] = PaymentPlan(plan, block.timestamp, cyanWalletAddress, PaymentPlanStatus.PAWN_ACTIVE);

        emit CreatedPawn(planId, createType);
    }

    /**
     * @notice Make a payment for the payment plan
     * @param planId Payment Plan ID
     * @param isEarlyPayment If true, payment will be made for the whole plan
     */
    function pay(uint256 planId, bool isEarlyPayment) external payable nonReentrant {
        requireActivePlan(planId);
        PaymentPlan storage _paymentPlan = paymentPlan[planId];

        uint8 numOfRemainingPayments = _paymentPlan.plan.totalNumberOfPayments - _paymentPlan.plan.counterPaidPayments;
        bool shouldComplete = isEarlyPayment || numOfRemainingPayments == 1;

        (
            uint256 payAmountForCollateral,
            uint256 payAmountForInterest,
            uint256 payAmountForService,
            uint256 currentPayment,

        ) = getPaymentInfoByPlanId(planId, shouldComplete);

        address currencyAddress = getCurrencyAddressByPlanId(planId);
        receiveCurrency(currencyAddress, currentPayment, msg.sender);

        claimableServiceFee[currencyAddress] += payAmountForService;
        PaymentPlanV2Logic.transferEarnedAmountToCyanVault(
            items[planId].cyanVaultAddress,
            payAmountForCollateral,
            payAmountForInterest
        );

        if (shouldComplete) {
            completePaymentPlan(_paymentPlan);
            CyanWalletLogic.setLockState(_paymentPlan.cyanWalletAddress, items[planId], false);

            if (isEarlyPayment) {
                emit CompletedEarly(planId, numOfRemainingPayments);
            } else {
                emit Completed(planId);
            }
        } else {
            ++_paymentPlan.plan.counterPaidPayments;
            emit Paid(planId);
        }
    }

    /**
     * @notice Liquidate defaulted payment plan
     * @param planId Payment Plan ID
     * @param apePlanIds Array of ape plan Ids [BAYC/MAYC Ape Plan ID, BAKC Ape Plan ID]
     * @param estimatedValue Estimated value of defaulted assets
     */
    function liquidate(
        uint256 planId,
        uint256[2] calldata apePlanIds,
        uint256 estimatedValue
    ) external nonReentrant {
        if (estimatedValue == 0) revert InvalidAmount();

        PaymentPlan storage _paymentPlan = paymentPlan[planId];
        Item memory _item = items[planId];

        if (msg.sender == _item.cyanVaultAddress) {
            requireActivePlan(planId);
        } else {
            if (!hasRole(CYAN_ROLE, msg.sender)) {
                revert InvalidSender();
            }
            requireDefaultedPlan(planId);
        }

        PaymentPlanV2Logic.checkAndCompleteApePlans(
            _paymentPlan.cyanWalletAddress,
            _item.contractAddress,
            _item.tokenId,
            apePlanIds
        );

        (uint256 unpaidAmount, , , , ) = getPaymentInfoByPlanId(planId, true);

        CyanWalletLogic.setLockState(_paymentPlan.cyanWalletAddress, _item, false);
        CyanWalletLogic.transferNonLockedItem(_paymentPlan.cyanWalletAddress, _item.cyanVaultAddress, _item);

        _paymentPlan.status = isBNPL(_paymentPlan.status)
            ? PaymentPlanStatus.BNPL_LIQUIDATED
            : PaymentPlanStatus.PAWN_LIQUIDATED;
        ICyanVaultV2(payable(_item.cyanVaultAddress)).nftDefaulted(unpaidAmount, estimatedValue);

        emit LiquidatedPaymentPlan(planId, estimatedValue, unpaidAmount);
    }

    /**
     * @notice Triggers auto repayment from the cyan wallet
     * @param planId Payment Plan ID
     */
    function triggerAutoRepay(uint256 planId) external onlyRole(CYAN_AUTO_OPERATOR_ROLE) {
        uint8 autoRepayStatus = paymentPlan[planId].plan.autoRepayStatus;
        if (autoRepayStatus != 1 && autoRepayStatus != 2) revert InvalidAutoRepaymentStatus();
        requireActivePlan(planId);

        (, , , uint256 payAmount, uint256 dueDate) = getPaymentInfoByPlanId(planId, false);
        if ((dueDate - 1 days) > block.timestamp) revert InvalidAutoRepaymentDate();

        address cyanWalletAddress = paymentPlan[planId].cyanWalletAddress;
        if (autoRepayStatus == 2) {
            // Auto-repay from main wallet
            address mainWalletAddress = getMainWalletAddress(cyanWalletAddress);
            address currencyAddress = getCurrencyAddressByPlanId(planId);
            ICyanConduit conduit = ICyanConduit(addressProvider.addresses(CYAN_CONDUIT));

            // Using WETH when currency is native currency
            if (currencyAddress == address(0)) {
                currencyAddress = addressProvider.addresses("WETH");
            }

            conduit.transferERC20(mainWalletAddress, cyanWalletAddress, currencyAddress, payAmount);
        }
        CyanWalletLogic.executeAutoPay(cyanWalletAddress, planId, payAmount, autoRepayStatus);
    }

    /**
     * @notice Early unwind the plan by Opensea offer
     * @param planId Payment Plan ID
     * @param sellPrice Sell price of the token
     * @param offer Offer data to fulfill seaport order
     */
    function earlyUnwindOpensea(
        uint256 planId,
        uint256[2] calldata apePlanIds,
        uint256 sellPrice,
        bytes calldata offer,
        uint256 signatureExpiryDate,
        bytes memory signature
    ) external nonReentrant {
        if (signatureExpiryDate < block.timestamp) revert InvalidSignature();
        PaymentPlanV2Logic.verifyEarlyUnwindByOpeanseaSignature(
            planId,
            sellPrice,
            offer,
            signatureExpiryDate,
            block.chainid,
            cyanSigner,
            signature
        );
        earlyUnwind(planId, apePlanIds, sellPrice, offer, address(0));
    }

    /**
     * @notice Early unwind the plan by Cyan offer
     * @param planId Payment Plan ID
     * @param sellPrice Sell price of the token
     * @param signatureExpiryDate Signature expiry date
     * @param cyanBuyerAddress Buyer address from Cyan
     * @param signature Signature signed by Cyan buyer
     */
    function earlyUnwindCyan(
        uint256 planId,
        uint256[2] calldata apePlanIds,
        uint256 sellPrice,
        address cyanBuyerAddress,
        uint256 signatureExpiryDate,
        bytes memory signature
    ) external nonReentrant {
        if (signatureExpiryDate < block.timestamp) revert InvalidSignature();
        PaymentPlanV2Logic.verifyEarlyUnwindByCyanSignature(
            planId,
            sellPrice,
            signatureExpiryDate,
            block.chainid,
            cyanBuyerAddress,
            signature
        );
        if (!hasRole(CYAN_ROLE, cyanBuyerAddress)) revert InvalidCyanBuyer();

        bytes memory offer; // creating empty offer data
        earlyUnwind(planId, apePlanIds, sellPrice, offer, cyanBuyerAddress);
    }

    /**
     * @notice Internal function to handle the common logic of early unwind operations
     * @param planId Payment Plan ID
     * @param sellPrice Sell price of the token
     * @param offer Offer data to fulfill seaport order
     * @param cyanBuyerAddress Buyer address from Cyan
     */
    function earlyUnwind(
        uint256 planId,
        uint256[2] calldata apePlanIds,
        uint256 sellPrice,
        bytes memory offer,
        address cyanBuyerAddress
    ) private {
        PaymentPlan storage _paymentPlan = paymentPlan[planId];
        Item memory _item = items[planId];
        requireActivePlan(planId);

        address currencyAddress = getCurrencyAddressByPlanId(planId);

        (
            uint256 payAmountForCollateral,
            uint256 payAmountForInterest,
            uint256 payAmountForService,
            uint256 currentPayment,

        ) = getPaymentInfoByPlanId(planId, true);

        if (msg.sender != _item.cyanVaultAddress) {
            checkIsPlanOwner(msg.sender, _paymentPlan.cyanWalletAddress);
        } else {
            if (currentPayment > sellPrice) revert InvalidAmount();
        }

        PaymentPlanV2Logic.checkAndCompleteApePlans(
            _paymentPlan.cyanWalletAddress,
            _item.contractAddress,
            _item.tokenId,
            apePlanIds
        );

        CyanWalletLogic.setLockState(_paymentPlan.cyanWalletAddress, _item, false);
        if (cyanBuyerAddress == address(0)) {
            if (currencyAddress != address(0)) revert InvalidCurrency();
            IWallet(_paymentPlan.cyanWalletAddress).executeModule(
                abi.encodeWithSelector(IWallet.earlyUnwindOpensea.selector, currentPayment, sellPrice, _item, offer)
            );
        } else {
            ICyanConduit(addressProvider.addresses(CYAN_CONDUIT)).transferERC20(
                cyanBuyerAddress,
                _paymentPlan.cyanWalletAddress,
                currencyAddress == address(0) ? addressProvider.addresses("WETH") : currencyAddress,
                sellPrice
            );
            IWallet(_paymentPlan.cyanWalletAddress).executeModule(
                abi.encodeWithSelector(IWallet.earlyUnwindCyan.selector, currentPayment, currencyAddress)
            );
            CyanWalletLogic.transferNonLockedItem(_paymentPlan.cyanWalletAddress, cyanBuyerAddress, _item);
        }

        PaymentPlanV2Logic.receiveCurrencyFromCyanWallet(
            currencyAddress,
            _paymentPlan.cyanWalletAddress,
            currentPayment
        );

        claimableServiceFee[currencyAddress] += payAmountForService;
        PaymentPlanV2Logic.transferEarnedAmountToCyanVault(
            _item.cyanVaultAddress,
            payAmountForCollateral,
            payAmountForInterest
        );
        completePaymentPlan(_paymentPlan);

        emit EarlyUnwind(planId);
    }

    receive() external payable {}

    /**
     * @notice Revive defaulted payment plan with penalty
     * @param planId Payment Plan ID
     * @param penaltyAmount Amount that penalizes Defaulted plan revival
     * @param signatureExpiryDate Signature expiry date
     * @param signature Signature signed by Cyan signer
     */
    function revive(
        uint256 planId,
        uint256 penaltyAmount,
        uint256 signatureExpiryDate,
        bytes memory signature
    ) external payable nonReentrant {
        PaymentPlan storage _paymentPlan = paymentPlan[planId];
        if (signatureExpiryDate < block.timestamp) revert InvalidReviveDate();
        PaymentPlanV2Logic.verifyRevivalSignature(
            planId,
            penaltyAmount,
            signatureExpiryDate,
            block.chainid,
            _paymentPlan.plan.counterPaidPayments,
            cyanSigner,
            signature
        );
        requireDefaultedPlan(planId);

        (
            uint256 payAmountForCollateral,
            uint256 payAmountForInterest,
            uint256 payAmountForService,
            uint256 currentPayment,
            uint256 dueDate
        ) = getPaymentInfoByPlanId(planId, false);
        if (dueDate + _paymentPlan.plan.term <= block.timestamp) revert InvalidReviveDate();

        address currencyAddress = getCurrencyAddressByPlanId(planId);
        receiveCurrency(currencyAddress, currentPayment + penaltyAmount, msg.sender);

        claimableServiceFee[currencyAddress] += payAmountForService;
        PaymentPlanV2Logic.transferEarnedAmountToCyanVault(
            items[planId].cyanVaultAddress,
            payAmountForCollateral,
            payAmountForInterest + penaltyAmount
        );
        if (_paymentPlan.plan.counterPaidPayments + 1 == _paymentPlan.plan.totalNumberOfPayments) {
            completePaymentPlan(_paymentPlan);
            CyanWalletLogic.setLockState(_paymentPlan.cyanWalletAddress, items[planId], false);
            emit CompletedByRevival(planId, penaltyAmount);
        } else {
            ++_paymentPlan.plan.counterPaidPayments;
            emit Revived(planId, penaltyAmount);
        }
    }

    function getPaymentInfoByPlanId(uint256 planId, bool isEarlyPayment)
        public
        view
        returns (
            uint256,
            uint256,
            uint256,
            uint256,
            uint256
        )
    {
        Plan memory plan = paymentPlan[planId].plan;
        if (plan.totalNumberOfPayments == 0) revert PaymentPlanNotFound();

        return PaymentPlanV2Logic.getPaymentInfo(plan, isEarlyPayment, paymentPlan[planId].createdDate);
    }

    /**
     * @notice Check if payment plan is pending
     * @param planId Payment Plan ID
     * @return PaymentPlanStatus
     */
    function getPlanStatus(uint256 planId) public view returns (PaymentPlanStatus) {
        if (
            paymentPlan[planId].status == PaymentPlanStatus.BNPL_ACTIVE ||
            paymentPlan[planId].status == PaymentPlanStatus.PAWN_ACTIVE
        ) {
            (, , , , uint256 dueDate) = getPaymentInfoByPlanId(planId, false);
            bool isDefaulted = block.timestamp > dueDate;

            if (isDefaulted) {
                return
                    paymentPlan[planId].status == PaymentPlanStatus.BNPL_ACTIVE
                        ? PaymentPlanStatus.BNPL_DEFAULTED
                        : PaymentPlanStatus.PAWN_DEFAULTED;
            }
        }

        return paymentPlan[planId].status;
    }

    /**
     * @notice Updating Cyan signer address
     * @param _cyanSigner New Cyan signer address
     */
    function updateCyanSignerAddress(address _cyanSigner) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_cyanSigner == address(0)) revert InvalidAddress();
        cyanSigner = _cyanSigner;
        emit UpdatedCyanSigner(_cyanSigner);
    }

    /**
     * @notice Claiming collected service fee amount
     * @param currencyAddress Currency address
     */
    function claimServiceFee(address currencyAddress) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
        uint256 amount = claimableServiceFee[currencyAddress];
        sendCurrency(currencyAddress, amount, msg.sender);
        claimableServiceFee[currencyAddress] = 0;
        emit ClaimedServiceFee(currencyAddress, amount);
    }

    /**
     * @notice Updating Cyan wallet factory address that used for deploying new wallets
     * @param factory New Cyan wallet factory address
     */
    function updateWalletFactoryAddress(address factory) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (factory == address(0)) revert InvalidAddress();
        walletFactory = factory;
        emit UpdatedWalletFactory(factory);
    }

    /**
     * @notice Setting auto repay status for a payment plan
     * @param planId Payment plan ID
     * @param autoRepayStatus Auto repay status
     */
    function setAutoRepayStatus(uint256 planId, uint8 autoRepayStatus) external {
        checkIsPlanOwner(msg.sender, paymentPlan[planId].cyanWalletAddress);

        paymentPlan[planId].plan.autoRepayStatus = autoRepayStatus;
        emit SetAutoRepayStatus(planId, autoRepayStatus);
    }

    /**
     * @notice Getting currency address by plan ID
     * @param planId Payment plan ID
     */
    function getCurrencyAddressByPlanId(uint256 planId) public view returns (address) {
        return PaymentPlanV2Logic.getCurrencyAddressByVaultAddress(items[planId].cyanVaultAddress);
    }

    /**
     * @notice Getting main wallet address by Cyan wallet address
     * @param cyanWalletAddress Cyan wallet address
     */
    function getMainWalletAddress(address cyanWalletAddress) private view returns (address) {
        return IFactory(walletFactory).getWalletOwner(cyanWalletAddress);
    }

    function requireActivePlan(uint256 planId) private view {
        PaymentPlanStatus status = getPlanStatus(planId);
        if (status != PaymentPlanStatus.BNPL_ACTIVE && status != PaymentPlanStatus.PAWN_ACTIVE) revert InvalidStage();
    }

    function requireDefaultedPlan(uint256 planId) private view {
        PaymentPlanStatus status = getPlanStatus(planId);
        if (status != PaymentPlanStatus.BNPL_DEFAULTED && status != PaymentPlanStatus.PAWN_DEFAULTED)
            revert InvalidStage();
    }

    /**
     * @notice Marks a payment plan as completed.
     * @param _paymentPlan A reference to the PaymentPlan structure being completed
     */
    function completePaymentPlan(PaymentPlan storage _paymentPlan) private {
        _paymentPlan.plan.counterPaidPayments = _paymentPlan.plan.totalNumberOfPayments;
        _paymentPlan.status = isBNPL(_paymentPlan.status)
            ? PaymentPlanStatus.BNPL_COMPLETED
            : PaymentPlanStatus.PAWN_COMPLETED;
    }

    /**
     * @notice Return true if plan is BNPL by checking status
     * @param status Payment plan status
     * @return Is BNPL
     */
    function isBNPL(PaymentPlanStatus status) private pure returns (bool) {
        return
            status == PaymentPlanStatus.BNPL_CREATED ||
            status == PaymentPlanStatus.BNPL_FUNDED ||
            status == PaymentPlanStatus.BNPL_ACTIVE ||
            status == PaymentPlanStatus.BNPL_DEFAULTED ||
            status == PaymentPlanStatus.BNPL_REJECTED ||
            status == PaymentPlanStatus.BNPL_COMPLETED ||
            status == PaymentPlanStatus.BNPL_LIQUIDATED;
    }

    /**
     * @notice Receives currency for transaction. Supports both native and ERC20 tokens.
     * @param currency The address of the currency (address(0) for native, token address for ERC20).
     * @param amount The amount of currency to receive
     * @param from The sender's address
     */
    function receiveCurrency(
        address currency,
        uint256 amount,
        address from
    ) private {
        if (currency == address(0)) {
            if (amount != msg.value) revert InvalidAmount();
        } else {
            if (msg.value != 0) revert InvalidAmount();
            ICyanConduit(addressProvider.addresses(CYAN_CONDUIT)).transferERC20(from, address(this), currency, amount);
        }
    }

    /**
     * @notice Sends currency to a specified address. Supports both native and ERC20 tokens.
     * @param currency The address of the currency (address(0) for native, token address for ERC20).
     * @param amount The amount of currency to send
     * @param to The recipient's address
     */
    function sendCurrency(
        address currency,
        uint256 amount,
        address to
    ) private {
        if (currency == address(0)) {
            (bool success, ) = payable(to).call{ value: amount }("");
            if (!success) revert EthTransferFailed();
            return;
        } else {
            IERC20Upgradeable erc20Contract = IERC20Upgradeable(currency);
            erc20Contract.safeTransfer(to, amount);
        }
    }

    function checkIsPlanOwner(address sender, address planCyanWallet) private view returns (address) {
        address _sender = sender;
        if (sender != planCyanWallet) {
            _sender = getMainWalletAddress(planCyanWallet);
            if (sender != _sender) revert InvalidSender();
        }
        return _sender;
    }
}

File 2 of 36 : AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

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

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

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

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

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

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

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

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

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

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

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

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

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

        _revokeRole(role, account);
    }

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

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

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 4 of 36 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

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

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

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

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

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

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized < type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Internal function that returns the initialized version. Returns `_initialized`
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Internal function that returns the initialized version. Returns `_initializing`
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

File 5 of 36 : ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

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

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

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

    uint256 private _status;

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

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _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 This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 6 of 36 : draft-IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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 IERC20PermitUpgradeable {
    /**
     * @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);
}

File 7 of 36 : IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 8 of 36 : SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";
import "../extensions/draft-IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
    using AddressUpgradeable for address;

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

    function safeTransferFrom(
        IERC20Upgradeable 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(
        IERC20Upgradeable token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

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

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

    function safePermit(
        IERC20PermitUpgradeable 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(IERC20Upgradeable token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

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

File 9 of 36 : IERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721Upgradeable is IERC165Upgradeable {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

File 10 of 36 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [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://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

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

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

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

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

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

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 12 of 36 : ECDSAUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../StringsUpgradeable.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSAUpgradeable {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

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

pragma solidity ^0.8.0;

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

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

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

pragma solidity ^0.8.0;

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

File 15 of 36 : MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}

File 16 of 36 : StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/MathUpgradeable.sol";

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = MathUpgradeable.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, MathUpgradeable.log256(value) + 1);
        }
    }

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

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

File 17 of 36 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

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

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

File 18 of 36 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * 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}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * 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 value {ERC20} uses, unless this function is
     * 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;
        }
        _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;
        _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;
        }
        _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 {}
}

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

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

File 20 of 36 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

File 22 of 36 : ICyanConduit.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

enum ConduitItemType {
    NATIVE, // unused
    ERC20,
    ERC721,
    ERC1155
}

struct ConduitTransfer {
    ConduitItemType itemType;
    address collection;
    address from;
    address to;
    uint256 identifier;
    uint256 amount;
}

struct ConduitBatch1155Transfer {
    address collection;
    address from;
    address to;
    uint256[] ids;
    uint256[] amounts;
}

interface ICyanConduit {
    error ChannelClosed(address channel);
    error ChannelStatusAlreadySet(address channel, bool isOpen);
    error InvalidItemType();
    error InvalidAdmin();

    event ChannelUpdated(address indexed channel, bool open);

    function execute(ConduitTransfer[] calldata transfers) external returns (bytes4 magicValue);

    function executeBatch1155(ConduitBatch1155Transfer[] calldata batch1155Transfers)
        external
        returns (bytes4 magicValue);

    function executeWithBatch1155(
        ConduitTransfer[] calldata standardTransfers,
        ConduitBatch1155Transfer[] calldata batch1155Transfers
    ) external returns (bytes4 magicValue);

    function transferERC20(
        address from,
        address to,
        address token,
        uint256 amount
    ) external;

    function transferERC721(
        address from,
        address to,
        address collection,
        uint256 tokenId
    ) external;

    function transferERC1155(
        address from,
        address to,
        address collection,
        uint256 tokenId,
        uint256 amount
    ) external;

    function updateChannel(address channel, bool isOpen) external;
}

File 23 of 36 : IFactory.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface IFactory {
    function getOrDeployWallet(address) external returns (address);

    function getWalletOwner(address) external view returns (address);

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

File 24 of 36 : IWallet.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import { Item } from "../../main/payment-plan/PaymentPlanTypes.sol";

interface IWallet {
    function executeModule(bytes memory) external returns (bytes memory);

    function transferNonLockedERC721(
        address,
        uint256,
        address
    ) external;

    function transferNonLockedERC1155(
        address,
        uint256,
        uint256,
        address
    ) external;

    function transferNonLockedCryptoPunk(uint256, address) external;

    function setLockedERC721Token(
        address,
        uint256,
        bool
    ) external;

    function increaseLockedERC1155Token(
        address,
        uint256,
        uint256
    ) external;

    function decreaseLockedERC1155Token(
        address,
        uint256,
        uint256
    ) external;

    function setLockedCryptoPunk(uint256, bool) external;

    function autoPay(
        uint256,
        uint256,
        uint8
    ) external;

    function earlyUnwindOpensea(
        uint256,
        uint256,
        Item memory,
        bytes memory
    ) external;

    function earlyUnwindCyan(uint256, address) external;

    function isLockedNFT(address, uint256) external view returns (bool);

    function repayBendDaoLoan(
        address collection,
        uint256 tokenId,
        uint256 amount,
        address currency
    ) external;
}

File 25 of 36 : IWalletApeCoin.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import "./IWallet.sol";

interface IWalletApeCoin is IWallet {
    function depositBAYCAndLock(uint32 tokenId, uint224 amount) external;

    function depositMAYCAndLock(uint32 tokenId, uint224 amount) external;

    function depositBAKCAndLock(
        address mainCollection,
        uint32 mainTokenId,
        uint32 bakcTokenId,
        uint224 amount
    ) external;

    function withdrawBAYCAndUnlock(uint32 tokenId) external;

    function withdrawMAYCAndUnlock(uint32 tokenId) external;

    function withdrawBAKCAndUnlock(uint32 tokenId) external;

    function autoCompound(uint256 poolId, uint32 tokenId) external;

    function getApeLockState(address collection, uint256 tokenId) external view returns (uint8);

    function completeApeCoinPlan(uint256 planId) external;
}

File 26 of 36 : ICyanPaymentPlanV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import { PaymentPlanStatus } from "../../main/payment-plan/PaymentPlanTypes.sol";

interface ICyanPaymentPlanV2 {
    function pay(uint256, bool) external payable;

    function getPlanStatus(uint256) external view returns (PaymentPlanStatus);

    function getCurrencyAddressByPlanId(uint256) external view returns (address);

    function earlyUnwindOpensea(
        uint256,
        uint256[2] calldata,
        uint256,
        bytes memory,
        uint256,
        bytes memory
    ) external;

    function earlyUnwindCyan(
        uint256,
        uint256[2] calldata,
        uint256,
        address,
        uint256,
        bytes memory
    ) external;

    function liquidate(
        uint256,
        uint256[2] calldata,
        uint256
    ) external;
}

File 27 of 36 : ICyanPeerPlan.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface ICyanPeerPlan {
    enum PlanStatus {
        NONE,
        ACTIVE,
        DEFAULTED,
        COMPLETED,
        LIQUIDATED
    }
    struct LenderSignature {
        uint256 signedDate;
        uint256 expiryDate;
        uint32 maxUsageCount;
        bool extendable;
        bytes signature;
    }
    struct Plan {
        uint256 amount;
        address lenderAddress;
        address currencyAddress;
        uint32 interestRate;
        uint32 serviceFeeRate;
        uint32 term;
    }
    struct PaymentPlan {
        Plan plan;
        uint256 dueDate;
        address cyanWalletAddress;
        PlanStatus status;
        bool extendable;
    }
    struct Item {
        uint256 amount;
        uint256 tokenId;
        address contractAddress;
        // 1 -> ERC721
        // 2 -> ERC1155
        // 3 -> CryptoPunks
        uint8 itemType;
        bytes collectionSignature;
    }
}

File 28 of 36 : ICyanVaultV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface ICyanVaultV2 {
    function getCurrencyAddress() external view returns (address);

    function lend(address to, uint256 amount) external;

    function earn(uint256 amount, uint256 profit) external payable;

    function nftDefaulted(uint256 unpaidAmount, uint256 estimatedPriceOfNFT) external;

    function withdrawLocked(address cyanWalletAddress) external view returns (uint256);
}

File 29 of 36 : AddressProvider.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

/// @title Cyan AddressProvider contract
/// @author Bulgantamir Gankhuyag - <[email protected]>
/// @author Naranbayar Uuganbayar - <[email protected]>
contract AddressProvider is Ownable {
    error AddressNotFound(bytes32 id);

    event AddressSet(bytes32 id, address newAddress);

    mapping(bytes32 => address) public addresses;

    constructor(address owner) {
        transferOwnership(owner);
    }

    // @dev Sets an address for an id replacing the address saved in the addresses map
    // @param id The id
    // @param newAddress The address to set
    function setAddress(bytes32 id, address newAddress) external onlyOwner {
        addresses[id] = newAddress;
        emit AddressSet(id, newAddress);
    }
}

File 30 of 36 : CyanWalletLogic.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import { ICyanConduit } from "../interfaces/conduit/ICyanConduit.sol";
import { AddressProvider } from "../main/AddressProvider.sol";
import "../thirdparty/ICryptoPunk.sol";
import "../interfaces/core/IWallet.sol";
import "../interfaces/main/ICyanPeerPlan.sol";
import "./payment-plan/PaymentPlanTypes.sol";

library CyanWalletLogic {
    AddressProvider private constant addressProvider = AddressProvider(0xCF9A19D879769aDaE5e4f31503AAECDa82568E55);

    /**
     * @notice Allows operators to transfer out non locked tokens.
     *     Note: Can only transfer if token is not locked.
     * @param cyanWalletAddress Cyan Wallet address
     * @param to Receiver address
     * @param item Transferring item
     */
    function transferNonLockedItem(
        address cyanWalletAddress,
        address to,
        Item calldata item
    ) external {
        _transferNonLockedItem(cyanWalletAddress, to, item.contractAddress, item.tokenId, item.amount, item.itemType);
    }

    /**
     * @notice Allows operators to transfer out non locked tokens.
     *     Note: Can only transfer if token is not locked.
     * @param cyanWalletAddress Cyan Wallet address
     * @param to Receiver address
     * @param item Transferring item
     */
    function transferNonLockedItem(
        address cyanWalletAddress,
        address to,
        ICyanPeerPlan.Item calldata item
    ) external {
        _transferNonLockedItem(cyanWalletAddress, to, item.contractAddress, item.tokenId, item.amount, item.itemType);
    }

    function _transferNonLockedItem(
        address cyanWalletAddress,
        address to,
        address collection,
        uint256 tokenId,
        uint256 amount,
        uint8 itemType
    ) private {
        IWallet wallet = IWallet(cyanWalletAddress);
        if (itemType == 1) {
            // ERC721
            wallet.executeModule(
                abi.encodeWithSelector(IWallet.transferNonLockedERC721.selector, collection, tokenId, to)
            );
        } else if (itemType == 2) {
            // ERC1155
            wallet.executeModule(
                abi.encodeWithSelector(IWallet.transferNonLockedERC1155.selector, collection, tokenId, amount, to)
            );
        } else if (itemType == 3) {
            // CryptoPunks
            wallet.executeModule(abi.encodeWithSelector(IWallet.transferNonLockedCryptoPunk.selector, tokenId, to));
        } else {
            revert InvalidItem();
        }
    }

    /**
     * @notice Transfers token to CyanWallet and locks it
     * @param from From address
     * @param cyanWalletAddress Cyan Wallet address
     * @param item Transferring item
     */
    function transferItemAndLock(
        address from,
        address cyanWalletAddress,
        Item calldata item
    ) external {
        _transferItemAndLock(from, cyanWalletAddress, item.contractAddress, item.tokenId, item.amount, item.itemType);
    }

    /**
     * @notice Transfers token to CyanWallet and locks it
     * @param from From address
     * @param cyanWalletAddress Cyan Wallet address
     * @param item Transferring item
     */
    function transferItemAndLock(
        address from,
        address cyanWalletAddress,
        ICyanPeerPlan.Item calldata item
    ) external {
        _transferItemAndLock(from, cyanWalletAddress, item.contractAddress, item.tokenId, item.amount, item.itemType);
    }

    function _transferItemAndLock(
        address from,
        address cyanWalletAddress,
        address collection,
        uint256 tokenId,
        uint256 amount,
        uint8 itemType
    ) private {
        if (itemType == 3) {
            // CryptoPunks
            ICryptoPunk cryptoPunkContract = ICryptoPunk(collection);
            if (cryptoPunkContract.punkIndexToAddress(tokenId) != from) revert InvalidItem();
            cryptoPunkContract.buyPunk{ value: 0 }(tokenId);
            cryptoPunkContract.transferPunk(cyanWalletAddress, tokenId);
        } else {
            ICyanConduit conduit = ICyanConduit(addressProvider.addresses("CYAN_CONDUIT"));
            if (itemType == 1) {
                conduit.transferERC721(from, cyanWalletAddress, collection, tokenId);
            } else if (itemType == 2) {
                conduit.transferERC1155(from, cyanWalletAddress, collection, tokenId, amount);
            } else {
                revert InvalidItem();
            }
        }

        _setLockState(cyanWalletAddress, collection, tokenId, amount, itemType, true);
    }

    /**
     * @notice Update locking status of a token in Cyan Wallet
     * @param cyanWalletAddress Cyan Wallet address
     * @param item Locking/unlocking item
     * @param state Token will be locked if true
     */
    function setLockState(
        address cyanWalletAddress,
        Item calldata item,
        bool state
    ) public {
        _setLockState(cyanWalletAddress, item.contractAddress, item.tokenId, item.amount, item.itemType, state);
    }

    /**
     * @notice Update locking status of a token in Cyan Wallet
     * @param cyanWalletAddress Cyan Wallet address
     * @param item Locking/unlocking item
     * @param state Token will be locked if true
     */
    function setLockState(
        address cyanWalletAddress,
        ICyanPeerPlan.Item calldata item,
        bool state
    ) public {
        _setLockState(cyanWalletAddress, item.contractAddress, item.tokenId, item.amount, item.itemType, state);
    }

    function _setLockState(
        address cyanWalletAddress,
        address collection,
        uint256 tokenId,
        uint256 amount,
        uint8 itemType,
        bool state
    ) private {
        IWallet wallet = IWallet(cyanWalletAddress);
        if (itemType == 1) {
            // ERC721
            wallet.executeModule(
                abi.encodeWithSelector(IWallet.setLockedERC721Token.selector, collection, tokenId, state)
            );
        } else if (itemType == 2) {
            // ERC1155
            wallet.executeModule(
                abi.encodeWithSelector(
                    state ? IWallet.increaseLockedERC1155Token.selector : IWallet.decreaseLockedERC1155Token.selector,
                    collection,
                    tokenId,
                    amount
                )
            );
        } else if (itemType == 3) {
            // CryptoPunks
            wallet.executeModule(abi.encodeWithSelector(IWallet.setLockedCryptoPunk.selector, tokenId, state));
        } else {
            revert InvalidItem();
        }
    }

    /**
     * @notice Triggers Cyan Wallet's autoPay method
     * @param cyanWalletAddress Cyan Wallet address
     * @param planId Payment plan ID
     * @param amount Pay amount for the plan
     * @param autoRepayStatus Auto repayment status
     */
    function executeAutoPay(
        address cyanWalletAddress,
        uint256 planId,
        uint256 amount,
        uint8 autoRepayStatus
    ) external {
        IWallet(cyanWalletAddress).executeModule(
            abi.encodeWithSelector(IWallet.autoPay.selector, planId, amount, autoRepayStatus)
        );
    }
}

File 31 of 36 : PaymentPlanTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

// DataTypes
enum PawnCreateType {
    REGULAR,
    BEND_DAO,
    REFINANCE
}
enum PaymentPlanStatus {
    BNPL_CREATED,
    BNPL_FUNDED,
    BNPL_ACTIVE,
    BNPL_DEFAULTED,
    BNPL_REJECTED,
    BNPL_COMPLETED,
    BNPL_LIQUIDATED,
    PAWN_ACTIVE,
    PAWN_DEFAULTED,
    PAWN_COMPLETED,
    PAWN_LIQUIDATED
}
struct Plan {
    uint256 amount;
    uint32 downPaymentPercent;
    uint32 interestRate;
    uint32 serviceFeeRate;
    uint32 term;
    uint8 totalNumberOfPayments;
    uint8 counterPaidPayments;
    uint8 autoRepayStatus;
}
struct PaymentPlan {
    Plan plan;
    uint256 createdDate;
    address cyanWalletAddress;
    PaymentPlanStatus status;
}

struct Item {
    uint256 amount;
    uint256 tokenId;
    address contractAddress;
    address cyanVaultAddress;
    // 1 -> ERC721
    // 2 -> ERC1155
    // 3 -> CryptoPunks
    uint8 itemType;
}

struct PaymentAmountInfo {
    uint256 loanAmount;
    uint256 interestAmount;
    uint256 serviceAmount;
}

// Errors
error InvalidSender();
error InvalidBlockNumber();
error InvalidSignature();
error InvalidServiceFeeRate();
error InvalidTokenPrice();
error InvalidInterestRate();
error InvalidDownPaymentPercent();
error InvalidDownPayment();
error InvalidAmount();
error InvalidTerm();
error InvalidPaidCount();
error InvalidStage();
error InvalidAddress();
error InvalidAutoRepaymentDate();
error InvalidAutoRepaymentStatus();
error InvalidTotalNumberOfPayments();
error InvalidReviveDate();
error InvalidItem();
error InvalidBaseDiscountRate();
error InvalidApeCoinPlan();
error InvalidBendDaoPlan();
error InvalidCurrency();
error InvalidCyanBuyer();
error InvalidSelector();

error EthTransferFailed();

error PaymentPlanAlreadyExists();
error PaymentPlanNotFound();

File 32 of 36 : PaymentPlanV2Logic.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";

import "./PaymentPlanTypes.sol";
import "../../thirdparty/ICryptoPunk.sol";
import "../../thirdparty/IWETH.sol";
import "../../interfaces/core/IWalletApeCoin.sol";
import "../../interfaces/main/ICyanVaultV2.sol";
import "../../interfaces/core/IFactory.sol";
import { ICyanConduit } from "../../interfaces/conduit/ICyanConduit.sol";
import { ILendPoolLoan as IBDaoLendPoolLoan } from "../../thirdparty/benddao/ILendPoolLoan.sol";
import { DataTypes as BDaoDataTypes } from "../../thirdparty/benddao/DataTypes.sol";
import { AddressProvider } from "../../main/AddressProvider.sol";

/// @title Cyan Core Payment Plan V2 Logic
/// @author Bulgantamir Gankhuyag - <[email protected]>
/// @author Naranbayar Uuganbayar - <[email protected]>
library PaymentPlanV2Logic {
    AddressProvider private constant addressProvider = AddressProvider(0xCF9A19D879769aDaE5e4f31503AAECDa82568E55);

    using ECDSAUpgradeable for bytes32;
    using SafeERC20Upgradeable for IERC20Upgradeable;

    function checkAndCompleteApePlans(
        address cyanWalletAddress,
        address collection,
        uint256 tokenId,
        uint256[2] calldata apePlanIds
    ) external {
        IWalletApeCoin cyanWallet = IWalletApeCoin(cyanWalletAddress);

        _checkAndCompleteApePlan(cyanWallet, apePlanIds[0], collection, tokenId);
        _checkAndCompleteApePlan(cyanWallet, apePlanIds[1], collection, tokenId);
    }

    function _checkAndCompleteApePlan(
        IWalletApeCoin cyanWallet,
        uint256 apePlanId,
        address collection,
        uint256 tokenId
    ) private {
        if (apePlanId == 0) return;

        uint8 apeLockStateBefore = cyanWallet.getApeLockState(collection, tokenId);
        cyanWallet.executeModule(abi.encodeWithSelector(IWalletApeCoin.completeApeCoinPlan.selector, apePlanId));
        uint8 apeLockStateAfter = cyanWallet.getApeLockState(collection, tokenId);

        if (apeLockStateAfter >= apeLockStateBefore) revert InvalidApeCoinPlan();
    }

    /**
     * @notice Return expected payment plan for given price and interest rate
     * @param plan Plan details
     * @return Expected down payment amount
     * @return Expected total interest fee
     * @return Expected total service fee
     * @return Estimated subsequent payments after down payment
     * @return Expected total financing amount
     */
    function getExpectedPlan(Plan calldata plan)
        external
        pure
        returns (
            uint256,
            uint256,
            uint256,
            uint256,
            uint256
        )
    {
        if (plan.totalNumberOfPayments == 0) revert InvalidTotalNumberOfPayments();
        (
            PaymentAmountInfo memory singleAmounts,
            PaymentAmountInfo memory totalAmounts,
            uint256 downPaymentAmount,

        ) = calculatePaymentInfo(plan);
        uint256 totalFinancingAmount = plan.amount + totalAmounts.interestAmount + totalAmounts.serviceAmount;

        return (
            plan.downPaymentPercent > 0 ? downPaymentAmount + singleAmounts.serviceAmount : 0,
            totalAmounts.interestAmount,
            totalAmounts.serviceAmount,
            singleAmounts.loanAmount + singleAmounts.interestAmount + singleAmounts.serviceAmount,
            totalFinancingAmount
        );
    }

    function calculatePaymentInfo(Plan memory plan)
        internal
        pure
        returns (
            PaymentAmountInfo memory singleAmounts,
            PaymentAmountInfo memory totalAmounts,
            uint256 downPaymentAmount,
            uint8 payCountWithoutDownPayment
        )
    {
        payCountWithoutDownPayment = plan.totalNumberOfPayments - (plan.downPaymentPercent > 0 ? 1 : 0);
        downPaymentAmount = (plan.amount * plan.downPaymentPercent) / 10000;

        totalAmounts.loanAmount = plan.amount - downPaymentAmount;
        totalAmounts.interestAmount = (totalAmounts.loanAmount * plan.interestRate) / 10000;
        totalAmounts.serviceAmount = (plan.amount * plan.serviceFeeRate) / 10000;

        singleAmounts.loanAmount = totalAmounts.loanAmount / payCountWithoutDownPayment;
        singleAmounts.interestAmount = totalAmounts.interestAmount / payCountWithoutDownPayment;
        singleAmounts.serviceAmount = totalAmounts.serviceAmount / plan.totalNumberOfPayments;
    }

    /**
     * @notice Return payment info
     * @param plan Plan details
     * @param isEarlyPayment Is paying early
     * @return Remaining payment amount for collateral
     * @return Remaining payment amount for interest fee
     * @return Remaining payment amount for service fee
     * @return Remaining total payment amount
     */
    function getPaymentInfo(
        Plan memory plan,
        bool isEarlyPayment,
        uint256 createdDate
    )
        external
        view
        returns (
            uint256,
            uint256,
            uint256,
            uint256,
            uint256
        )
    {
        (PaymentAmountInfo memory singleAmounts, PaymentAmountInfo memory totalAmounts, , ) = calculatePaymentInfo(
            plan
        );

        uint8 paidCountWithoutDownPayment = plan.counterPaidPayments - (plan.downPaymentPercent > 0 ? 1 : 0);
        if (
            (plan.totalNumberOfPayments == 1 && plan.downPaymentPercent == 0) ||
            (plan.totalNumberOfPayments == 2 && plan.downPaymentPercent > 0)
        ) {
            // In case of single payment plan,
            // (single payment pawn, or downpayment+single payment bnpl)
            //  User will get discount from interest fee by only paying pro-rated interest fee
            uint256 completedPercent = ((block.timestamp - createdDate + 600) / 600) < (plan.term / 600)
                ? (((block.timestamp - createdDate + 600) / 600) * 100) / (plan.term / 600)
                : 100;
            singleAmounts.interestAmount = (singleAmounts.interestAmount * completedPercent) / 100;
        } else if (isEarlyPayment || (plan.totalNumberOfPayments - plan.counterPaidPayments) == 1) {
            // In case of early repayment,
            //  User will get discount from interest fee by only paying single interest fee
            singleAmounts.loanAmount = totalAmounts.loanAmount - singleAmounts.loanAmount * paidCountWithoutDownPayment;
            singleAmounts.serviceAmount =
                totalAmounts.serviceAmount -
                singleAmounts.serviceAmount *
                plan.counterPaidPayments;
        }

        return (
            singleAmounts.loanAmount,
            singleAmounts.interestAmount,
            singleAmounts.serviceAmount,
            singleAmounts.loanAmount + singleAmounts.interestAmount + singleAmounts.serviceAmount,
            createdDate + plan.term * (paidCountWithoutDownPayment + 1)
        );
    }

    function requireCorrectPlanParams(
        bool isBNPL,
        Item calldata item,
        Plan calldata plan,
        uint256 signedBlockNum
    ) public view {
        if (item.contractAddress == address(0)) revert InvalidAddress();
        if (item.cyanVaultAddress == address(0)) revert InvalidAddress();
        if (item.itemType < 1 || item.itemType > 3) revert InvalidItem();
        if (item.itemType == 1 && item.amount != 0) revert InvalidItem();
        if (item.itemType == 2 && item.amount == 0) revert InvalidItem();
        if (item.itemType == 3 && item.amount != 0) revert InvalidItem();

        if (signedBlockNum + 50 < block.number) revert InvalidSignature();
        if (plan.serviceFeeRate > 400) revert InvalidServiceFeeRate();
        if (plan.amount == 0) revert InvalidTokenPrice();
        if (plan.interestRate == 0) revert InvalidInterestRate();
        if (plan.term == 0) revert InvalidTerm();

        if (isBNPL) {
            if (plan.downPaymentPercent == 0 || plan.downPaymentPercent >= 10000) revert InvalidDownPaymentPercent();
            if (plan.totalNumberOfPayments <= 1) revert InvalidTotalNumberOfPayments();
            if (plan.counterPaidPayments != 1) revert InvalidPaidCount();
        } else {
            if (plan.downPaymentPercent != 0) revert InvalidDownPaymentPercent();
            if (plan.totalNumberOfPayments == 0) revert InvalidTotalNumberOfPayments();
            if (plan.counterPaidPayments != 0) revert InvalidPaidCount();
        }
    }

    function verifySignature(
        Item calldata item,
        Plan calldata plan,
        uint256 planId,
        uint256 signedBlockNum,
        uint256 chainid,
        address signer,
        bytes memory signature
    ) public pure {
        bytes32 itemHash = keccak256(
            abi.encodePacked(item.cyanVaultAddress, item.contractAddress, item.tokenId, item.amount, item.itemType)
        );
        bytes32 planHash = keccak256(
            abi.encodePacked(
                plan.amount,
                plan.downPaymentPercent,
                plan.interestRate,
                plan.serviceFeeRate,
                plan.term,
                plan.totalNumberOfPayments,
                plan.counterPaidPayments,
                plan.autoRepayStatus
            )
        );
        bytes32 msgHash = keccak256(abi.encodePacked(itemHash, planHash, planId, signedBlockNum, chainid));
        bytes32 signedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash));
        if (signedHash.recover(signature) != signer) revert InvalidSignature();
    }

    function verifyRevivalSignature(
        uint256 planId,
        uint256 penaltyAmount,
        uint256 signatureExpiryDate,
        uint256 chainid,
        uint8 counterPaidPayments,
        address signer,
        bytes memory signature
    ) external pure {
        bytes32 msgHash = keccak256(
            abi.encodePacked(planId, penaltyAmount, signatureExpiryDate, chainid, counterPaidPayments)
        );
        bytes32 signedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash));
        if (signedHash.recover(signature) != signer) revert InvalidSignature();
    }

    function verifyEarlyUnwindByOpeanseaSignature(
        uint256 planId,
        uint256 sellPrice,
        bytes memory offer,
        uint256 signatureExpiryDate,
        uint256 chainid,
        address signer,
        bytes memory signature
    ) external pure {
        bytes32 offerHash = keccak256(abi.encodePacked(offer));
        bytes32 msgHash = keccak256(abi.encodePacked(planId, sellPrice, offerHash, signatureExpiryDate, chainid));
        bytes32 signedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash));
        if (signedHash.recover(signature) != signer) revert InvalidSignature();
    }

    function verifyEarlyUnwindByCyanSignature(
        uint256 planId,
        uint256 sellPrice,
        uint256 signatureExpiryDate,
        uint256 chainid,
        address cyanBuyerAddress,
        bytes memory signature
    ) external pure {
        bytes32 msgHash = keccak256(abi.encodePacked(planId, sellPrice, signatureExpiryDate, chainid));
        bytes32 signedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", msgHash));
        if (signedHash.recover(signature) != cyanBuyerAddress) revert InvalidSignature();
    }

    function receiveCurrencyFromCyanWallet(
        address currencyAddress,
        address from,
        uint256 amount
    ) external {
        if (currencyAddress == address(0)) {
            IWETH weth = IWETH(addressProvider.addresses("WETH"));
            weth.transferFrom(from, address(this), amount);
            weth.withdraw(amount);
        } else {
            IERC20Upgradeable(currencyAddress).safeTransferFrom(from, address(this), amount);
        }
    }

    /**
     * @notice Getting currency address by vault address
     * @param vaultAddress Cyan Vault address
     */
    function getCurrencyAddressByVaultAddress(address vaultAddress) internal view returns (address) {
        return ICyanVaultV2(payable(vaultAddress)).getCurrencyAddress();
    }

    function createPawn(
        Item calldata item,
        Plan calldata plan,
        uint256 planId,
        PawnCreateType createType,
        uint256 signedBlockNum,
        address mainWalletAddress,
        address cyanWalletAddress,
        address cyanSigner,
        bytes memory signature
    ) external returns (bool) {
        requireCorrectPlanParams(false, item, plan, signedBlockNum);
        verifySignature(item, plan, planId, signedBlockNum, block.chainid, cyanSigner, signature);

        if (createType == PawnCreateType.BEND_DAO) {
            ICyanVaultV2(payable(item.cyanVaultAddress)).lend(cyanWalletAddress, plan.amount);

            address currencyAddress = getCurrencyAddressByVaultAddress(item.cyanVaultAddress);
            migrateBendDaoPlan(item, plan, cyanWalletAddress, currencyAddress);

            if (IERC721Upgradeable(item.contractAddress).ownerOf(item.tokenId) != cyanWalletAddress) {
                revert InvalidBendDaoPlan();
            }
        } else if (createType == PawnCreateType.REFINANCE) {
            ICyanVaultV2(payable(item.cyanVaultAddress)).lend(address(this), plan.amount);
        } else {
            bool isTransferRequired = false;
            if (item.itemType == 1) {
                // ERC721, check if item is already in Cyan wallet
                if (IERC721Upgradeable(item.contractAddress).ownerOf(item.tokenId) != cyanWalletAddress) {
                    isTransferRequired = true;
                }
            } else if (item.itemType == 2) {
                // ERC1155, check if message sender is Cyan wallet
                if (msg.sender != cyanWalletAddress) {
                    isTransferRequired = true;
                }
            } else if (item.itemType == 3) {
                // CryptoPunk, check if item is already in Cyan wallet
                if (ICryptoPunk(item.contractAddress).punkIndexToAddress(item.tokenId) != cyanWalletAddress) {
                    isTransferRequired = true;
                }
            }
            ICyanVaultV2(payable(item.cyanVaultAddress)).lend(mainWalletAddress, plan.amount);
            return isTransferRequired;
        }
        return false;
    }

    function migrateBendDaoPlan(
        Item calldata item,
        Plan calldata plan,
        address cyanWallet,
        address currency
    ) private {
        IBDaoLendPoolLoan bendDaoLendPoolLoan = IBDaoLendPoolLoan(addressProvider.addresses("BENDDAO_LEND_POOL_LOAN"));
        uint256 loanId = bendDaoLendPoolLoan.getCollateralLoanId(item.contractAddress, item.tokenId);
        (, uint256 loanAmount) = bendDaoLendPoolLoan.getLoanReserveBorrowAmount(loanId);

        BDaoDataTypes.LoanData memory loanData = bendDaoLendPoolLoan.getLoan(loanId);
        if (loanData.state != BDaoDataTypes.LoanState.Active) revert InvalidBendDaoPlan();
        if (loanData.borrower != msg.sender) revert InvalidSender();
        if (plan.amount < loanAmount) revert InvalidAmount();
        if (loanData.reserveAsset != (currency == address(0) ? addressProvider.addresses("WETH") : currency))
            revert InvalidCurrency();

        IWallet(cyanWallet).executeModule(
            abi.encodeWithSelector(
                IWallet.repayBendDaoLoan.selector,
                item.contractAddress,
                item.tokenId,
                loanAmount,
                currency
            )
        );
        ICyanConduit(addressProvider.addresses("CYAN_CONDUIT")).transferERC721(
            loanData.borrower,
            cyanWallet,
            item.contractAddress,
            item.tokenId
        );
    }

    function activate(PaymentPlan storage _paymentPlan, Item calldata item) external returns (uint256) {
        if (_paymentPlan.plan.counterPaidPayments != 1) revert InvalidPaidCount();
        if (
            _paymentPlan.status != PaymentPlanStatus.BNPL_CREATED &&
            _paymentPlan.status != PaymentPlanStatus.BNPL_FUNDED
        ) revert InvalidStage();

        (PaymentAmountInfo memory singleAmounts, , uint256 downPaymentAmount, ) = PaymentPlanV2Logic
            .calculatePaymentInfo(_paymentPlan.plan);

        address cyanVaultAddress = item.cyanVaultAddress;

        if (_paymentPlan.status == PaymentPlanStatus.BNPL_CREATED) {
            // Admin already funded the plan, so Vault is transfering equal amount of currency back to admin.
            ICyanVaultV2(payable(cyanVaultAddress)).lend(msg.sender, _paymentPlan.plan.amount);
        }
        transferEarnedAmountToCyanVault(cyanVaultAddress, downPaymentAmount, 0);

        _paymentPlan.status = PaymentPlanStatus.BNPL_ACTIVE;
        return singleAmounts.serviceAmount;
    }

    /**
     * @notice Transfer earned amount to Cyan Vault
     * @param cyanVaultAddress Original price of the token
     * @param paidTokenPayment Paid token payment
     * @param paidInterestFee Paid interest fee
     */
    function transferEarnedAmountToCyanVault(
        address cyanVaultAddress,
        uint256 paidTokenPayment,
        uint256 paidInterestFee
    ) internal {
        ICyanVaultV2 cyanVault = ICyanVaultV2(payable(cyanVaultAddress));
        address currencyAddress = cyanVault.getCurrencyAddress();
        if (currencyAddress == address(0)) {
            cyanVault.earn{ value: paidTokenPayment + paidInterestFee }(paidTokenPayment, paidInterestFee);
        } else {
            IERC20Upgradeable erc20Contract = IERC20Upgradeable(currencyAddress);
            erc20Contract.approve(cyanVaultAddress, paidTokenPayment + paidInterestFee);
            cyanVault.earn(paidTokenPayment, paidInterestFee);
        }
    }
}

File 33 of 36 : DataTypes.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

library DataTypes {
    struct ReserveData {
        //stores the reserve configuration
        ReserveConfigurationMap configuration;
        //the liquidity index. Expressed in ray
        uint128 liquidityIndex;
        //variable borrow index. Expressed in ray
        uint128 variableBorrowIndex;
        //the current supply rate. Expressed in ray
        uint128 currentLiquidityRate;
        //the current variable borrow rate. Expressed in ray
        uint128 currentVariableBorrowRate;
        uint40 lastUpdateTimestamp;
        //tokens addresses
        address bTokenAddress;
        address debtTokenAddress;
        //address of the interest rate strategy
        address interestRateAddress;
        //the id of the reserve. Represents the position in the list of the active reserves
        uint8 id;
    }

    struct NftData {
        //stores the nft configuration
        NftConfigurationMap configuration;
        //address of the bNFT contract
        address bNftAddress;
        //the id of the nft. Represents the position in the list of the active nfts
        uint8 id;
        uint256 maxSupply;
        uint256 maxTokenId;
    }

    struct ReserveConfigurationMap {
        //bit 0-15: LTV
        //bit 16-31: Liq. threshold
        //bit 32-47: Liq. bonus
        //bit 48-55: Decimals
        //bit 56: Reserve is active
        //bit 57: reserve is frozen
        //bit 58: borrowing is enabled
        //bit 59: stable rate borrowing enabled
        //bit 60-63: reserved
        //bit 64-79: reserve factor
        uint256 data;
    }

    struct NftConfigurationMap {
        //bit 0-15: LTV
        //bit 16-31: Liq. threshold
        //bit 32-47: Liq. bonus
        //bit 56: NFT is active
        //bit 57: NFT is frozen
        uint256 data;
    }

    /**
     * @dev Enum describing the current state of a loan
     * State change flow:
     *  Created -> Active -> Repaid
     *                    -> Auction -> Defaulted
     */
    enum LoanState {
        // We need a default that is not 'Created' - this is the zero value
        None,
        // The loan data is stored, but not initiated yet.
        Created,
        // The loan has been initialized, funds have been delivered to the borrower and the collateral is held.
        Active,
        // The loan is in auction, higest price liquidator will got chance to claim it.
        Auction,
        // The loan has been repaid, and the collateral has been returned to the borrower. This is a terminal state.
        Repaid,
        // The loan was delinquent and collateral claimed by the liquidator. This is a terminal state.
        Defaulted
    }

    struct LoanData {
        //the id of the nft loan
        uint256 loanId;
        //the current state of the loan
        LoanState state;
        //address of borrower
        address borrower;
        //address of nft asset token
        address nftAsset;
        //the id of nft token
        uint256 nftTokenId;
        //address of reserve asset token
        address reserveAsset;
        //scaled borrow amount. Expressed in ray
        uint256 scaledAmount;
        //start time of first bid time
        uint256 bidStartTimestamp;
        //bidder address of higest bid
        address bidderAddress;
        //price of higest bid
        uint256 bidPrice;
        //borrow amount of loan
        uint256 bidBorrowAmount;
        //bidder address of first bid
        address firstBidderAddress;
    }

    struct ExecuteDepositParams {
        address initiator;
        address asset;
        uint256 amount;
        address onBehalfOf;
        uint16 referralCode;
    }

    struct ExecuteWithdrawParams {
        address initiator;
        address asset;
        uint256 amount;
        address to;
    }

    struct ExecuteBorrowParams {
        address initiator;
        address asset;
        uint256 amount;
        address nftAsset;
        uint256 nftTokenId;
        address onBehalfOf;
        uint16 referralCode;
    }

    struct ExecuteBatchBorrowParams {
        address initiator;
        address[] assets;
        uint256[] amounts;
        address[] nftAssets;
        uint256[] nftTokenIds;
        address onBehalfOf;
        uint16 referralCode;
    }

    struct ExecuteRepayParams {
        address initiator;
        address nftAsset;
        uint256 nftTokenId;
        uint256 amount;
    }

    struct ExecuteBatchRepayParams {
        address initiator;
        address[] nftAssets;
        uint256[] nftTokenIds;
        uint256[] amounts;
    }

    struct ExecuteAuctionParams {
        address initiator;
        address nftAsset;
        uint256 nftTokenId;
        uint256 bidPrice;
        address onBehalfOf;
    }

    struct ExecuteRedeemParams {
        address initiator;
        address nftAsset;
        uint256 nftTokenId;
        uint256 amount;
        uint256 bidFine;
    }

    struct ExecuteLiquidateParams {
        address initiator;
        address nftAsset;
        uint256 nftTokenId;
        uint256 amount;
    }

    struct ExecuteLendPoolStates {
        uint256 pauseStartTime;
        uint256 pauseDurationTime;
    }
}

File 34 of 36 : ILendPoolLoan.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import "./DataTypes.sol";

interface ILendPoolLoan {
    function getCollateralLoanId(address nftAsset, uint256 nftTokenId) external view returns (uint256);

    function getLoan(uint256 loanId) external view returns (DataTypes.LoanData memory loanData);

    function getLoanReserveBorrowAmount(uint256 loanId) external view returns (address, uint256);
}

File 35 of 36 : ICryptoPunk.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface ICryptoPunk {
    function punkIndexToAddress(uint256) external view returns (address);

    function buyPunk(uint256) external payable;

    function transferPunk(address, uint256) external;

    function offerPunkForSale(uint256, uint256) external;

    function offerPunkForSaleToAddress(
        uint256,
        uint256,
        address
    ) external;

    function acceptBidForPunk(uint256, uint256) external;
}

File 36 of 36 : IWETH.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

/// @title Wrapped Etheruem Contract interface
interface IWETH is IERC20 {
    function withdraw(uint256 wad) external;

    function deposit() external payable;
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 500
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/main/CyanWalletLogic.sol": {
      "CyanWalletLogic": "0x495279f278fe3d44b92c320d84397559271d1fb5"
    },
    "contracts/main/payment-plan/PaymentPlanV2Logic.sol": {
      "PaymentPlanV2Logic": "0x3d7bc1c3cc39e41e8be4711898075bc21c22a9d6"
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"EthTransferFailed","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidAutoRepaymentDate","type":"error"},{"inputs":[],"name":"InvalidAutoRepaymentStatus","type":"error"},{"inputs":[],"name":"InvalidCurrency","type":"error"},{"inputs":[],"name":"InvalidCyanBuyer","type":"error"},{"inputs":[],"name":"InvalidItem","type":"error"},{"inputs":[],"name":"InvalidPaidCount","type":"error"},{"inputs":[],"name":"InvalidReviveDate","type":"error"},{"inputs":[],"name":"InvalidSender","type":"error"},{"inputs":[],"name":"InvalidSignature","type":"error"},{"inputs":[],"name":"InvalidStage","type":"error"},{"inputs":[],"name":"PaymentPlanAlreadyExists","type":"error"},{"inputs":[],"name":"PaymentPlanNotFound","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"currency","type":"address"},{"indexed":true,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ClaimedServiceFee","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"}],"name":"Completed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"penaltyAmount","type":"uint256"}],"name":"CompletedByRevival","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"},{"indexed":true,"internalType":"uint8","name":"paidNumOfPayment","type":"uint8"}],"name":"CompletedEarly","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"}],"name":"CreatedBNPL","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"},{"indexed":false,"internalType":"enum PawnCreateType","name":"createType","type":"uint8"}],"name":"CreatedPawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"}],"name":"EarlyUnwind","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"estimatedPrice","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"unpaidAmount","type":"uint256"}],"name":"LiquidatedPaymentPlan","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"}],"name":"Paid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"penaltyAmount","type":"uint256"}],"name":"Revived","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"},{"indexed":true,"internalType":"uint8","name":"autoRepayStatus","type":"uint8"}],"name":"SetAutoRepayStatus","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"planId","type":"uint256"},{"indexed":true,"internalType":"enum PaymentPlanStatus","name":"planStatus","type":"uint8"}],"name":"UpdatedBNPL","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"signer","type":"address"}],"name":"UpdatedCyanSigner","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"factory","type":"address"}],"name":"UpdatedWalletFactory","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"planIds","type":"uint256[]"}],"name":"activateBNPL","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"currencyAddress","type":"address"}],"name":"claimServiceFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"claimableServiceFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"address","name":"cyanVaultAddress","type":"address"},{"internalType":"uint8","name":"itemType","type":"uint8"}],"internalType":"struct Item","name":"item","type":"tuple"},{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint32","name":"downPaymentPercent","type":"uint32"},{"internalType":"uint32","name":"interestRate","type":"uint32"},{"internalType":"uint32","name":"serviceFeeRate","type":"uint32"},{"internalType":"uint32","name":"term","type":"uint32"},{"internalType":"uint8","name":"totalNumberOfPayments","type":"uint8"},{"internalType":"uint8","name":"counterPaidPayments","type":"uint8"},{"internalType":"uint8","name":"autoRepayStatus","type":"uint8"}],"internalType":"struct Plan","name":"plan","type":"tuple"},{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"uint256","name":"signedBlockNum","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"createBNPL","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"address","name":"cyanVaultAddress","type":"address"},{"internalType":"uint8","name":"itemType","type":"uint8"}],"internalType":"struct Item","name":"item","type":"tuple"},{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint32","name":"downPaymentPercent","type":"uint32"},{"internalType":"uint32","name":"interestRate","type":"uint32"},{"internalType":"uint32","name":"serviceFeeRate","type":"uint32"},{"internalType":"uint32","name":"term","type":"uint32"},{"internalType":"uint8","name":"totalNumberOfPayments","type":"uint8"},{"internalType":"uint8","name":"counterPaidPayments","type":"uint8"},{"internalType":"uint8","name":"autoRepayStatus","type":"uint8"}],"internalType":"struct Plan","name":"plan","type":"tuple"},{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"uint256","name":"signedBlockNum","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"createPawn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"address","name":"cyanVaultAddress","type":"address"},{"internalType":"uint8","name":"itemType","type":"uint8"}],"internalType":"struct Item","name":"item","type":"tuple"},{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint32","name":"downPaymentPercent","type":"uint32"},{"internalType":"uint32","name":"interestRate","type":"uint32"},{"internalType":"uint32","name":"serviceFeeRate","type":"uint32"},{"internalType":"uint32","name":"term","type":"uint32"},{"internalType":"uint8","name":"totalNumberOfPayments","type":"uint8"},{"internalType":"uint8","name":"counterPaidPayments","type":"uint8"},{"internalType":"uint8","name":"autoRepayStatus","type":"uint8"}],"internalType":"struct Plan","name":"plan","type":"tuple"},{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"uint256","name":"existingPlanId","type":"uint256"},{"internalType":"uint256","name":"signedBlockNum","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"createPawnByRefinance","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"address","name":"cyanVaultAddress","type":"address"},{"internalType":"uint8","name":"itemType","type":"uint8"}],"internalType":"struct Item","name":"item","type":"tuple"},{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint32","name":"downPaymentPercent","type":"uint32"},{"internalType":"uint32","name":"interestRate","type":"uint32"},{"internalType":"uint32","name":"serviceFeeRate","type":"uint32"},{"internalType":"uint32","name":"term","type":"uint32"},{"internalType":"uint8","name":"totalNumberOfPayments","type":"uint8"},{"internalType":"uint8","name":"counterPaidPayments","type":"uint8"},{"internalType":"uint8","name":"autoRepayStatus","type":"uint8"}],"internalType":"struct Plan","name":"plan","type":"tuple"},{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"uint256","name":"signedBlockNum","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"createPawnFromBendDao","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"uint256[2]","name":"apePlanIds","type":"uint256[2]"},{"internalType":"uint256","name":"sellPrice","type":"uint256"},{"internalType":"address","name":"cyanBuyerAddress","type":"address"},{"internalType":"uint256","name":"signatureExpiryDate","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"earlyUnwindCyan","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"uint256[2]","name":"apePlanIds","type":"uint256[2]"},{"internalType":"uint256","name":"sellPrice","type":"uint256"},{"internalType":"bytes","name":"offer","type":"bytes"},{"internalType":"uint256","name":"signatureExpiryDate","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"earlyUnwindOpensea","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"planIds","type":"uint256[]"}],"name":"fundBNPL","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"}],"name":"getCurrencyAddressByPlanId","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"bool","name":"isEarlyPayment","type":"bool"}],"name":"getPaymentInfoByPlanId","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"}],"name":"getPlanStatus","outputs":[{"internalType":"enum PaymentPlanStatus","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_cyanSigner","type":"address"},{"internalType":"address","name":"_cyanSuperAdmin","type":"address"},{"internalType":"address","name":"_walletFactory","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"items","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"contractAddress","type":"address"},{"internalType":"address","name":"cyanVaultAddress","type":"address"},{"internalType":"uint8","name":"itemType","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"uint256[2]","name":"apePlanIds","type":"uint256[2]"},{"internalType":"uint256","name":"estimatedValue","type":"uint256"}],"name":"liquidate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"bool","name":"isEarlyPayment","type":"bool"}],"name":"pay","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"paymentPlan","outputs":[{"components":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint32","name":"downPaymentPercent","type":"uint32"},{"internalType":"uint32","name":"interestRate","type":"uint32"},{"internalType":"uint32","name":"serviceFeeRate","type":"uint32"},{"internalType":"uint32","name":"term","type":"uint32"},{"internalType":"uint8","name":"totalNumberOfPayments","type":"uint8"},{"internalType":"uint8","name":"counterPaidPayments","type":"uint8"},{"internalType":"uint8","name":"autoRepayStatus","type":"uint8"}],"internalType":"struct Plan","name":"plan","type":"tuple"},{"internalType":"uint256","name":"createdDate","type":"uint256"},{"internalType":"address","name":"cyanWalletAddress","type":"address"},{"internalType":"enum PaymentPlanStatus","name":"status","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"}],"name":"rejectBNPL","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"uint256","name":"penaltyAmount","type":"uint256"},{"internalType":"uint256","name":"signatureExpiryDate","type":"uint256"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"revive","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"},{"internalType":"uint8","name":"autoRepayStatus","type":"uint8"}],"name":"setAutoRepayStatus","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"planId","type":"uint256"}],"name":"triggerAutoRepay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_cyanSigner","type":"address"}],"name":"updateCyanSignerAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"factory","type":"address"}],"name":"updateWalletFactoryAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

60806040523480156200001157600080fd5b506200001c62000022565b620000e4565b600054610100900460ff16156200008f5760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff9081161015620000e2576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b6155be80620000f46000396000f3fe6080604052600436106101dc5760003560e01c806374d807be11610102578063b2079fa311610095578063d2a47a7011610064578063d2a47a70146106ba578063d547741f146106da578063e249d277146106fa578063ff7885331461074257600080fd5b8063b2079fa3146105ae578063bfb231d2146105db578063c0c4c8ff1461066d578063c0c53b8b1461069a57600080fd5b80639e102b82116100d15780639e102b821461052e5780639ee6ec1d1461054e578063a217fddf14610561578063aac044fb1461057657600080fd5b806374d807be146103c957806380fe5a6d146103e957806391d14854146104c8578063979335051461050e57600080fd5b80632f2ff15d1161017a5780633f77cfa0116101495780633f77cfa0146103635780634f3df7a51461038357806357bed5d41461039657806373c75441146103b657600080fd5b80632f2ff15d146102e357806330be54361461030357806331d6b0651461032357806336568abe1461034357600080fd5b806323c4b449116101b657806323c4b44914610252578063248a9ca3146102725780632acf4c40146102b05780632b09dd0f146102c357600080fd5b806301ffc9a7146101e85780630f6521291461021d578063161c1c351461023257600080fd5b366101e357005b600080fd5b3480156101f457600080fd5b506102086102033660046144eb565b610762565b60405190151581526020015b60405180910390f35b61023061022b3660046145da565b610799565b005b34801561023e57600080fd5b5061023061024d366004614649565b610af5565b34801561025e57600080fd5b5061023061026d366004614677565b610b7e565b34801561027e57600080fd5b506102a261028d3660046146ad565b60009081526065602052604090206001015490565b604051908152602001610214565b6102306102be3660046146f1565b610efc565b3480156102cf57600080fd5b506102306102de366004614649565b61118d565b3480156102ef57600080fd5b506102306102fe366004614772565b61120a565b34801561030f57600080fd5b5061023061031e3660046147a2565b61122f565b34801561032f57600080fd5b5061023061033e366004614817565b61147e565b34801561034f57600080fd5b5061023061035e366004614772565b6114a6565b34801561036f57600080fd5b5061023061037e3660046148ae565b611533565b610230610391366004614817565b6115b6565b3480156103a257600080fd5b506102306103b13660046146ad565b61198e565b6102306103c43660046146ad565b611ca8565b3480156103d557600080fd5b506102306103e43660046147a2565b611f2d565b3480156103f557600080fd5b506104b86104043660046146ad565b60ca6020908152600091825260409182902082516101008101845281548152600182015463ffffffff808216948301949094526401000000008104841694820194909452600160401b840483166060820152600160601b8404909216608083015260ff600160801b8404811660a0840152600160881b8404811660c0840152600160901b909304831660e08301526002810154600390910154919290916001600160a01b03811691600160a01b9091041684565b60405161021494939291906148fd565b3480156104d457600080fd5b506102086104e3366004614772565b60009182526065602090815260408084206001600160a01b0393909316845291905290205460ff1690565b34801561051a57600080fd5b50610230610529366004614649565b6120cd565b34801561053a57600080fd5b5061023061054936600461499c565b61214a565b61023061055c366004614a70565b612248565b34801561056d57600080fd5b506102a2600081565b34801561058257600080fd5b506105966105913660046146ad565b6124ce565b6040516001600160a01b039091168152602001610214565b3480156105ba57600080fd5b506105ce6105c93660046146ad565b6124f2565b6040516102149190614a95565b3480156105e757600080fd5b506106366105f63660046146ad565b60c9602052600090815260409020805460018201546002830154600390930154919290916001600160a01b0391821691811690600160a01b900460ff1685565b6040805195865260208601949094526001600160a01b039283169385019390935216606083015260ff16608082015260a001610214565b34801561067957600080fd5b506102a2610688366004614649565b60cb6020526000908152604090205481565b3480156106a657600080fd5b506102306106b5366004614aa3565b6125e6565b3480156106c657600080fd5b506102306106d5366004614aee565b612800565b3480156106e657600080fd5b506102306106f5366004614772565b61290c565b34801561070657600080fd5b5061071a610715366004614a70565b612931565b604080519586526020860194909452928401919091526060830152608082015260a001610214565b34801561074e57600080fd5b5061023061075d366004614817565b612a89565b60006001600160e01b03198216637965db0b60e01b148061079357506301ffc9a760e01b6001600160e01b03198316145b92915050565b6107a1612aa0565b600084815260ca60205260409020428310156107d05760405163f4230a5760e01b815260040160405180910390fd5b600181015460cc5460405163b1147ac160e01b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d69263b1147ac19261082c928a928a928a924692600160881b900460ff16916001600160a01b0316908b90600401614ba2565b60006040518083038186803b15801561084457600080fd5b505af4158015610858573d6000803e3d6000fd5b5050505061086585612af9565b60008060008060006108788a6000612931565b60018b01549499509297509095509350915042906108a390600160601b900463ffffffff1683614c08565b116108c15760405163f4230a5760e01b815260040160405180910390fd5b60006108cc8b6124ce565b90506108e2816108dc8c86614c08565b33612b59565b6001600160a01b038116600090815260cb60205260408120805486929061090a908490614c08565b909155505060008b815260c9602052604090206003015461093e906001600160a01b0316876109398d89614c08565b612c96565b60018088015460ff600160801b820481169261096492600160881b900490911690614c1b565b60ff1603610a6f5761097587612e6c565b60038781015460008d815260c960205260408082209051631f9f5fb560e21b81526001600160a01b0393841660048201528154602482015260018201546044820152600282015484166064820152930154918216608484015260a09190911c60ff1660a483015260c482015273495279f278fe3d44b92c320d84397559271d1fb590637e7d7ed49060e40160006040518083038186803b158015610a1857600080fd5b505af4158015610a2c573d6000803e3d6000fd5b505050508a7fcf2c54121f1f969a5f1ef034280738334cc37362016fa191d67eadec18ab04138b604051610a6291815260200190565b60405180910390a2610ade565b600187018054601190610a8b90600160881b900460ff16614c34565b91906101000a81548160ff021916908360ff1602179055508a7f874dd68f5d4b9530b4d57f516b7830957282deaebe992c9bae94dcd244c8eef28b604051610ad591815260200190565b60405180910390a25b50505050505050610aef6001609755565b50505050565b610afd612aa0565b6000610b0881612eec565b6001600160a01b038216600090815260cb6020526040902054610b2c838233612ef6565b6001600160a01b038316600081815260cb6020526040808220829055518392917f772e576b9fc0ca150ba5f438bab3fae809babf5bc72c5fe5d963e4f126c886a691a35050610b7b6001609755565b50565b610b86612aa0565b80600003610ba75760405163162908e360e11b815260040160405180910390fd5b600083815260ca6020908152604080832060c9835292819020815160a0810183528154815260018201549381019390935260028101546001600160a01b03908116928401929092526003015490811660608301819052600160a01b90910460ff1660808301523303610c2157610c1c85612f8d565b610c79565b3360009081527f20ed6bc75ca2f07d3f30c9ffd0b7d42ad30542806a6d5ce8b8b71f2228b0a3da602052604090205460ff16610c7057604051636edaef2f60e11b815260040160405180910390fd5b610c7985612af9565b600382015460408083015160208401519151633939a00160e11b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d693637273400293610ccb936001600160a01b03909216928a90600401614c53565b60006040518083038186803b158015610ce357600080fd5b505af4158015610cf7573d6000803e3d6000fd5b505050506000610d08866001612931565b5050506003850154604051631f9f5fb560e21b815292935073495279f278fe3d44b92c320d84397559271d1fb592637e7d7ed49250610d58916001600160a01b0316908690600090600401614c83565b60006040518083038186803b158015610d7057600080fd5b505af4158015610d84573d6000803e3d6000fd5b505050600384015460608401516040516305bd511560e11b815273495279f278fe3d44b92c320d84397559271d1fb59350630b7aa22a92610dd5926001600160a01b03909116918790600401614ced565b60006040518083038186803b158015610ded57600080fd5b505af4158015610e01573d6000803e3d6000fd5b505050506003830154610e1d90600160a01b900460ff16612fbe565b610e2857600a610e2b565b60065b60038401805460ff60a01b1916600160a01b83600a811115610e4f57610e4f6148d3565b02179055506060820151604051630f78acab60e31b815260048101839052602481018690526001600160a01b0390911690637bc5655890604401600060405180830381600087803b158015610ea357600080fd5b505af1158015610eb7573d6000803e3d6000fd5b505050508084877f72fe82cd21a1a15fa4aa0b197f1db5ec0c7dbea458a241c0a193b615555ea09760405160405180910390a4505050610ef76001609755565b505050565b610f04612aa0565b610f0d83612f8d565b600083815260ca602052604081206003810154909190610f379033906001600160a01b0316613081565b600086815260c96020908152604091829020825160a08101845281548152600182015481840181905260028301546001600160a01b03908116958301959095526003909201549384166060820152600160a01b90930460ff1660808401529293509091908a0135148015610fcf5750610fb660608a0160408b01614649565b6001600160a01b031681604001516001600160a01b0316145b8015610ff35750610fe660a08a0160808b01614d4f565b60ff16816080015160ff16145b8015611000575080518935145b61101d576040516327b3518960e11b815260040160405180910390fd5b600061103761103260808c0160608d01614649565b6130db565b9050611042876124ce565b6001600160a01b0316816001600160a01b03161461107357604051631eb3268560e31b815260040160405180910390fd5b6000806000806110848b6001612931565b50935093509350935061109c8e8e8e60028e8e61313f565b8c358111156110b9576110b4856108dc8f3584614d6c565b6110db565b60006110c6828f35614d6c565b905080156110d9576110d986828a612ef6565b505b6001600160a01b038516600090815260cb602052604081208054849290611103908490614c08565b90915550506060860151611118908585612c96565b600188015461113a9060ff600160881b8204811691600160801b900416614d7f565b60ff168b7f90bfd14bfda88bd1c0f165030b0d00bbd67c021452e46d63b32770f43bc1e8c860405160405180910390a361117388612e6c565b50505050505050506111856001609755565b505050505050565b600061119881612eec565b6001600160a01b0382166111bf5760405163e6c4247b60e01b815260040160405180910390fd5b60cd80546001600160a01b0319166001600160a01b0384169081179091556040517fe62d9ecc2f46536d69df8cf1ba196250488dc869eadabc42466d72ee898716ce90600090a25050565b60008281526065602052604090206001015461122581612eec565b610ef7838361358e565b611237612aa0565b7f321163fcbab3bac890d4fb1f03b22c5c6bd95bc472ee55584937974a1db0335661126181612eec565b60005b8281101561146e57600084848381811061128057611280614d98565b60209081029290920135600081815260ca8452604080822060c98652818320825160a0810184528154815260018201549781019790975260028101546001600160a01b03908116888501526003909101549081166060880152600160a01b900460ff16608087015290516359bf732f60e01b815292955093925090733d7bc1c3cc39e41e8be4711898075bc21c22a9d6906359bf732f906113279086908690600401614dae565b602060405180830381865af4158015611344573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113689190614dff565b9050600061137983606001516130db565b6001600160a01b038116600090815260cb60205260408120805492935084929091906113a6908490614c08565b90915550506003840154604051637c68c57160e11b815273495279f278fe3d44b92c320d84397559271d1fb59163f8d18ae2916113f59133916001600160a01b03909116908890600401614ced565b60006040518083038186803b15801561140d57600080fd5b505af4158015611421573d6000803e3d6000fd5b506002925061142e915050565b60405186907ed0e48b2e978cce35d3b88d090f3361dcffdf8a233ebcad9d572adadf3152c190600090a350505050508061146790614e18565b9050611264565b505061147a6001609755565b5050565b611486612aa0565b6114958585856001868661313f565b61149f6001609755565b5050505050565b6001600160a01b03811633146115295760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201527f20726f6c657320666f722073656c66000000000000000000000000000000000060648201526084015b60405180910390fd5b61147a8282613630565b600082815260ca60205260409020600301546115599033906001600160a01b0316613081565b50600082815260ca6020526040808220600101805460ff60901b1916600160901b60ff8616908102919091179091559051909184917f719e7861647821315c8e1bcf126e3affc0d31c1f250cabdc2904054fff3515f49190a35050565b6115be612aa0565b60405163a668c9af60e01b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d69063a668c9af906115fc90600190899089908890600401614f40565b60006040518083038186803b15801561161457600080fd5b505af4158015611628573d6000803e3d6000fd5b505060cc54604051636f82e3ed60e11b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d6935063df05c7da925061167c91899189918991899146916001600160a01b03909116908a90600401614f74565b60006040518083038186803b15801561169457600080fd5b505af41580156116a8573d6000803e3d6000fd5b505050600084815260ca6020526040902060010154600160801b900460ff161590506116e7576040516368ac339960e01b815260040160405180910390fd5b6000806117016116fc36889003880188614fd6565b6136b3565b509250509150600061171f8860600160208101906110329190614649565b9050611735818385604001516108dc9190614c08565b60cd54604051635035507560e11b81523360048201526000916001600160a01b03169063a06aa0ea906024016020604051808303816000875af1158015611780573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117a49190615099565b90506040518060800160405280898036038101906117c29190614fd6565b81524260208201526001600160a01b038316604082015260600160009052600088815260ca60209081526040918290208351805182558083015160018301805483870151606080860151608087015160a088015160c089015160e09099015160ff908116600160901b0260ff60901b199a8216600160881b0260ff60881b1992909316600160801b029190911661ffff60801b1963ffffffff948516600160601b0263ffffffff60601b19968616600160401b02969096166fffffffffffffffff0000000000000000199886166401000000000267ffffffffffffffff19909a1695909b16949094179790971795909516979097179190911716929092179390931793909316919091179055918401516002820155918301516003830180546001600160a01b039092166001600160a01b03198316811782559285015192909174ffffffffffffffffffffffffffffffffffffffffff191617600160a01b83600a811115611932576119326148d3565b02179055505050600087815260c960205260409020899061195382826150b6565b505060405187907feaa1e7f59197f03e5abd233e86f8550ab3dbc2f40d353eeac8be6607517e5e0e90600090a25050505061149f6001609755565b7f3476efba29c1dd189ede426d6e97aa39c0683187a42f9eec0c97d2d56eb0a4bc6119b881612eec565b600082815260ca60205260409020600190810154600160901b900460ff169081148015906119ea57508060ff16600214155b15611a085760405163816fa01960e01b815260040160405180910390fd5b611a1183612f8d565b600080611a1f856000612931565b94509450505050426201518082611a369190614d6c565b1115611a5557604051638c1b949360e01b815260040160405180910390fd5b600085815260ca60205260409020600301546001600160a01b031660ff8416600203611c1e576000611a8682613808565b90506000611a93886124ce565b60405163699f200f60e01b81526b10d6505397d0d3d39115525560a21b600482015290915060009073cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015611af7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b1b9190615099565b90506001600160a01b038216611ba85760405163699f200f60e01b8152630ae8aa8960e31b600482015273cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015611b81573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ba59190615099565b91505b60405163368fa33960e21b81526001600160a01b038481166004830152858116602483015283811660448301526064820188905282169063da3e8ce490608401600060405180830381600087803b158015611c0257600080fd5b505af1158015611c16573d6000803e3d6000fd5b505050505050505b60405163174b554760e11b81526001600160a01b0382166004820152602481018790526044810184905260ff8516606482015273495279f278fe3d44b92c320d84397559271d1fb590632e96aa8e9060840160006040518083038186803b158015611c8857600080fd5b505af4158015611c9c573d6000803e3d6000fd5b50505050505050505050565b611cb0612aa0565b7f321163fcbab3bac890d4fb1f03b22c5c6bd95bc472ee55584937974a1db03356611cda81612eec565b600082815260ca60205260409020600180820154600160881b900460ff1614611d1657604051630201a46f60e31b815260040160405180910390fd5b60006003820154600160a01b900460ff16600a811115611d3857611d386148d3565b14158015611d66575060016003820154600160a01b900460ff16600a811115611d6357611d636148d3565b14155b15611d845760405163e82a532960e01b815260040160405180910390fd5b604080516101008101825282548152600183015463ffffffff80821660208401526401000000008204811693830193909352600160401b810483166060830152600160601b8104909216608082015260ff600160801b8304811660a0830152600160881b8304811660c0830152600160901b90920490911660e08201526000908190611e0f906136b3565b5092505091506000611e20866124ce565b6003850154909150600090611e3d906001600160a01b0316613808565b9050611e5982856040015185611e539190614c08565b83612ef6565b60016003860154600160a01b900460ff16600a811115611e7b57611e7b6148d3565b03611ebc578454611e8e90839033612b59565b600087815260c960205260408120600301548654611eb7926001600160a01b0390921691612c96565b611edb565b3415611edb5760405163162908e360e11b815260040160405180910390fd5b60038501805460ff60a01b1916600160a21b17905560405160049088907ed0e48b2e978cce35d3b88d090f3361dcffdf8a233ebcad9d572adadf3152c190600090a3505050505050610b7b6001609755565b611f35612aa0565b7f321163fcbab3bac890d4fb1f03b22c5c6bd95bc472ee55584937974a1db03356611f5f81612eec565b60005b8281101561146e576000848483818110611f7e57611f7e614d98565b60209081029290920135600081815260ca8452604080822060c990955290819020600301548454915163a2fb342d60e01b815233600482015260248101929092529194506001600160a01b03909116915063a2fb342d90604401600060405180830381600087803b158015611ff257600080fd5b505af1158015612006573d6000803e3d6000fd5b50505050600181810154600160881b900460ff161461203857604051630201a46f60e31b815260040160405180910390fd5b60006003820154600160a01b900460ff16600a81111561205a5761205a6148d3565b146120785760405163e82a532960e01b815260040160405180910390fd5b60038101805460ff60a01b1916600160a01b17905560405160019083907ed0e48b2e978cce35d3b88d090f3361dcffdf8a233ebcad9d572adadf3152c190600090a35050806120c690614e18565b9050611f62565b60006120d881612eec565b6001600160a01b0382166120ff5760405163e6c4247b60e01b815260040160405180910390fd5b60cc80546001600160a01b0319166001600160a01b0384169081179091556040517fb600274ef5d11bda880beece19f867f60804daa64e9abecaf8f54ba2d2a73c1190600090a25050565b612152612aa0565b4282101561217357604051638baa579f60e01b815260040160405180910390fd5b60cc5460405163e13fe1ad60e01b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d69163e13fe1ad916121c3918b918a918a918a918a9146916001600160a01b0316908b90600401615146565b60006040518083038186803b1580156121db57600080fd5b505af41580156121ef573d6000803e3d6000fd5b5050505061223587878787878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509250613853915050565b61223f6001609755565b50505050505050565b612250612aa0565b61225982612f8d565b600082815260ca60205260408120600181015490919061228c9060ff600160881b8204811691600160801b900416614d7f565b90506000838061229f57508160ff166001145b90506000806000806122b18986612931565b50935093509350935060006122c58a6124ce565b90506122d2818333612b59565b6001600160a01b038116600090815260cb6020526040812080548592906122fa908490614c08565b909155505060008a815260c96020526040902060030154612325906001600160a01b03168686612c96565b851561245a5761233488612e6c565b60038881015460008c815260c960205260408082209051631f9f5fb560e21b81526001600160a01b0393841660048201528154602482015260018201546044820152600282015484166064820152930154918216608484015260a09190911c60ff1660a483015260c482015273495279f278fe3d44b92c320d84397559271d1fb590637e7d7ed49060e40160006040518083038186803b1580156123d757600080fd5b505af41580156123eb573d6000803e3d6000fd5b50505050881561242a5760405160ff8816908b907f90bfd14bfda88bd1c0f165030b0d00bbd67c021452e46d63b32770f43bc1e8c890600090a36124bc565b6040518a907fdfd517ed69f8a0a57d49fe494e4864fac3cfe3585c14c0bfddf39f72463ec3fd90600090a26124bc565b60018801805460119061247690600160881b900460ff16614c34565b91906101000a81548160ff021916908360ff160217905550897f581d416ae9dff30c9305c2b35cb09ed5991897ab97804db29ccf92678e95316060405160405180910390a25b505050505050505061147a6001609755565b600081815260c96020526040812060030154610793906001600160a01b03166130db565b60006002600083815260ca6020526040902060030154600160a01b900460ff16600a811115612523576125236148d3565b148061255b57506007600083815260ca6020526040902060030154600160a01b900460ff16600a811115612559576125596148d3565b145b156125c657600061256d836000612931565b9450505042831091505080156125c3576002600085815260ca6020526040902060030154600160a01b900460ff16600a8111156125ac576125ac6148d3565b146125b85760086125bb565b60035b949350505050565b50505b50600090815260ca6020526040902060030154600160a01b900460ff1690565b600054610100900460ff16158080156126065750600054600160ff909116105b806126205750303b158015612620575060005460ff166001145b6126925760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a65640000000000000000000000000000000000006064820152608401611520565b6000805460ff1916600117905580156126b5576000805461ff0019166101001790555b6001600160a01b03841615806126d257506001600160a01b038316155b806126e457506001600160a01b038216155b156127025760405163e6c4247b60e01b815260040160405180910390fd5b60cc80546001600160a01b038087166001600160a01b03199283161790925560cd80549285169290911691909117905561273d600084613f1f565b612745613f29565b61274d613f96565b6040516001600160a01b038516907fb600274ef5d11bda880beece19f867f60804daa64e9abecaf8f54ba2d2a73c1190600090a26040516001600160a01b038316907fe62d9ecc2f46536d69df8cf1ba196250488dc869eadabc42466d72ee898716ce90600090a28015610aef576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a150505050565b612808612aa0565b4282101561282957604051638baa579f60e01b815260040160405180910390fd5b6040516302edd95160e11b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d6906305dbb2a29061286a9089908890879046908a9089906004016151ba565b60006040518083038186803b15801561288257600080fd5b505af4158015612896573d6000803e3d6000fd5b505050506001600160a01b03831660009081527f20ed6bc75ca2f07d3f30c9ffd0b7d42ad30542806a6d5ce8b8b71f2228b0a3da602052604090205460ff166128f257604051634828265b60e11b815260040160405180910390fd5b60606129018787878488613853565b506111856001609755565b60008281526065602052604090206001015461292781612eec565b610ef78383613630565b600082815260ca602090815260408083208151610100810183528154815260019091015463ffffffff808216948301949094526401000000008104841692820192909252600160401b820483166060820152600160601b8204909216608083015260ff600160801b8204811660a08401819052600160881b8304821660c0850152600160901b9092041660e0830152829182918291829182036129e75760405163467136bd60e11b815260040160405180910390fd5b600088815260ca60205260409081902060020154905163c1ccd57960e01b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d69163c1ccd57991612a349185918c9190600401615200565b60a060405180830381865af4158015612a51573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a759190615284565b939c929b5090995097509095509350505050565b612a91612aa0565b6114958585856000868661313f565b600260975403612af25760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401611520565b6002609755565b6000612b04826124f2565b9050600381600a811115612b1a57612b1a6148d3565b14158015612b3b575060085b81600a811115612b3857612b386148d3565b14155b1561147a5760405163e82a532960e01b815260040160405180910390fd5b6001600160a01b038316612b8757348214610ef75760405163162908e360e11b815260040160405180910390fd5b3415612ba65760405163162908e360e11b815260040160405180910390fd5b60405163699f200f60e01b81526b10d6505397d0d3d39115525560a21b600482015273cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015612c04573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c289190615099565b60405163368fa33960e21b81526001600160a01b038381166004830152306024830152858116604483015260648201859052919091169063da3e8ce490608401600060405180830381600087803b158015612c8257600080fd5b505af115801561223f573d6000803e3d6000fd5b60008390506000816001600160a01b031663bfe0c27e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612cdb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cff9190615099565b90506001600160a01b038116612d84576001600160a01b03821663643840f2612d288587614c08565b6040516001600160e01b031960e084901b16815260048101889052602481018790526044016000604051808303818588803b158015612d6657600080fd5b505af1158015612d7a573d6000803e3d6000fd5b505050505061149f565b806001600160a01b03811663095ea7b387612d9f8789614c08565b6040516001600160e01b031960e085901b1681526001600160a01b03909216600483015260248201526044016020604051808303816000875af1158015612dea573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e0e91906152c4565b5060405163321c207960e11b815260048101869052602481018590526001600160a01b0384169063643840f290604401600060405180830381600087803b158015612e5857600080fd5b505af1158015611c9c573d6000803e3d6000fd5b60018101805460ff60881b198116600160801b90910460ff908116600160881b02919091179091556003820154612eab91600160a01b90910416612fbe565b612eb6576009612eb9565b60055b60038201805460ff60a01b1916600160a01b83600a811115612edd57612edd6148d3565b021790555050565b6001609755565b610b7b8133614009565b6001600160a01b038316612f78576000816001600160a01b03168360405160006040518083038185875af1925050503d8060008114612f51576040519150601f19603f3d011682016040523d82523d6000602084013e612f56565b606091505b5050905080610aef57604051630db2c7f160e31b815260040160405180910390fd5b82610aef6001600160a01b038216838561407e565b6000612f98826124f2565b9050600281600a811115612fae57612fae6148d3565b14158015612b3b57506007612b26565b60008082600a811115612fd357612fd36148d3565b1480612ff05750600182600a811115612fee57612fee6148d3565b145b8061300c5750600282600a81111561300a5761300a6148d3565b145b806130285750600382600a811115613026576130266148d3565b145b806130445750600482600a811115613042576130426148d3565b145b806130605750600582600a81111561305e5761305e6148d3565b145b806107935750600682600a81111561307a5761307a6148d3565b1492915050565b6000826001600160a01b03808216908416146130d4576130a083613808565b9050806001600160a01b0316846001600160a01b0316146130d457604051636edaef2f60e11b815260040160405180910390fd5b9392505050565b6000816001600160a01b031663bfe0c27e6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561311b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107939190615099565b600084815260ca6020526040902060010154600160801b900460ff1615613179576040516368ac339960e01b815260040160405180910390fd5b60cd54604051635035507560e11b81523360048201526000916001600160a01b03169063a06aa0ea906024016020604051808303816000875af11580156131c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131e89190615099565b9050336001600160a01b0382168190036132085761320582613808565b90505b60cc546040516313f3090b60e01b8152600091733d7bc1c3cc39e41e8be4711898075bc21c22a9d6916313f3090b9161325d918d918d918d918d918d918b918d916001600160a01b0316908f906004016152f1565b602060405180830381865af415801561327a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061329e91906152c4565b905060028660028111156132b4576132b46148d3565b1461339c57801561332f57604051637c68c57160e11b815273495279f278fe3d44b92c320d84397559271d1fb59063f8d18ae2906132fa90859087908e90600401615360565b60006040518083038186803b15801561331257600080fd5b505af4158015613326573d6000803e3d6000fd5b5050505061339c565b604051631f9f5fb560e21b815273495279f278fe3d44b92c320d84397559271d1fb590637e7d7ed49061336b9086908d90600190600401615385565b60006040518083038186803b15801561338357600080fd5b505af4158015613397573d6000803e3d6000fd5b505050505b600087815260c96020526040902089906133b682826150b6565b50506040805160808101909152806133d3368b90038b018b614fd6565b81524260208201526001600160a01b038516604082015260600160079052600088815260ca60209081526040918290208351805182558083015160018301805483870151606080860151608087015160a088015160c089015160e09099015160ff908116600160901b0260ff60901b199a8216600160881b0260ff60881b1992909316600160801b029190911661ffff60801b1963ffffffff948516600160601b0263ffffffff60601b19968616600160401b02969096166fffffffffffffffff0000000000000000199886166401000000000267ffffffffffffffff19909a1695909b16949094179790971795909516979097179190911716929092179390931793909316919091179055918401516002820155918301516003830180546001600160a01b039092166001600160a01b03198316811782559285015192909174ffffffffffffffffffffffffffffffffffffffffff191617600160a01b83600a811115613543576135436148d3565b0217905550905050867fe3c5a8fbdc814f563f15d04282af0e83465c96f99634799decb45e715d5908d18760405161357b91906153a2565b60405180910390a2505050505050505050565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff1661147a5760008281526065602090815260408083206001600160a01b03851684529091529020805460ff191660011790556135ec3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff161561147a5760008281526065602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6136d760405180606001604052806000815260200160008152602001600081525090565b6136fb60405180606001604052806000815260200160008152602001600081525090565b6000806000856020015163ffffffff161161371757600061371a565b60015b8560a001516137299190614d7f565b9050612710856020015163ffffffff16866000015161374891906153b0565b61375291906153c7565b8551909250613762908390614d6c565b80845260408601516127109161377e9163ffffffff16906153b0565b61378891906153c7565b602084015260608501518551612710916137aa9163ffffffff909116906153b0565b6137b491906153c7565b604084015282516137c99060ff8316906153c7565b845260208301516137de9060ff8316906153c7565b602085015260a085015160408401516137fa9160ff16906153c7565b604085015292949193509190565b60cd5460405163966708a560e01b81526001600160a01b038381166004830152600092169063966708a590602401602060405180830381865afa15801561311b573d6000803e3d6000fd5b600085815260ca6020908152604080832060c9835292819020815160a0810183528154815260018201549381019390935260028101546001600160a01b0390811692840192909252600301549081166060830152600160a01b900460ff1660808201526138bf87612f8d565b60006138ca886124ce565b90506000806000806138dd8c6001612931565b50935093509350935085606001516001600160a01b0316336001600160a01b03161461392257600387015461391c9033906001600160a01b0316613081565b50613943565b898111156139435760405163162908e360e11b815260040160405180910390fd5b733d7bc1c3cc39e41e8be4711898075bc21c22a9d663727340028860030160009054906101000a90046001600160a01b0316886040015189602001518f6040518563ffffffff1660e01b815260040161399f9493929190614c53565b60006040518083038186803b1580156139b757600080fd5b505af41580156139cb573d6000803e3d6000fd5b505050506003870154604051631f9f5fb560e21b815273495279f278fe3d44b92c320d84397559271d1fb591637e7d7ed491613a18916001600160a01b0316908a90600090600401614c83565b60006040518083038186803b158015613a3057600080fd5b505af4158015613a44573d6000803e3d6000fd5b5050506001600160a01b0389169050613b56576001600160a01b03851615613a7f57604051631eb3268560e31b815260040160405180910390fd5b8660030160009054906101000a90046001600160a01b03166001600160a01b031663a93b06c86373f8e32860e01b838d8a8e604051602401613ac494939291906153e9565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b03199485161790525160e084901b9092168252613b0991600401615453565b6000604051808303816000875af1158015613b28573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052613b509190810190615466565b50613e20565b60405163699f200f60e01b81526b10d6505397d0d3d39115525560a21b600482015273cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015613bb4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613bd89190615099565b60038801546001600160a01b039182169163da3e8ce4918b9190811690891615613c025788613c7c565b60405163699f200f60e01b8152630ae8aa8960e31b600482015273cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015613c58573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c7c9190615099565b60405160e085901b6001600160e01b03191681526001600160a01b03938416600482015291831660248301529091166044820152606481018d9052608401600060405180830381600087803b158015613cd457600080fd5b505af1158015613ce8573d6000803e3d6000fd5b50505050600387015460408051602481018490526001600160a01b0388811660448084019190915283518084039091018152606490920183526020820180516001600160e01b0316631ae9c0eb60e11b179052915163152760d960e31b8152919092169163a93b06c891613d5f9190600401615453565b6000604051808303816000875af1158015613d7e573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052613da69190810190615466565b5060038701546040516305bd511560e11b815273495279f278fe3d44b92c320d84397559271d1fb591630b7aa22a91613def916001600160a01b0316908c908b90600401614ced565b60006040518083038186803b158015613e0757600080fd5b505af4158015613e1b573d6000803e3d6000fd5b505050505b600387015460405163a7737e3160e01b81526001600160a01b038088166004830152909116602482015260448101829052733d7bc1c3cc39e41e8be4711898075bc21c22a9d69063a7737e319060640160006040518083038186803b158015613e8857600080fd5b505af4158015613e9c573d6000803e3d6000fd5b505050506001600160a01b038516600090815260cb602052604081208054849290613ec8908490614c08565b90915550506060860151613edd908585612c96565b613ee687612e6c565b6040518c907ffa77073553b7085fac8c378daa25f5d003ce42427f66d5514834f634123e1c9e90600090a2505050505050505050505050565b61147a828261358e565b600054610100900460ff16613f945760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401611520565b565b600054610100900460ff166140015760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401611520565b613f946140d0565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff1661147a5761403c8161413b565b61404783602061414d565b6040516020016140589291906154d4565b60408051601f198184030181529082905262461bcd60e51b825261152091600401615453565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610ef79084906142f6565b600054610100900460ff16612ee55760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401611520565b60606107936001600160a01b03831660145b6060600061415c8360026153b0565b614167906002614c08565b67ffffffffffffffff81111561417f5761417f614515565b6040519080825280601f01601f1916602001820160405280156141a9576020820181803683370190505b509050600360fc1b816000815181106141c4576141c4614d98565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106141f3576141f3614d98565b60200101906001600160f81b031916908160001a90535060006142178460026153b0565b614222906001614c08565b90505b60018111156142a7577f303132333435363738396162636465660000000000000000000000000000000085600f166010811061426357614263614d98565b1a60f81b82828151811061427957614279614d98565b60200101906001600160f81b031916908160001a90535060049490941c936142a081615555565b9050614225565b5083156130d45760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401611520565b600061434b826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166143c89092919063ffffffff16565b805190915015610ef7578080602001905181019061436991906152c4565b610ef75760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401611520565b60606125bb848460008585600080866001600160a01b031685876040516143ef919061556c565b60006040518083038185875af1925050503d806000811461442c576040519150601f19603f3d011682016040523d82523d6000602084013e614431565b606091505b50915091506144428783838761444d565b979650505050505050565b606083156144bc5782516000036144b5576001600160a01b0385163b6144b55760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401611520565b50816125bb565b6125bb83838151156144d15781518083602001fd5b8060405162461bcd60e51b81526004016115209190615453565b6000602082840312156144fd57600080fd5b81356001600160e01b0319811681146130d457600080fd5b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff8111828210171561455457614554614515565b604052919050565b600067ffffffffffffffff82111561457657614576614515565b50601f01601f191660200190565b600082601f83011261459557600080fd5b81356145a86145a38261455c565b61452b565b8181528460208386010111156145bd57600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080608085870312156145f057600080fd5b843593506020850135925060408501359150606085013567ffffffffffffffff81111561461c57600080fd5b61462887828801614584565b91505092959194509250565b6001600160a01b0381168114610b7b57600080fd5b60006020828403121561465b57600080fd5b81356130d481614634565b806040810183101561079357600080fd5b60008060006080848603121561468c57600080fd5b8335925061469d8560208601614666565b9150606084013590509250925092565b6000602082840312156146bf57600080fd5b5035919050565b600060a082840312156146d857600080fd5b50919050565b600061010082840312156146d857600080fd5b600080600080600080610220878903121561470b57600080fd5b61471588886146c6565b95506147248860a089016146de565b94506101a087013593506101c087013592506101e0870135915061020087013567ffffffffffffffff81111561475957600080fd5b61476589828a01614584565b9150509295509295509295565b6000806040838503121561478557600080fd5b82359150602083013561479781614634565b809150509250929050565b600080602083850312156147b557600080fd5b823567ffffffffffffffff808211156147cd57600080fd5b818501915085601f8301126147e157600080fd5b8135818111156147f057600080fd5b8660208260051b850101111561480557600080fd5b60209290920196919550909350505050565b6000806000806000610200868803121561483057600080fd5b61483a87876146c6565b94506148498760a088016146de565b93506101a086013592506101c086013591506101e086013567ffffffffffffffff81111561487657600080fd5b61488288828901614584565b9150509295509295909350565b60ff81168114610b7b57600080fd5b80356148a98161488f565b919050565b600080604083850312156148c157600080fd5b8235915060208301356147978161488f565b634e487b7160e01b600052602160045260246000fd5b600b81106148f9576148f96148d3565b9052565b610160810161496e828780518252602081015163ffffffff8082166020850152806040840151166040850152806060840151166060850152806080840151166080850152505060ff60a08201511660a083015260ff60c08201511660c083015260ff60e08201511660e08301525050565b846101008301526001600160a01b0384166101208301526149936101408301846148e9565b95945050505050565b600080600080600080600060e0888a0312156149b757600080fd5b873596506149c88960208a01614666565b955060608801359450608088013567ffffffffffffffff808211156149ec57600080fd5b818a0191508a601f830112614a0057600080fd5b813581811115614a0f57600080fd5b8b6020828501011115614a2157600080fd5b6020830196508095505060a08a0135935060c08a0135915080821115614a4657600080fd5b50614a538a828b01614584565b91505092959891949750929550565b8015158114610b7b57600080fd5b60008060408385031215614a8357600080fd5b82359150602083013561479781614a62565b6020810161079382846148e9565b600080600060608486031215614ab857600080fd5b8335614ac381614634565b92506020840135614ad381614634565b91506040840135614ae381614634565b809150509250925092565b60008060008060008060e08789031215614b0757600080fd5b86359550614b188860208901614666565b9450606087013593506080870135614b2f81614634565b925060a0870135915060c087013567ffffffffffffffff81111561475957600080fd5b60005b83811015614b6d578181015183820152602001614b55565b50506000910152565b60008151808452614b8e816020860160208601614b52565b601f01601f19169290920160200192915050565b87815286602082015285604082015284606082015260ff841660808201526001600160a01b03831660a082015260e060c08201526000614be560e0830184614b76565b9998505050505050505050565b634e487b7160e01b600052601160045260246000fd5b8082018082111561079357610793614bf2565b60ff818116838216019081111561079357610793614bf2565b600060ff821660ff8103614c4a57614c4a614bf2565b60010192915050565b6001600160a01b03858116825284166020820152604080820184905260a082019083606084013795945050505050565b6001600160a01b038416815260e08101614cdd6020830185805182526020810151602083015260408101516001600160a01b038082166040850152806060840151166060850152505060ff60808201511660808301525050565b82151560c0830152949350505050565b6001600160a01b0384811682528316602082015260e081016125bb6040830184805182526020810151602083015260408101516001600160a01b038082166040850152806060840151166060850152505060ff60808201511660808301525050565b600060208284031215614d6157600080fd5b81356130d48161488f565b8181038181111561079357610793614bf2565b60ff828116828216039081111561079357610793614bf2565b634e487b7160e01b600052603260045260246000fd5b82815260c081016130d46020830184805182526020810151602083015260408101516001600160a01b038082166040850152806060840151166060850152505060ff60808201511660808301525050565b600060208284031215614e1157600080fd5b5051919050565b600060018201614e2a57614e2a614bf2565b5060010190565b80358252602081013560208301526040810135614e4d81614634565b6001600160a01b039081166040840152606082013590614e6c82614634565b1660608301526080810135614e808161488f565b60ff81166080840152505050565b803563ffffffff811681146148a957600080fd5b80358252614eb260208201614e8e565b63ffffffff808216602085015280614ecc60408501614e8e565b16604085015280614edf60608501614e8e565b16606085015280614ef260808501614e8e565b166080850152505060a0810135614f088161488f565b60ff1660a083015260c0810135614f1e8161488f565b60ff1660c0830152614f3260e0820161489e565b60ff811660e0840152505050565b84151581526101e08101614f576020830186614e31565b614f6460c0830185614ea2565b826101c083015295945050505050565b6000610240614f83838b614e31565b614f9060a084018a614ea2565b876101a0840152866101c0840152856101e08401526001600160a01b03851661020084015280610220840152614fc881840185614b76565b9a9950505050505050505050565b6000610100808385031215614fea57600080fd5b6040519081019067ffffffffffffffff8211818310171561500d5761500d614515565b816040528335815261502160208501614e8e565b602082015261503260408501614e8e565b604082015261504360608501614e8e565b606082015261505460808501614e8e565b608082015260a084013591506150698261488f565b8160a082015261507b60c0850161489e565b60c082015261508c60e0850161489e565b60e0820152949350505050565b6000602082840312156150ab57600080fd5b81516130d481614634565b813581556020820135600182015560408201356150d281614634565b6002820180546001600160a01b0319166001600160a01b0383161790555060038101606083013561510281614634565b81546001600160a01b0319166001600160a01b03821617825550608083013561512a8161488f565b815460ff60a01b191660a09190911b60ff60a01b161790555050565b88815287602082015260e060408201528560e082015260006101008789828501376000818985010152601f19601f89011683018760608501528660808501526001600160a01b03861660a0850152818482030160c08501526151aa82820186614b76565b9c9b505050505050505050505050565b8681528560208201528460408201528360608201526001600160a01b038316608082015260c060a082015260006151f460c0830184614b76565b98975050505050505050565b6101408101615271828680518252602081015163ffffffff8082166020850152806040840151166040850152806060840151166060850152806080840151166080850152505060ff60a08201511660a083015260ff60c08201511660c083015260ff60e08201511660e08301525050565b9215156101008201526101200152919050565b600080600080600060a0868803121561529c57600080fd5b5050835160208501516040860151606087015160809097015192989197509594509092509050565b6000602082840312156152d657600080fd5b81516130d481614a62565b600381106148f9576148f96148d3565b6000610280615300838d614e31565b61530d60a084018c614ea2565b896101a08401526153226101c084018a6152e1565b876101e08401526001600160a01b0380881661020085015280871661022085015280861661024085015250806102608401526151aa81840185614b76565b6001600160a01b0384811682528316602082015260e081016125bb6040830184614e31565b6001600160a01b038416815260e08101614cdd6020830185614e31565b6020810161079382846152e1565b808202811582820484141761079357610793614bf2565b6000826153e457634e487b7160e01b600052601260045260246000fd5b500490565b60006101008683528560208401526154416040840186805182526020810151602083015260408101516001600160a01b038082166040850152806060840151166060850152505060ff60808201511660808301525050565b8060e084015261444281840185614b76565b6020815260006130d46020830184614b76565b60006020828403121561547857600080fd5b815167ffffffffffffffff81111561548f57600080fd5b8201601f810184136154a057600080fd5b80516154ae6145a38261455c565b8181528560208385010111156154c357600080fd5b614993826020830160208601614b52565b7f416363657373436f6e74726f6c3a206163636f756e742000000000000000000081526000835161550c816017850160208801614b52565b7f206973206d697373696e6720726f6c65200000000000000000000000000000006017918401918201528351615549816028840160208801614b52565b01602801949350505050565b60008161556457615564614bf2565b506000190190565b6000825161557e818460208701614b52565b919091019291505056fea26469706673582212200b18dcc128057ba250f5a7b32001656aabd251b001d613069ab15ec4909cd91d64736f6c63430008130033

Deployed Bytecode

0x6080604052600436106101dc5760003560e01c806374d807be11610102578063b2079fa311610095578063d2a47a7011610064578063d2a47a70146106ba578063d547741f146106da578063e249d277146106fa578063ff7885331461074257600080fd5b8063b2079fa3146105ae578063bfb231d2146105db578063c0c4c8ff1461066d578063c0c53b8b1461069a57600080fd5b80639e102b82116100d15780639e102b821461052e5780639ee6ec1d1461054e578063a217fddf14610561578063aac044fb1461057657600080fd5b806374d807be146103c957806380fe5a6d146103e957806391d14854146104c8578063979335051461050e57600080fd5b80632f2ff15d1161017a5780633f77cfa0116101495780633f77cfa0146103635780634f3df7a51461038357806357bed5d41461039657806373c75441146103b657600080fd5b80632f2ff15d146102e357806330be54361461030357806331d6b0651461032357806336568abe1461034357600080fd5b806323c4b449116101b657806323c4b44914610252578063248a9ca3146102725780632acf4c40146102b05780632b09dd0f146102c357600080fd5b806301ffc9a7146101e85780630f6521291461021d578063161c1c351461023257600080fd5b366101e357005b600080fd5b3480156101f457600080fd5b506102086102033660046144eb565b610762565b60405190151581526020015b60405180910390f35b61023061022b3660046145da565b610799565b005b34801561023e57600080fd5b5061023061024d366004614649565b610af5565b34801561025e57600080fd5b5061023061026d366004614677565b610b7e565b34801561027e57600080fd5b506102a261028d3660046146ad565b60009081526065602052604090206001015490565b604051908152602001610214565b6102306102be3660046146f1565b610efc565b3480156102cf57600080fd5b506102306102de366004614649565b61118d565b3480156102ef57600080fd5b506102306102fe366004614772565b61120a565b34801561030f57600080fd5b5061023061031e3660046147a2565b61122f565b34801561032f57600080fd5b5061023061033e366004614817565b61147e565b34801561034f57600080fd5b5061023061035e366004614772565b6114a6565b34801561036f57600080fd5b5061023061037e3660046148ae565b611533565b610230610391366004614817565b6115b6565b3480156103a257600080fd5b506102306103b13660046146ad565b61198e565b6102306103c43660046146ad565b611ca8565b3480156103d557600080fd5b506102306103e43660046147a2565b611f2d565b3480156103f557600080fd5b506104b86104043660046146ad565b60ca6020908152600091825260409182902082516101008101845281548152600182015463ffffffff808216948301949094526401000000008104841694820194909452600160401b840483166060820152600160601b8404909216608083015260ff600160801b8404811660a0840152600160881b8404811660c0840152600160901b909304831660e08301526002810154600390910154919290916001600160a01b03811691600160a01b9091041684565b60405161021494939291906148fd565b3480156104d457600080fd5b506102086104e3366004614772565b60009182526065602090815260408084206001600160a01b0393909316845291905290205460ff1690565b34801561051a57600080fd5b50610230610529366004614649565b6120cd565b34801561053a57600080fd5b5061023061054936600461499c565b61214a565b61023061055c366004614a70565b612248565b34801561056d57600080fd5b506102a2600081565b34801561058257600080fd5b506105966105913660046146ad565b6124ce565b6040516001600160a01b039091168152602001610214565b3480156105ba57600080fd5b506105ce6105c93660046146ad565b6124f2565b6040516102149190614a95565b3480156105e757600080fd5b506106366105f63660046146ad565b60c9602052600090815260409020805460018201546002830154600390930154919290916001600160a01b0391821691811690600160a01b900460ff1685565b6040805195865260208601949094526001600160a01b039283169385019390935216606083015260ff16608082015260a001610214565b34801561067957600080fd5b506102a2610688366004614649565b60cb6020526000908152604090205481565b3480156106a657600080fd5b506102306106b5366004614aa3565b6125e6565b3480156106c657600080fd5b506102306106d5366004614aee565b612800565b3480156106e657600080fd5b506102306106f5366004614772565b61290c565b34801561070657600080fd5b5061071a610715366004614a70565b612931565b604080519586526020860194909452928401919091526060830152608082015260a001610214565b34801561074e57600080fd5b5061023061075d366004614817565b612a89565b60006001600160e01b03198216637965db0b60e01b148061079357506301ffc9a760e01b6001600160e01b03198316145b92915050565b6107a1612aa0565b600084815260ca60205260409020428310156107d05760405163f4230a5760e01b815260040160405180910390fd5b600181015460cc5460405163b1147ac160e01b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d69263b1147ac19261082c928a928a928a924692600160881b900460ff16916001600160a01b0316908b90600401614ba2565b60006040518083038186803b15801561084457600080fd5b505af4158015610858573d6000803e3d6000fd5b5050505061086585612af9565b60008060008060006108788a6000612931565b60018b01549499509297509095509350915042906108a390600160601b900463ffffffff1683614c08565b116108c15760405163f4230a5760e01b815260040160405180910390fd5b60006108cc8b6124ce565b90506108e2816108dc8c86614c08565b33612b59565b6001600160a01b038116600090815260cb60205260408120805486929061090a908490614c08565b909155505060008b815260c9602052604090206003015461093e906001600160a01b0316876109398d89614c08565b612c96565b60018088015460ff600160801b820481169261096492600160881b900490911690614c1b565b60ff1603610a6f5761097587612e6c565b60038781015460008d815260c960205260408082209051631f9f5fb560e21b81526001600160a01b0393841660048201528154602482015260018201546044820152600282015484166064820152930154918216608484015260a09190911c60ff1660a483015260c482015273495279f278fe3d44b92c320d84397559271d1fb590637e7d7ed49060e40160006040518083038186803b158015610a1857600080fd5b505af4158015610a2c573d6000803e3d6000fd5b505050508a7fcf2c54121f1f969a5f1ef034280738334cc37362016fa191d67eadec18ab04138b604051610a6291815260200190565b60405180910390a2610ade565b600187018054601190610a8b90600160881b900460ff16614c34565b91906101000a81548160ff021916908360ff1602179055508a7f874dd68f5d4b9530b4d57f516b7830957282deaebe992c9bae94dcd244c8eef28b604051610ad591815260200190565b60405180910390a25b50505050505050610aef6001609755565b50505050565b610afd612aa0565b6000610b0881612eec565b6001600160a01b038216600090815260cb6020526040902054610b2c838233612ef6565b6001600160a01b038316600081815260cb6020526040808220829055518392917f772e576b9fc0ca150ba5f438bab3fae809babf5bc72c5fe5d963e4f126c886a691a35050610b7b6001609755565b50565b610b86612aa0565b80600003610ba75760405163162908e360e11b815260040160405180910390fd5b600083815260ca6020908152604080832060c9835292819020815160a0810183528154815260018201549381019390935260028101546001600160a01b03908116928401929092526003015490811660608301819052600160a01b90910460ff1660808301523303610c2157610c1c85612f8d565b610c79565b3360009081527f20ed6bc75ca2f07d3f30c9ffd0b7d42ad30542806a6d5ce8b8b71f2228b0a3da602052604090205460ff16610c7057604051636edaef2f60e11b815260040160405180910390fd5b610c7985612af9565b600382015460408083015160208401519151633939a00160e11b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d693637273400293610ccb936001600160a01b03909216928a90600401614c53565b60006040518083038186803b158015610ce357600080fd5b505af4158015610cf7573d6000803e3d6000fd5b505050506000610d08866001612931565b5050506003850154604051631f9f5fb560e21b815292935073495279f278fe3d44b92c320d84397559271d1fb592637e7d7ed49250610d58916001600160a01b0316908690600090600401614c83565b60006040518083038186803b158015610d7057600080fd5b505af4158015610d84573d6000803e3d6000fd5b505050600384015460608401516040516305bd511560e11b815273495279f278fe3d44b92c320d84397559271d1fb59350630b7aa22a92610dd5926001600160a01b03909116918790600401614ced565b60006040518083038186803b158015610ded57600080fd5b505af4158015610e01573d6000803e3d6000fd5b505050506003830154610e1d90600160a01b900460ff16612fbe565b610e2857600a610e2b565b60065b60038401805460ff60a01b1916600160a01b83600a811115610e4f57610e4f6148d3565b02179055506060820151604051630f78acab60e31b815260048101839052602481018690526001600160a01b0390911690637bc5655890604401600060405180830381600087803b158015610ea357600080fd5b505af1158015610eb7573d6000803e3d6000fd5b505050508084877f72fe82cd21a1a15fa4aa0b197f1db5ec0c7dbea458a241c0a193b615555ea09760405160405180910390a4505050610ef76001609755565b505050565b610f04612aa0565b610f0d83612f8d565b600083815260ca602052604081206003810154909190610f379033906001600160a01b0316613081565b600086815260c96020908152604091829020825160a08101845281548152600182015481840181905260028301546001600160a01b03908116958301959095526003909201549384166060820152600160a01b90930460ff1660808401529293509091908a0135148015610fcf5750610fb660608a0160408b01614649565b6001600160a01b031681604001516001600160a01b0316145b8015610ff35750610fe660a08a0160808b01614d4f565b60ff16816080015160ff16145b8015611000575080518935145b61101d576040516327b3518960e11b815260040160405180910390fd5b600061103761103260808c0160608d01614649565b6130db565b9050611042876124ce565b6001600160a01b0316816001600160a01b03161461107357604051631eb3268560e31b815260040160405180910390fd5b6000806000806110848b6001612931565b50935093509350935061109c8e8e8e60028e8e61313f565b8c358111156110b9576110b4856108dc8f3584614d6c565b6110db565b60006110c6828f35614d6c565b905080156110d9576110d986828a612ef6565b505b6001600160a01b038516600090815260cb602052604081208054849290611103908490614c08565b90915550506060860151611118908585612c96565b600188015461113a9060ff600160881b8204811691600160801b900416614d7f565b60ff168b7f90bfd14bfda88bd1c0f165030b0d00bbd67c021452e46d63b32770f43bc1e8c860405160405180910390a361117388612e6c565b50505050505050506111856001609755565b505050505050565b600061119881612eec565b6001600160a01b0382166111bf5760405163e6c4247b60e01b815260040160405180910390fd5b60cd80546001600160a01b0319166001600160a01b0384169081179091556040517fe62d9ecc2f46536d69df8cf1ba196250488dc869eadabc42466d72ee898716ce90600090a25050565b60008281526065602052604090206001015461122581612eec565b610ef7838361358e565b611237612aa0565b7f321163fcbab3bac890d4fb1f03b22c5c6bd95bc472ee55584937974a1db0335661126181612eec565b60005b8281101561146e57600084848381811061128057611280614d98565b60209081029290920135600081815260ca8452604080822060c98652818320825160a0810184528154815260018201549781019790975260028101546001600160a01b03908116888501526003909101549081166060880152600160a01b900460ff16608087015290516359bf732f60e01b815292955093925090733d7bc1c3cc39e41e8be4711898075bc21c22a9d6906359bf732f906113279086908690600401614dae565b602060405180830381865af4158015611344573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113689190614dff565b9050600061137983606001516130db565b6001600160a01b038116600090815260cb60205260408120805492935084929091906113a6908490614c08565b90915550506003840154604051637c68c57160e11b815273495279f278fe3d44b92c320d84397559271d1fb59163f8d18ae2916113f59133916001600160a01b03909116908890600401614ced565b60006040518083038186803b15801561140d57600080fd5b505af4158015611421573d6000803e3d6000fd5b506002925061142e915050565b60405186907ed0e48b2e978cce35d3b88d090f3361dcffdf8a233ebcad9d572adadf3152c190600090a350505050508061146790614e18565b9050611264565b505061147a6001609755565b5050565b611486612aa0565b6114958585856001868661313f565b61149f6001609755565b5050505050565b6001600160a01b03811633146115295760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201527f20726f6c657320666f722073656c66000000000000000000000000000000000060648201526084015b60405180910390fd5b61147a8282613630565b600082815260ca60205260409020600301546115599033906001600160a01b0316613081565b50600082815260ca6020526040808220600101805460ff60901b1916600160901b60ff8616908102919091179091559051909184917f719e7861647821315c8e1bcf126e3affc0d31c1f250cabdc2904054fff3515f49190a35050565b6115be612aa0565b60405163a668c9af60e01b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d69063a668c9af906115fc90600190899089908890600401614f40565b60006040518083038186803b15801561161457600080fd5b505af4158015611628573d6000803e3d6000fd5b505060cc54604051636f82e3ed60e11b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d6935063df05c7da925061167c91899189918991899146916001600160a01b03909116908a90600401614f74565b60006040518083038186803b15801561169457600080fd5b505af41580156116a8573d6000803e3d6000fd5b505050600084815260ca6020526040902060010154600160801b900460ff161590506116e7576040516368ac339960e01b815260040160405180910390fd5b6000806117016116fc36889003880188614fd6565b6136b3565b509250509150600061171f8860600160208101906110329190614649565b9050611735818385604001516108dc9190614c08565b60cd54604051635035507560e11b81523360048201526000916001600160a01b03169063a06aa0ea906024016020604051808303816000875af1158015611780573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117a49190615099565b90506040518060800160405280898036038101906117c29190614fd6565b81524260208201526001600160a01b038316604082015260600160009052600088815260ca60209081526040918290208351805182558083015160018301805483870151606080860151608087015160a088015160c089015160e09099015160ff908116600160901b0260ff60901b199a8216600160881b0260ff60881b1992909316600160801b029190911661ffff60801b1963ffffffff948516600160601b0263ffffffff60601b19968616600160401b02969096166fffffffffffffffff0000000000000000199886166401000000000267ffffffffffffffff19909a1695909b16949094179790971795909516979097179190911716929092179390931793909316919091179055918401516002820155918301516003830180546001600160a01b039092166001600160a01b03198316811782559285015192909174ffffffffffffffffffffffffffffffffffffffffff191617600160a01b83600a811115611932576119326148d3565b02179055505050600087815260c960205260409020899061195382826150b6565b505060405187907feaa1e7f59197f03e5abd233e86f8550ab3dbc2f40d353eeac8be6607517e5e0e90600090a25050505061149f6001609755565b7f3476efba29c1dd189ede426d6e97aa39c0683187a42f9eec0c97d2d56eb0a4bc6119b881612eec565b600082815260ca60205260409020600190810154600160901b900460ff169081148015906119ea57508060ff16600214155b15611a085760405163816fa01960e01b815260040160405180910390fd5b611a1183612f8d565b600080611a1f856000612931565b94509450505050426201518082611a369190614d6c565b1115611a5557604051638c1b949360e01b815260040160405180910390fd5b600085815260ca60205260409020600301546001600160a01b031660ff8416600203611c1e576000611a8682613808565b90506000611a93886124ce565b60405163699f200f60e01b81526b10d6505397d0d3d39115525560a21b600482015290915060009073cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015611af7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b1b9190615099565b90506001600160a01b038216611ba85760405163699f200f60e01b8152630ae8aa8960e31b600482015273cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015611b81573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ba59190615099565b91505b60405163368fa33960e21b81526001600160a01b038481166004830152858116602483015283811660448301526064820188905282169063da3e8ce490608401600060405180830381600087803b158015611c0257600080fd5b505af1158015611c16573d6000803e3d6000fd5b505050505050505b60405163174b554760e11b81526001600160a01b0382166004820152602481018790526044810184905260ff8516606482015273495279f278fe3d44b92c320d84397559271d1fb590632e96aa8e9060840160006040518083038186803b158015611c8857600080fd5b505af4158015611c9c573d6000803e3d6000fd5b50505050505050505050565b611cb0612aa0565b7f321163fcbab3bac890d4fb1f03b22c5c6bd95bc472ee55584937974a1db03356611cda81612eec565b600082815260ca60205260409020600180820154600160881b900460ff1614611d1657604051630201a46f60e31b815260040160405180910390fd5b60006003820154600160a01b900460ff16600a811115611d3857611d386148d3565b14158015611d66575060016003820154600160a01b900460ff16600a811115611d6357611d636148d3565b14155b15611d845760405163e82a532960e01b815260040160405180910390fd5b604080516101008101825282548152600183015463ffffffff80821660208401526401000000008204811693830193909352600160401b810483166060830152600160601b8104909216608082015260ff600160801b8304811660a0830152600160881b8304811660c0830152600160901b90920490911660e08201526000908190611e0f906136b3565b5092505091506000611e20866124ce565b6003850154909150600090611e3d906001600160a01b0316613808565b9050611e5982856040015185611e539190614c08565b83612ef6565b60016003860154600160a01b900460ff16600a811115611e7b57611e7b6148d3565b03611ebc578454611e8e90839033612b59565b600087815260c960205260408120600301548654611eb7926001600160a01b0390921691612c96565b611edb565b3415611edb5760405163162908e360e11b815260040160405180910390fd5b60038501805460ff60a01b1916600160a21b17905560405160049088907ed0e48b2e978cce35d3b88d090f3361dcffdf8a233ebcad9d572adadf3152c190600090a3505050505050610b7b6001609755565b611f35612aa0565b7f321163fcbab3bac890d4fb1f03b22c5c6bd95bc472ee55584937974a1db03356611f5f81612eec565b60005b8281101561146e576000848483818110611f7e57611f7e614d98565b60209081029290920135600081815260ca8452604080822060c990955290819020600301548454915163a2fb342d60e01b815233600482015260248101929092529194506001600160a01b03909116915063a2fb342d90604401600060405180830381600087803b158015611ff257600080fd5b505af1158015612006573d6000803e3d6000fd5b50505050600181810154600160881b900460ff161461203857604051630201a46f60e31b815260040160405180910390fd5b60006003820154600160a01b900460ff16600a81111561205a5761205a6148d3565b146120785760405163e82a532960e01b815260040160405180910390fd5b60038101805460ff60a01b1916600160a01b17905560405160019083907ed0e48b2e978cce35d3b88d090f3361dcffdf8a233ebcad9d572adadf3152c190600090a35050806120c690614e18565b9050611f62565b60006120d881612eec565b6001600160a01b0382166120ff5760405163e6c4247b60e01b815260040160405180910390fd5b60cc80546001600160a01b0319166001600160a01b0384169081179091556040517fb600274ef5d11bda880beece19f867f60804daa64e9abecaf8f54ba2d2a73c1190600090a25050565b612152612aa0565b4282101561217357604051638baa579f60e01b815260040160405180910390fd5b60cc5460405163e13fe1ad60e01b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d69163e13fe1ad916121c3918b918a918a918a918a9146916001600160a01b0316908b90600401615146565b60006040518083038186803b1580156121db57600080fd5b505af41580156121ef573d6000803e3d6000fd5b5050505061223587878787878080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509250613853915050565b61223f6001609755565b50505050505050565b612250612aa0565b61225982612f8d565b600082815260ca60205260408120600181015490919061228c9060ff600160881b8204811691600160801b900416614d7f565b90506000838061229f57508160ff166001145b90506000806000806122b18986612931565b50935093509350935060006122c58a6124ce565b90506122d2818333612b59565b6001600160a01b038116600090815260cb6020526040812080548592906122fa908490614c08565b909155505060008a815260c96020526040902060030154612325906001600160a01b03168686612c96565b851561245a5761233488612e6c565b60038881015460008c815260c960205260408082209051631f9f5fb560e21b81526001600160a01b0393841660048201528154602482015260018201546044820152600282015484166064820152930154918216608484015260a09190911c60ff1660a483015260c482015273495279f278fe3d44b92c320d84397559271d1fb590637e7d7ed49060e40160006040518083038186803b1580156123d757600080fd5b505af41580156123eb573d6000803e3d6000fd5b50505050881561242a5760405160ff8816908b907f90bfd14bfda88bd1c0f165030b0d00bbd67c021452e46d63b32770f43bc1e8c890600090a36124bc565b6040518a907fdfd517ed69f8a0a57d49fe494e4864fac3cfe3585c14c0bfddf39f72463ec3fd90600090a26124bc565b60018801805460119061247690600160881b900460ff16614c34565b91906101000a81548160ff021916908360ff160217905550897f581d416ae9dff30c9305c2b35cb09ed5991897ab97804db29ccf92678e95316060405160405180910390a25b505050505050505061147a6001609755565b600081815260c96020526040812060030154610793906001600160a01b03166130db565b60006002600083815260ca6020526040902060030154600160a01b900460ff16600a811115612523576125236148d3565b148061255b57506007600083815260ca6020526040902060030154600160a01b900460ff16600a811115612559576125596148d3565b145b156125c657600061256d836000612931565b9450505042831091505080156125c3576002600085815260ca6020526040902060030154600160a01b900460ff16600a8111156125ac576125ac6148d3565b146125b85760086125bb565b60035b949350505050565b50505b50600090815260ca6020526040902060030154600160a01b900460ff1690565b600054610100900460ff16158080156126065750600054600160ff909116105b806126205750303b158015612620575060005460ff166001145b6126925760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a65640000000000000000000000000000000000006064820152608401611520565b6000805460ff1916600117905580156126b5576000805461ff0019166101001790555b6001600160a01b03841615806126d257506001600160a01b038316155b806126e457506001600160a01b038216155b156127025760405163e6c4247b60e01b815260040160405180910390fd5b60cc80546001600160a01b038087166001600160a01b03199283161790925560cd80549285169290911691909117905561273d600084613f1f565b612745613f29565b61274d613f96565b6040516001600160a01b038516907fb600274ef5d11bda880beece19f867f60804daa64e9abecaf8f54ba2d2a73c1190600090a26040516001600160a01b038316907fe62d9ecc2f46536d69df8cf1ba196250488dc869eadabc42466d72ee898716ce90600090a28015610aef576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a150505050565b612808612aa0565b4282101561282957604051638baa579f60e01b815260040160405180910390fd5b6040516302edd95160e11b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d6906305dbb2a29061286a9089908890879046908a9089906004016151ba565b60006040518083038186803b15801561288257600080fd5b505af4158015612896573d6000803e3d6000fd5b505050506001600160a01b03831660009081527f20ed6bc75ca2f07d3f30c9ffd0b7d42ad30542806a6d5ce8b8b71f2228b0a3da602052604090205460ff166128f257604051634828265b60e11b815260040160405180910390fd5b60606129018787878488613853565b506111856001609755565b60008281526065602052604090206001015461292781612eec565b610ef78383613630565b600082815260ca602090815260408083208151610100810183528154815260019091015463ffffffff808216948301949094526401000000008104841692820192909252600160401b820483166060820152600160601b8204909216608083015260ff600160801b8204811660a08401819052600160881b8304821660c0850152600160901b9092041660e0830152829182918291829182036129e75760405163467136bd60e11b815260040160405180910390fd5b600088815260ca60205260409081902060020154905163c1ccd57960e01b8152733d7bc1c3cc39e41e8be4711898075bc21c22a9d69163c1ccd57991612a349185918c9190600401615200565b60a060405180830381865af4158015612a51573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a759190615284565b939c929b5090995097509095509350505050565b612a91612aa0565b6114958585856000868661313f565b600260975403612af25760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401611520565b6002609755565b6000612b04826124f2565b9050600381600a811115612b1a57612b1a6148d3565b14158015612b3b575060085b81600a811115612b3857612b386148d3565b14155b1561147a5760405163e82a532960e01b815260040160405180910390fd5b6001600160a01b038316612b8757348214610ef75760405163162908e360e11b815260040160405180910390fd5b3415612ba65760405163162908e360e11b815260040160405180910390fd5b60405163699f200f60e01b81526b10d6505397d0d3d39115525560a21b600482015273cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015612c04573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c289190615099565b60405163368fa33960e21b81526001600160a01b038381166004830152306024830152858116604483015260648201859052919091169063da3e8ce490608401600060405180830381600087803b158015612c8257600080fd5b505af115801561223f573d6000803e3d6000fd5b60008390506000816001600160a01b031663bfe0c27e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612cdb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cff9190615099565b90506001600160a01b038116612d84576001600160a01b03821663643840f2612d288587614c08565b6040516001600160e01b031960e084901b16815260048101889052602481018790526044016000604051808303818588803b158015612d6657600080fd5b505af1158015612d7a573d6000803e3d6000fd5b505050505061149f565b806001600160a01b03811663095ea7b387612d9f8789614c08565b6040516001600160e01b031960e085901b1681526001600160a01b03909216600483015260248201526044016020604051808303816000875af1158015612dea573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e0e91906152c4565b5060405163321c207960e11b815260048101869052602481018590526001600160a01b0384169063643840f290604401600060405180830381600087803b158015612e5857600080fd5b505af1158015611c9c573d6000803e3d6000fd5b60018101805460ff60881b198116600160801b90910460ff908116600160881b02919091179091556003820154612eab91600160a01b90910416612fbe565b612eb6576009612eb9565b60055b60038201805460ff60a01b1916600160a01b83600a811115612edd57612edd6148d3565b021790555050565b6001609755565b610b7b8133614009565b6001600160a01b038316612f78576000816001600160a01b03168360405160006040518083038185875af1925050503d8060008114612f51576040519150601f19603f3d011682016040523d82523d6000602084013e612f56565b606091505b5050905080610aef57604051630db2c7f160e31b815260040160405180910390fd5b82610aef6001600160a01b038216838561407e565b6000612f98826124f2565b9050600281600a811115612fae57612fae6148d3565b14158015612b3b57506007612b26565b60008082600a811115612fd357612fd36148d3565b1480612ff05750600182600a811115612fee57612fee6148d3565b145b8061300c5750600282600a81111561300a5761300a6148d3565b145b806130285750600382600a811115613026576130266148d3565b145b806130445750600482600a811115613042576130426148d3565b145b806130605750600582600a81111561305e5761305e6148d3565b145b806107935750600682600a81111561307a5761307a6148d3565b1492915050565b6000826001600160a01b03808216908416146130d4576130a083613808565b9050806001600160a01b0316846001600160a01b0316146130d457604051636edaef2f60e11b815260040160405180910390fd5b9392505050565b6000816001600160a01b031663bfe0c27e6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561311b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107939190615099565b600084815260ca6020526040902060010154600160801b900460ff1615613179576040516368ac339960e01b815260040160405180910390fd5b60cd54604051635035507560e11b81523360048201526000916001600160a01b03169063a06aa0ea906024016020604051808303816000875af11580156131c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131e89190615099565b9050336001600160a01b0382168190036132085761320582613808565b90505b60cc546040516313f3090b60e01b8152600091733d7bc1c3cc39e41e8be4711898075bc21c22a9d6916313f3090b9161325d918d918d918d918d918d918b918d916001600160a01b0316908f906004016152f1565b602060405180830381865af415801561327a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061329e91906152c4565b905060028660028111156132b4576132b46148d3565b1461339c57801561332f57604051637c68c57160e11b815273495279f278fe3d44b92c320d84397559271d1fb59063f8d18ae2906132fa90859087908e90600401615360565b60006040518083038186803b15801561331257600080fd5b505af4158015613326573d6000803e3d6000fd5b5050505061339c565b604051631f9f5fb560e21b815273495279f278fe3d44b92c320d84397559271d1fb590637e7d7ed49061336b9086908d90600190600401615385565b60006040518083038186803b15801561338357600080fd5b505af4158015613397573d6000803e3d6000fd5b505050505b600087815260c96020526040902089906133b682826150b6565b50506040805160808101909152806133d3368b90038b018b614fd6565b81524260208201526001600160a01b038516604082015260600160079052600088815260ca60209081526040918290208351805182558083015160018301805483870151606080860151608087015160a088015160c089015160e09099015160ff908116600160901b0260ff60901b199a8216600160881b0260ff60881b1992909316600160801b029190911661ffff60801b1963ffffffff948516600160601b0263ffffffff60601b19968616600160401b02969096166fffffffffffffffff0000000000000000199886166401000000000267ffffffffffffffff19909a1695909b16949094179790971795909516979097179190911716929092179390931793909316919091179055918401516002820155918301516003830180546001600160a01b039092166001600160a01b03198316811782559285015192909174ffffffffffffffffffffffffffffffffffffffffff191617600160a01b83600a811115613543576135436148d3565b0217905550905050867fe3c5a8fbdc814f563f15d04282af0e83465c96f99634799decb45e715d5908d18760405161357b91906153a2565b60405180910390a2505050505050505050565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff1661147a5760008281526065602090815260408083206001600160a01b03851684529091529020805460ff191660011790556135ec3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff161561147a5760008281526065602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6136d760405180606001604052806000815260200160008152602001600081525090565b6136fb60405180606001604052806000815260200160008152602001600081525090565b6000806000856020015163ffffffff161161371757600061371a565b60015b8560a001516137299190614d7f565b9050612710856020015163ffffffff16866000015161374891906153b0565b61375291906153c7565b8551909250613762908390614d6c565b80845260408601516127109161377e9163ffffffff16906153b0565b61378891906153c7565b602084015260608501518551612710916137aa9163ffffffff909116906153b0565b6137b491906153c7565b604084015282516137c99060ff8316906153c7565b845260208301516137de9060ff8316906153c7565b602085015260a085015160408401516137fa9160ff16906153c7565b604085015292949193509190565b60cd5460405163966708a560e01b81526001600160a01b038381166004830152600092169063966708a590602401602060405180830381865afa15801561311b573d6000803e3d6000fd5b600085815260ca6020908152604080832060c9835292819020815160a0810183528154815260018201549381019390935260028101546001600160a01b0390811692840192909252600301549081166060830152600160a01b900460ff1660808201526138bf87612f8d565b60006138ca886124ce565b90506000806000806138dd8c6001612931565b50935093509350935085606001516001600160a01b0316336001600160a01b03161461392257600387015461391c9033906001600160a01b0316613081565b50613943565b898111156139435760405163162908e360e11b815260040160405180910390fd5b733d7bc1c3cc39e41e8be4711898075bc21c22a9d663727340028860030160009054906101000a90046001600160a01b0316886040015189602001518f6040518563ffffffff1660e01b815260040161399f9493929190614c53565b60006040518083038186803b1580156139b757600080fd5b505af41580156139cb573d6000803e3d6000fd5b505050506003870154604051631f9f5fb560e21b815273495279f278fe3d44b92c320d84397559271d1fb591637e7d7ed491613a18916001600160a01b0316908a90600090600401614c83565b60006040518083038186803b158015613a3057600080fd5b505af4158015613a44573d6000803e3d6000fd5b5050506001600160a01b0389169050613b56576001600160a01b03851615613a7f57604051631eb3268560e31b815260040160405180910390fd5b8660030160009054906101000a90046001600160a01b03166001600160a01b031663a93b06c86373f8e32860e01b838d8a8e604051602401613ac494939291906153e9565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b03199485161790525160e084901b9092168252613b0991600401615453565b6000604051808303816000875af1158015613b28573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052613b509190810190615466565b50613e20565b60405163699f200f60e01b81526b10d6505397d0d3d39115525560a21b600482015273cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015613bb4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613bd89190615099565b60038801546001600160a01b039182169163da3e8ce4918b9190811690891615613c025788613c7c565b60405163699f200f60e01b8152630ae8aa8960e31b600482015273cf9a19d879769adae5e4f31503aaecda82568e559063699f200f90602401602060405180830381865afa158015613c58573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c7c9190615099565b60405160e085901b6001600160e01b03191681526001600160a01b03938416600482015291831660248301529091166044820152606481018d9052608401600060405180830381600087803b158015613cd457600080fd5b505af1158015613ce8573d6000803e3d6000fd5b50505050600387015460408051602481018490526001600160a01b0388811660448084019190915283518084039091018152606490920183526020820180516001600160e01b0316631ae9c0eb60e11b179052915163152760d960e31b8152919092169163a93b06c891613d5f9190600401615453565b6000604051808303816000875af1158015613d7e573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052613da69190810190615466565b5060038701546040516305bd511560e11b815273495279f278fe3d44b92c320d84397559271d1fb591630b7aa22a91613def916001600160a01b0316908c908b90600401614ced565b60006040518083038186803b158015613e0757600080fd5b505af4158015613e1b573d6000803e3d6000fd5b505050505b600387015460405163a7737e3160e01b81526001600160a01b038088166004830152909116602482015260448101829052733d7bc1c3cc39e41e8be4711898075bc21c22a9d69063a7737e319060640160006040518083038186803b158015613e8857600080fd5b505af4158015613e9c573d6000803e3d6000fd5b505050506001600160a01b038516600090815260cb602052604081208054849290613ec8908490614c08565b90915550506060860151613edd908585612c96565b613ee687612e6c565b6040518c907ffa77073553b7085fac8c378daa25f5d003ce42427f66d5514834f634123e1c9e90600090a2505050505050505050505050565b61147a828261358e565b600054610100900460ff16613f945760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401611520565b565b600054610100900460ff166140015760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401611520565b613f946140d0565b60008281526065602090815260408083206001600160a01b038516845290915290205460ff1661147a5761403c8161413b565b61404783602061414d565b6040516020016140589291906154d4565b60408051601f198184030181529082905262461bcd60e51b825261152091600401615453565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610ef79084906142f6565b600054610100900460ff16612ee55760405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608401611520565b60606107936001600160a01b03831660145b6060600061415c8360026153b0565b614167906002614c08565b67ffffffffffffffff81111561417f5761417f614515565b6040519080825280601f01601f1916602001820160405280156141a9576020820181803683370190505b509050600360fc1b816000815181106141c4576141c4614d98565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106141f3576141f3614d98565b60200101906001600160f81b031916908160001a90535060006142178460026153b0565b614222906001614c08565b90505b60018111156142a7577f303132333435363738396162636465660000000000000000000000000000000085600f166010811061426357614263614d98565b1a60f81b82828151811061427957614279614d98565b60200101906001600160f81b031916908160001a90535060049490941c936142a081615555565b9050614225565b5083156130d45760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401611520565b600061434b826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166143c89092919063ffffffff16565b805190915015610ef7578080602001905181019061436991906152c4565b610ef75760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401611520565b60606125bb848460008585600080866001600160a01b031685876040516143ef919061556c565b60006040518083038185875af1925050503d806000811461442c576040519150601f19603f3d011682016040523d82523d6000602084013e614431565b606091505b50915091506144428783838761444d565b979650505050505050565b606083156144bc5782516000036144b5576001600160a01b0385163b6144b55760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401611520565b50816125bb565b6125bb83838151156144d15781518083602001fd5b8060405162461bcd60e51b81526004016115209190615453565b6000602082840312156144fd57600080fd5b81356001600160e01b0319811681146130d457600080fd5b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff8111828210171561455457614554614515565b604052919050565b600067ffffffffffffffff82111561457657614576614515565b50601f01601f191660200190565b600082601f83011261459557600080fd5b81356145a86145a38261455c565b61452b565b8181528460208386010111156145bd57600080fd5b816020850160208301376000918101602001919091529392505050565b600080600080608085870312156145f057600080fd5b843593506020850135925060408501359150606085013567ffffffffffffffff81111561461c57600080fd5b61462887828801614584565b91505092959194509250565b6001600160a01b0381168114610b7b57600080fd5b60006020828403121561465b57600080fd5b81356130d481614634565b806040810183101561079357600080fd5b60008060006080848603121561468c57600080fd5b8335925061469d8560208601614666565b9150606084013590509250925092565b6000602082840312156146bf57600080fd5b5035919050565b600060a082840312156146d857600080fd5b50919050565b600061010082840312156146d857600080fd5b600080600080600080610220878903121561470b57600080fd5b61471588886146c6565b95506147248860a089016146de565b94506101a087013593506101c087013592506101e0870135915061020087013567ffffffffffffffff81111561475957600080fd5b61476589828a01614584565b9150509295509295509295565b6000806040838503121561478557600080fd5b82359150602083013561479781614634565b809150509250929050565b600080602083850312156147b557600080fd5b823567ffffffffffffffff808211156147cd57600080fd5b818501915085601f8301126147e157600080fd5b8135818111156147f057600080fd5b8660208260051b850101111561480557600080fd5b60209290920196919550909350505050565b6000806000806000610200868803121561483057600080fd5b61483a87876146c6565b94506148498760a088016146de565b93506101a086013592506101c086013591506101e086013567ffffffffffffffff81111561487657600080fd5b61488288828901614584565b9150509295509295909350565b60ff81168114610b7b57600080fd5b80356148a98161488f565b919050565b600080604083850312156148c157600080fd5b8235915060208301356147978161488f565b634e487b7160e01b600052602160045260246000fd5b600b81106148f9576148f96148d3565b9052565b610160810161496e828780518252602081015163ffffffff8082166020850152806040840151166040850152806060840151166060850152806080840151166080850152505060ff60a08201511660a083015260ff60c08201511660c083015260ff60e08201511660e08301525050565b846101008301526001600160a01b0384166101208301526149936101408301846148e9565b95945050505050565b600080600080600080600060e0888a0312156149b757600080fd5b873596506149c88960208a01614666565b955060608801359450608088013567ffffffffffffffff808211156149ec57600080fd5b818a0191508a601f830112614a0057600080fd5b813581811115614a0f57600080fd5b8b6020828501011115614a2157600080fd5b6020830196508095505060a08a0135935060c08a0135915080821115614a4657600080fd5b50614a538a828b01614584565b91505092959891949750929550565b8015158114610b7b57600080fd5b60008060408385031215614a8357600080fd5b82359150602083013561479781614a62565b6020810161079382846148e9565b600080600060608486031215614ab857600080fd5b8335614ac381614634565b92506020840135614ad381614634565b91506040840135614ae381614634565b809150509250925092565b60008060008060008060e08789031215614b0757600080fd5b86359550614b188860208901614666565b9450606087013593506080870135614b2f81614634565b925060a0870135915060c087013567ffffffffffffffff81111561475957600080fd5b60005b83811015614b6d578181015183820152602001614b55565b50506000910152565b60008151808452614b8e816020860160208601614b52565b601f01601f19169290920160200192915050565b87815286602082015285604082015284606082015260ff841660808201526001600160a01b03831660a082015260e060c08201526000614be560e0830184614b76565b9998505050505050505050565b634e487b7160e01b600052601160045260246000fd5b8082018082111561079357610793614bf2565b60ff818116838216019081111561079357610793614bf2565b600060ff821660ff8103614c4a57614c4a614bf2565b60010192915050565b6001600160a01b03858116825284166020820152604080820184905260a082019083606084013795945050505050565b6001600160a01b038416815260e08101614cdd6020830185805182526020810151602083015260408101516001600160a01b038082166040850152806060840151166060850152505060ff60808201511660808301525050565b82151560c0830152949350505050565b6001600160a01b0384811682528316602082015260e081016125bb6040830184805182526020810151602083015260408101516001600160a01b038082166040850152806060840151166060850152505060ff60808201511660808301525050565b600060208284031215614d6157600080fd5b81356130d48161488f565b8181038181111561079357610793614bf2565b60ff828116828216039081111561079357610793614bf2565b634e487b7160e01b600052603260045260246000fd5b82815260c081016130d46020830184805182526020810151602083015260408101516001600160a01b038082166040850152806060840151166060850152505060ff60808201511660808301525050565b600060208284031215614e1157600080fd5b5051919050565b600060018201614e2a57614e2a614bf2565b5060010190565b80358252602081013560208301526040810135614e4d81614634565b6001600160a01b039081166040840152606082013590614e6c82614634565b1660608301526080810135614e808161488f565b60ff81166080840152505050565b803563ffffffff811681146148a957600080fd5b80358252614eb260208201614e8e565b63ffffffff808216602085015280614ecc60408501614e8e565b16604085015280614edf60608501614e8e565b16606085015280614ef260808501614e8e565b166080850152505060a0810135614f088161488f565b60ff1660a083015260c0810135614f1e8161488f565b60ff1660c0830152614f3260e0820161489e565b60ff811660e0840152505050565b84151581526101e08101614f576020830186614e31565b614f6460c0830185614ea2565b826101c083015295945050505050565b6000610240614f83838b614e31565b614f9060a084018a614ea2565b876101a0840152866101c0840152856101e08401526001600160a01b03851661020084015280610220840152614fc881840185614b76565b9a9950505050505050505050565b6000610100808385031215614fea57600080fd5b6040519081019067ffffffffffffffff8211818310171561500d5761500d614515565b816040528335815261502160208501614e8e565b602082015261503260408501614e8e565b604082015261504360608501614e8e565b606082015261505460808501614e8e565b608082015260a084013591506150698261488f565b8160a082015261507b60c0850161489e565b60c082015261508c60e0850161489e565b60e0820152949350505050565b6000602082840312156150ab57600080fd5b81516130d481614634565b813581556020820135600182015560408201356150d281614634565b6002820180546001600160a01b0319166001600160a01b0383161790555060038101606083013561510281614634565b81546001600160a01b0319166001600160a01b03821617825550608083013561512a8161488f565b815460ff60a01b191660a09190911b60ff60a01b161790555050565b88815287602082015260e060408201528560e082015260006101008789828501376000818985010152601f19601f89011683018760608501528660808501526001600160a01b03861660a0850152818482030160c08501526151aa82820186614b76565b9c9b505050505050505050505050565b8681528560208201528460408201528360608201526001600160a01b038316608082015260c060a082015260006151f460c0830184614b76565b98975050505050505050565b6101408101615271828680518252602081015163ffffffff8082166020850152806040840151166040850152806060840151166060850152806080840151166080850152505060ff60a08201511660a083015260ff60c08201511660c083015260ff60e08201511660e08301525050565b9215156101008201526101200152919050565b600080600080600060a0868803121561529c57600080fd5b5050835160208501516040860151606087015160809097015192989197509594509092509050565b6000602082840312156152d657600080fd5b81516130d481614a62565b600381106148f9576148f96148d3565b6000610280615300838d614e31565b61530d60a084018c614ea2565b896101a08401526153226101c084018a6152e1565b876101e08401526001600160a01b0380881661020085015280871661022085015280861661024085015250806102608401526151aa81840185614b76565b6001600160a01b0384811682528316602082015260e081016125bb6040830184614e31565b6001600160a01b038416815260e08101614cdd6020830185614e31565b6020810161079382846152e1565b808202811582820484141761079357610793614bf2565b6000826153e457634e487b7160e01b600052601260045260246000fd5b500490565b60006101008683528560208401526154416040840186805182526020810151602083015260408101516001600160a01b038082166040850152806060840151166060850152505060ff60808201511660808301525050565b8060e084015261444281840185614b76565b6020815260006130d46020830184614b76565b60006020828403121561547857600080fd5b815167ffffffffffffffff81111561548f57600080fd5b8201601f810184136154a057600080fd5b80516154ae6145a38261455c565b8181528560208385010111156154c357600080fd5b614993826020830160208601614b52565b7f416363657373436f6e74726f6c3a206163636f756e742000000000000000000081526000835161550c816017850160208801614b52565b7f206973206d697373696e6720726f6c65200000000000000000000000000000006017918401918201528351615549816028840160208801614b52565b01602801949350505050565b60008161556457615564614bf2565b506000190190565b6000825161557e818460208701614b52565b919091019291505056fea26469706673582212200b18dcc128057ba250f5a7b32001656aabd251b001d613069ab15ec4909cd91d64736f6c63430008130033

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits

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.