Sepolia Testnet

Contract

0x1C6568b1858C05F0229fadE7B01C473436Ab93B1

Overview

ETH Balance

0 ETH

Token Holdings

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Value
Deploy New Colle...53730742024-02-27 9:35:4854 days ago1709026548IN
0x1C6568b1...436Ab93B1
0 ETH0.0082395815.37287191
Deploy New Colle...49398592023-12-23 1:27:00120 days ago1703294820IN
0x1C6568b1...436Ab93B1
0 ETH0.000780461.50385896
Deploy New Colle...49393852023-12-22 23:32:48120 days ago1703287968IN
0x1C6568b1...436Ab93B1
0 ETH0.000825741.54040674
Deploy New Colle...49212752023-12-20 4:20:12123 days ago1703046012IN
0x1C6568b1...436Ab93B1
0 ETH0.001103232.16758892
Deploy New Colle...49209252023-12-20 3:00:00123 days ago1703041200IN
0x1C6568b1...436Ab93B1
0 ETH0.001144052.10624669
Set Subscription...49090422023-12-18 6:13:24125 days ago1702880004IN
0x1C6568b1...436Ab93B1
0 ETH0.0015205252.88782783
Set Factory49090402023-12-18 6:13:00125 days ago1702879980IN
0x1C6568b1...436Ab93B1
0 ETH0.0024813153.81758135
Add Implementati...49090392023-12-18 6:12:48125 days ago1702879968IN
0x1C6568b1...436Ab93B1
0 ETH0.0028964752.78693449
Add Implementati...49090382023-12-18 6:12:36125 days ago1702879956IN
0x1C6568b1...436Ab93B1
0 ETH0.0037735954.49475703
0x6080604049090322023-12-18 6:11:24125 days ago1702879884IN
 Create: EventManager
0 ETH0.1141213452.1375597

Advanced mode:
Parent Transaction Hash Block From To Value
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
EventManager

Compiler Version
v0.8.21+commit.d9974bed

Optimization Enabled:
Yes with 200 runs

Other Settings:
istanbul EvmVersion, MIT license

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 19 : EventManager.sol
// SPDX-License-Identifier: MIT
// Event Manager with Full Ticket's life cycle
pragma solidity 0.8.21;
    
    import "UsersSBTCollectionRegistry.sol";

contract EventManager is UsersSBTCollectionRegistry {

    struct Period {
        uint256 start;
        uint256 finish;
    }

    struct EventDates {
        Period useTicket;
        Period certificate;
        bytes2 sbtRules;
        address tickets;
    }

    // from ticket contracts to event contract (wNFT-SBT)
    // it possible to use one ticket's contract for different events
    mapping(address => address[]) public ticketsForEvents;

    // from event contract (wNFT-SBT) to dates
    mapping(address => EventDates) public events;
    
    /// This error occur when somebody try edit contract
    /// that was created by (for) another user
    error Unauthorized(address User, address Contract);

    constructor (address _subscrRegistry)
        UsersSBTCollectionRegistry(_subscrRegistry)
    {}

    function deployNewCollection(
        address _implAddress, 
        address _creator,
        string memory name_,
        string memory symbol_,
        string memory _baseurl,
        address _wrapper,
        address _ticketContract,
        EventDates calldata _eventDates
    ) public  returns (address newCollection)
    {
        // TODO   some  checks
        // First create event contract as simple proxy
        newCollection = deployNewCollection(
            _implAddress, 
            _creator,
            name_,
            symbol_,
            _baseurl,
            _wrapper
        );

        // Save event info
        ticketsForEvents[_ticketContract].push(newCollection);
        events[newCollection] = _eventDates;
    }

    function editDatesForEvent(address _eventContract, EventDates calldata _newEventDates)
        external
    {
        // Only event creator can edit dates
        Asset[] memory e = collectionRegistry[msg.sender];
        for (uint256 i = 0; i < e.length; i ++) {
            if (e[i].contractAddress == _eventContract) {
                events[_eventContract] =  _newEventDates;
                return;
            }
        }
        revert Unauthorized(msg.sender, _eventContract);
        
    }

    function getEventsForTicket(address _ticketContract) 
        external
        view 
        returns(address[] memory e, EventDates[] memory d)
    {
        e = ticketsForEvents[_ticketContract];
        d = new EventDates[](e.length);
        for (uint256 i = 0; i < e.length; i ++) {
            d[i] = events[e[i]];
        }

    }

    function getDataForEvent(address _eventContract)
        external
        view
        returns(EventDates memory d)
    {
        d = events[_eventContract];
    }

    function isWrapEnabled(
        address _ticketContract, 
        address _eventContract
    )
         external 
         view 
         returns(bool enabled) 
    {
        address[] memory e = ticketsForEvents[_ticketContract];
        for (uint256 i = 0; i < e.length; i ++) {
            if (e[i] == _eventContract) {
                if (events[_eventContract].useTicket.start <= block.timestamp && 
                    events[_eventContract].useTicket.finish > block.timestamp)
                {
                    enabled = true;
                }
            } 
        }
    }

    function isRulesUpdateEnabled(
        address _eventContract
    )
         external 
         view 
         returns(bytes2 rules) 
    {
        if (events[_eventContract].certificate.start <= block.timestamp && 
            events[_eventContract].certificate.finish > block.timestamp)
        {
            rules = events[_eventContract].sbtRules;
        }

    }

}

File 3 of 19 : UsersSBTCollectionRegistry.sol
// SPDX-License-Identifier: MIT
// Proxy for Public Mintable User NFT Collection
pragma solidity 0.8.21;
    
    import "ServiceProviderOwnable.sol";
    import "IUsersSBTCollectionFactory.sol";

contract UsersSBTCollectionRegistry is ServiceProviderOwnable {
    
    enum AssetType {EMPTY, NATIVE, ERC20, ERC721, ERC1155, FUTURE1, FUTURE2, FUTURE3}

    struct Asset {
        AssetType assetType;
        address contractAddress;
    }

    Asset[] public supportedImplementations;
    // mapping from user to his(her) contracts with type
    mapping(address => Asset[]) public collectionRegistry;

    IUsersSBTCollectionFactory public factory;
    
    constructor (address _subscrRegistry)
        ServiceProviderOwnable(_subscrRegistry)
    {}

    function deployNewCollection(
        address _implAddress, 
        address _creator,
        string memory name_,
        string memory symbol_,
        string memory _baseurl,
        address _wrapper
    ) public returns(address newCollection) 
    {
        (bool _supported, uint256 index) = isImplementationSupported(_implAddress);
        require(_supported, "This implementation address is not supported");
        _checkAndFixSubscription(msg.sender);
        newCollection = factory.deployProxyFor(
            _implAddress, 
            _creator,
            name_,
            symbol_,
            _baseurl,
            _wrapper
        );
        collectionRegistry[_creator].push(Asset(supportedImplementations[index].assetType, newCollection)); 
    }
    function getSupportedImplementation() external view returns(Asset[] memory) {
        return supportedImplementations;
    }

    function getUsersCollections(address _user) external view returns(Asset[] memory) {
        return collectionRegistry[_user];
    }
    ////////////////////////////////////
    /// Admin  functions           /////
    ////////////////////////////////////
    function addImplementation(Asset calldata _impl) external onlyOwner {
        // Check that not exist
        for(uint256 i; i < supportedImplementations.length; ++i){
            require(
                supportedImplementations[i].contractAddress != _impl.contractAddress,
                "Already exist"
            );
        }
        supportedImplementations.push(Asset(_impl.assetType, _impl.contractAddress));
    }

    function removeImplementationByIndex(uint256 _index) external onlyOwner {
        if (_index != supportedImplementations.length -1) {
            supportedImplementations[_index] = supportedImplementations[supportedImplementations.length -1];
        }
        supportedImplementations.pop();
    }

    function setFactory(address _factory) external onlyOwner {
        factory = IUsersSBTCollectionFactory(_factory);
    }

    //////////////////////////////////////
    function isImplementationSupported(address _impl) public view  returns(bool isSupported, uint256 index) {
        for (uint256 i; i < supportedImplementations.length; ++i){
            if (_impl == supportedImplementations[i].contractAddress){
                isSupported = true;
                index = i; 
                break;
            }
        }
    }

    function checkUserSubscription(address _user) 
            external 
            view 
            returns (bool ok, bool needFix)
        {
            (ok, needFix) = _checkUserSubscription(
                _user
            );
        }
}

File 4 of 19 : ServiceProviderOwnable.sol
// SPDX-License-Identifier: MIT
// ENVELOP(NIFTSY) Subscription Registry Contract V2


/// The subscription platform operates with the following role model 
/// (it is assumed that the actor with the role is implemented as a contract).
/// `Service Provider` is a contract whose services are sold by subscription.
/// `Agent` - a contract that sells a subscription on behalf ofservice provider. 
///  May receive sales commission
///  `Platform` - SubscriptionRegistry contract that performs processingsubscriptions, 
///  fares, tickets


pragma solidity 0.8.21;

import "Ownable.sol";
import "ServiceProvider.sol";

/// @title ServiceProviderOwnable  contract 
/// @author Envelop project Team
/// @notice Contract implements Ownable pattern for service providers.
/// @dev Inherit this code in service provider contract that
/// want use subscription. 
contract ServiceProviderOwnable is ServiceProvider, Ownable {


    constructor(address _subscrRegistry)
        ServiceProvider(_subscrRegistry) 
    {
        
    }

     ///////////////////////////////////////
    //     Admin functions               ///
    ////////////////////////////////////////
    function newTariff(Tariff memory _newTariff) external onlyOwner returns(uint256 tariffIndex) {
        tariffIndex = _registerServiceTariff(_newTariff); 
    }

    function registerServiceTariff(Tariff memory _newTariff) 
        external onlyOwner returns(uint256)
    {
        return _registerServiceTariff(_newTariff);
    }

    function editServiceTariff(
        uint256 _tariffIndex, 
        uint256 _timelockPeriod,
        uint256 _ticketValidPeriod,
        uint256 _counter,
        bool _isAvailable,
        address _beneficiary
    ) external onlyOwner 
    {
        _editServiceTariff(
            _tariffIndex, 
            _timelockPeriod,
            _ticketValidPeriod,
            _counter,
            _isAvailable,
            _beneficiary
        );
    }

    function addPayOption(
        uint256 _tariffIndex,
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) external onlyOwner returns(uint256 index)
    {
        index = _addTariffPayOption(
            _tariffIndex,
            _paymentToken,
            _paymentAmount,
            _agentFeePercent
        );
    }

    function editPayOption(
        uint256 _tariffIndex,
        uint256 _payWithIndex, 
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) external onlyOwner
    {
        _editTariffPayOption(
            _tariffIndex,
            _payWithIndex, 
            _paymentToken,
            _paymentAmount,
            _agentFeePercent
        );

    }

    function authorizeAgentForService(
        address _agent,
        uint256[] memory _serviceTariffIndexes
    ) external onlyOwner returns (uint256[] memory actualTariffs)
    {
        actualTariffs = _authorizeAgentForService(
            _agent,
            _serviceTariffIndexes
        );

    }

    function setSubscriptionRegistry(address _subscrRegistry) external onlyOwner {
        subscriptionRegistry = ISubscriptionRegistry(_subscrRegistry);
    }

    function setSubscriptionOnOff(bool _isEnable) external onlyOwner {
        isEnabled = _isEnable;
    }

}

File 5 of 19 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "Context.sol";

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

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

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

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

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

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

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions 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 6 of 19 : 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 7 of 19 : ServiceProvider.sol
// SPDX-License-Identifier: MIT
// ENVELOP(NIFTSY) Subscription Registry Contract V2


/// The subscription platform operates with the following role model 
/// (it is assumed that the actor with the role is implemented as a contract).
/// `Service Provider` is a contract whose services are sold by subscription.
/// `Agent` - a contract that sells a subscription on behalf ofservice provider. 
///  May receive sales commission
///  `Platform` - SubscriptionRegistry contract that performs processingsubscriptions, 
///  fares, tickets


pragma solidity 0.8.21;

import "ISubscriptionRegistry.sol";

/// @title ServiceProvider abstract contract 
/// @author Envelop project Team
/// @notice Abstract contract implements subscribing features.
/// For use with SubscriptionRegestry
/// @dev Use this code in service provider contract that
/// want use subscription. One contract = one servie
/// Please see example folder
abstract contract ServiceProvider {

    address public serviceProvider;
    ISubscriptionRegistry public subscriptionRegistry;
    bool public isEnabled = true;

    constructor(address _subscrRegistry) {
        require(_subscrRegistry != address(0), 'Non zero only');
        serviceProvider = address(this);
        subscriptionRegistry = ISubscriptionRegistry(_subscrRegistry);
    }

    function _registerServiceTariff(Tariff memory _newTariff) 
        internal virtual returns(uint256)
    {
        return subscriptionRegistry.registerServiceTariff(_newTariff);
    }

    
    function _editServiceTariff(
        uint256 _tariffIndex, 
        uint256 _timelockPeriod,
        uint256 _ticketValidPeriod,
        uint256 _counter,
        bool _isAvailable,
        address _beneficiary
    ) internal virtual 
    {
        subscriptionRegistry.editServiceTariff(
            _tariffIndex, 
            _timelockPeriod,
            _ticketValidPeriod,
            _counter,
            _isAvailable,
            _beneficiary
        );
    }

    function _addTariffPayOption(
        uint256 _tariffIndex,
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) internal virtual returns(uint256)
    {
        return subscriptionRegistry.addTariffPayOption(
            _tariffIndex,
            _paymentToken,
            _paymentAmount,
            _agentFeePercent
        );
    }
    
    function _editTariffPayOption(
        uint256 _tariffIndex,
        uint256 _payWithIndex, 
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) internal virtual 
    {
        subscriptionRegistry.editTariffPayOption(
            _tariffIndex,
            _payWithIndex, 
            _paymentToken,
            _paymentAmount,
            _agentFeePercent
        );
    } 

    function _authorizeAgentForService(
        address _agent,
        uint256[] memory _serviceTariffIndexes
    ) internal virtual returns (uint256[] memory)
    {
        // TODO Check agent
        return subscriptionRegistry.authorizeAgentForService(
            _agent,
            _serviceTariffIndexes
        );
    }

    ////////////////////////////
    //        Main USAGE      //
    ////////////////////////////
    function _checkAndFixSubscription(address _user) 
        internal 
        returns (bool ok) 
    { 
        if (isEnabled) {
            ok = subscriptionRegistry.checkAndFixUserSubscription(
                _user
            );
        } else {
            ok = true;
        }
    }

    function _checkUserSubscription(address _user) 
        internal 
        view 
        returns (bool ok, bool needFix)
    {
        if (isEnabled) {
            (ok, needFix) = subscriptionRegistry.checkUserSubscription(
                _user,
                address(this)  
            );
        } else {
            ok = true;
        }
    }
}

File 8 of 19 : ISubscriptionRegistry.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import {SubscriptionType, PayOption, Tariff, Ticket} from "SubscriptionRegistry.sol";
interface ISubscriptionRegistry   {

    /**
     * @notice Add new tariff for caller
     * @dev Call this method from ServiceProvider
     * for setup new tariff 
     * using `Tariff` data type(please see above)
     *
     * @param _newTariff full encded Tariff object
     * @return last added tariff index in  Tariff[] array 
     * for current Service Provider (msg.sender)
     */
    function registerServiceTariff(Tariff calldata _newTariff) external returns(uint256);
    
    
    /**
     * @notice Authorize agent for caller service provider
     * @dev Call this method from ServiceProvider
     *
     * @param _agent  - address of contract that implement Agent role 
     * @param _serviceTariffIndexes  - array of index in `availableTariffs` array
     * that available for given `_agent` 
     * @return full array of actual tarifs for this agent 
     */
    function authorizeAgentForService(
        address _agent,
        uint256[] calldata _serviceTariffIndexes
    ) external returns (uint256[] memory);

    /**
     * @notice By Ticket for subscription
     * @dev Call this method from Agent
     *
     * @param _service  - Service Provider address 
     * @param _tariffIndex  - index in  `availableTariffs` array 
     * @param _payWithIndex  - index in `tariff.payWith` array 
     * @param _buyFor - address for whome this ticket would be bought 
     * @param _payer - address of payer for this ticket
     * @return ticket structure that would be use for validate service process
     */ 
    function buySubscription(
        address _service,
        uint256 _tariffIndex,
        uint256 _payWithIndex,
        address _buyFor,
        address _payer
    ) external payable returns(Ticket memory ticket);

    /**
     * @notice Edit tariff for caller
     * @dev Call this method from ServiceProvider
     * for setup new tariff 
     * using `Tariff` data type(please see above)
     *
     * @param _tariffIndex  - index in `availableTariffs` array 
     * @param _timelockPeriod - see SubscriptionType notice above
     * @param _ticketValidPeriod - see SubscriptionType notice above
     * @param _counter - see SubscriptionType notice above
     * @param _isAvailable - see SubscriptionType notice above
     * @param _beneficiary - see SubscriptionType notice above
     */
    function editServiceTariff(
        uint256 _tariffIndex, 
        uint256 _timelockPeriod,
        uint256 _ticketValidPeriod,
        uint256 _counter,
        bool _isAvailable,
        address _beneficiary
    ) external;

    /**
     * @notice Add tariff PayOption for exact service
     * @dev Call this method from ServiceProvider
     * for add tariff PayOption 
     *
     * @param _tariffIndex  - index in `availableTariffs` array 
     * @param _paymentToken - see PayOption notice above
     * @param _paymentAmount - see PayOption notice above
     * @param _agentFeePercent - see PayOption notice above
     * @return last added PaymentOption index in array 
     * for _tariffIndex Tariff of caller Service Provider (msg.sender)
     */
    function addTariffPayOption(
        uint256 _tariffIndex,
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) external returns(uint256);
    
    /**
     * @notice Edit tariff PayOption for exact service
     * @dev Call this method from ServiceProvider
     * for edit tariff PayOption 
     *
     * @param _tariffIndex  - index in  `availableTariffs` array 
     * @param _payWithIndex  - index in `tariff.payWith` array 
     * @param _paymentToken - see PayOption notice above
     * @param _paymentAmount - see PayOption notice above
     * @param _agentFeePercent - see PayOption notice above
     * for _tariffIndex Tariff of caller Service Provider (msg.sender)
     */
    function editTariffPayOption(
        uint256 _tariffIndex,
        uint256 _payWithIndex, 
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) external; 
    
    /**
     * @notice Check that `_user` have still valid ticket for this service.
     * @dev Call this method from any context
     *
     * @param _user  - address of user who has an ticket and who trying get service 
     * @param _service - address of Service Provider
     * @return ok True in case ticket is valid
     * @return needFix True in case ticket has counter > 0
     */
    function checkUserSubscription(
        address _user, 
        address _service
    ) external view returns (bool ok, bool needFix);


    /**
     * @notice Check that `_user` have still valid ticket for this service.
     * Decrement ticket counter in case it > 0
     * @dev Call this method from ServiceProvider
     *
     * @param _user  - address of user who has an ticket and who trying get service 
     * @return ok True in case ticket is valid
     */
    function checkAndFixUserSubscription(address _user) external returns (bool ok);

    /**
     * @notice Decrement ticket counter in case it > 0
     * @dev Call this method from new SubscriptionRegistry in case of upgrade
     *
     * @param _user  - address of user who has an ticket and who trying get service 
     * @param _serviceFromProxy  - address of service from more new SubscriptionRegistry contract 
     */
    function fixUserSubscription(address _user, address _serviceFromProxy) external;


    /**
     * @notice Returns `_user` ticket for this service.
     * @dev Call this method from any context
     *
     * @param _user  - address of user who has an ticket and who trying get service 
     * @param _service - address of Service Provider
     * @return ticket
     */
    function getUserTicketForService(
        address _service,
        address _user
    ) external view returns(Ticket memory); 
    
    /**
     * @notice Returns array of Tariff for `_service`
     * @dev Call this method from any context
     *
     * @param _service - address of Service Provider
     * @return Tariff array
     */
    function getTariffsForService(address _service) external view returns (Tariff[] memory);

    /**
     * @notice Returns ticket price include any fees
     * @dev Call this method from any context
     *
     * @param _service - address of Service Provider
     * @param _tariffIndex  - index in  `availableTariffs` array 
     * @param _payWithIndex  - index in `tariff.payWith` array 
     * @return tulpe with payment token an ticket price 
     */
    function getTicketPrice(
        address _service,
        uint256 _tariffIndex,
        uint256 _payWithIndex
    ) external view returns (address, uint256);

    /**
     * @notice Returns array of Tariff for `_service` assigned to `_agent`
     * @dev Call this method from any context
     *
     * @param _agent - address of Agent
     * @param _service - address of Service Provider
     * @return Tariff array
     */
    function getAvailableAgentsTariffForService(
        address _agent, 
        address _service
    ) external view returns(Tariff[] memory); 
}

File 9 of 19 : SubscriptionRegistry.sol
// SPDX-License-Identifier: MIT
// ENVELOP(NIFTSY) Team. Subscription Registry Contract V2
pragma solidity 0.8.21;

import "Ownable.sol";
import "SafeERC20.sol";
import "ITrustedWrapper.sol";
import "LibEnvelopTypes.sol";
import "ISubscriptionRegistry.sol";

/// The subscription platform operates with the following role model 
/// (it is assumed that the actor with the role is implemented as a contract).
/// `Service Provider` is a contract whose services are sold by subscription.
/// `Agent` - a contract that sells a subscription on behalf ofservice provider. 
///  May receive sales commission
///  `Platform` - SubscriptionRegistry contract that performs processingsubscriptions, 
///  fares, tickets

    struct SubscriptionType {
        uint256 timelockPeriod;    // in seconds e.g. 3600*24*30*12 = 31104000 = 1 year
        uint256 ticketValidPeriod; // in seconds e.g. 3600*24*30    =  2592000 = 1 month
        uint256 counter;     // For case when ticket valid for N usage, e.g. for Min N NFTs          
        bool isAvailable;    // USe for stop using tariff because we can`t remove tariff from array 
        address beneficiary; // Who will receive payment for tickets
    }
    struct PayOption {
        address paymentToken;   // token contract address or zero address for native token(ETC etc)
        uint256 paymentAmount;  // ticket price exclude any fees
        uint16 agentFeePercent; // 100%-10000, 20%-2000, 3%-300 
    }

    struct Tariff {
        SubscriptionType subscription; // link to subscriptionType
        PayOption[] payWith; // payment option array. Use it for price in defferent tokens
    }

    // native subscribtionManager tickets format
    struct Ticket {
        uint256 validUntil; // Unixdate, tickets not valid after
        uint256 countsLeft; // for tarif with fixed use counter
    }

/// @title Base contract in Envelop Subscription Platform 
/// @author Envelop Team
/// @notice You can use this contract for make and operate any on-chain subscriptions
/// @dev  Contract that performs processing subscriptions, fares(tariffs), tickets
/// @custom:please see example folder.
contract SubscriptionRegistry is Ownable {
    using SafeERC20 for IERC20;

    uint256 constant public PERCENT_DENOMINATOR = 10000;

    /// @notice Envelop Multisig contract
    address public platformOwner; 
    
    /// @notice Platform owner can receive fee from each payments
    uint16 public platformFeePercent = 50; // 100%-10000, 20%-2000, 3%-300


    /// @notice address used for wrapp & lock incoming assets
    address  public mainWrapper; 
    /// @notice Used in case upgrade this contract
    address  public previousRegistry; 
    /// @notice Used in case upgrade this contract
    address  public proxyRegistry; 

    /// @notice Only white listed assets can be used on platform
    mapping(address => bool) public whiteListedForPayments;
    
    /// @notice from service(=smart contract address) to tarifs
    mapping(address => Tariff[]) public availableTariffs;

    /// @notice from service to agent to available tarifs(tarif index);
    mapping(address => mapping(address => uint256[])) public agentServiceRegistry;
     
    
    /// @notice mapping from user addres to service contract address  to ticket
    mapping(address => mapping(address => Ticket)) public userTickets;

    event PlatfromFeeChanged(uint16 indexed newPercent);
    event WhitelistPaymentTokenChanged(address indexed asset, bool indexed state);
    event TariffChanged(address indexed service, uint256 indexed tariffIndex);
    event TicketIssued(
        address indexed service, 
        address indexed agent, 
        address indexed forUser, 
        uint256 tariffIndex
    );

    constructor(address _platformOwner) {
        require(_platformOwner != address(0),'Zero platform fee receiver');
        platformOwner = _platformOwner;
    } 
   
    /**
     * @notice Add new tariff for caller
     * @dev Call this method from ServiceProvider
     * for setup new tariff 
     * using `Tariff` data type(please see above)
     *
     * @param _newTariff full encded Tariff object
     * @return last added tariff index in  Tariff[] array 
     * for current Service Provider (msg.sender)
     */
    function registerServiceTariff(Tariff calldata _newTariff) 
        external 
        returns(uint256)
    {
        // TODO
        // Tarif structure check
        // PayWith array whiteList check
        return _addTariff(msg.sender, _newTariff);
    }

    /**
     * @notice Edit tariff for caller
     * @dev Call this method from ServiceProvider
     * for setup new tariff 
     * using `Tariff` data type(please see above)
     *
     * @param _tariffIndex  - index in `availableTariffs` array 
     * @param _timelockPeriod - see SubscriptionType notice above
     * @param _ticketValidPeriod - see SubscriptionType notice above
     * @param _counter - see SubscriptionType notice above
     * @param _isAvailable - see SubscriptionType notice above
     * @param _beneficiary - see SubscriptionType notice above
     */
    function editServiceTariff(
        uint256 _tariffIndex, 
        uint256 _timelockPeriod,
        uint256 _ticketValidPeriod,
        uint256 _counter,
        bool _isAvailable,
        address _beneficiary
    ) 
        external
    {
        // TODO
        // Tariff structure check
        // PayWith array whiteList check
        _editTariff(
            msg.sender,
            _tariffIndex, 
            _timelockPeriod,
            _ticketValidPeriod,
            _counter,
            _isAvailable,
            _beneficiary
        );

    }

    
    /**
     * @notice Add tariff PayOption for exact service
     * @dev Call this method from ServiceProvider
     * for add tariff PayOption 
     *
     * @param _tariffIndex  - index in `availableTariffs` array 
     * @param _paymentToken - see PayOption notice above
     * @param _paymentAmount - see PayOption notice above
     * @param _agentFeePercent - see PayOption notice above
     * @return last added PaymentOption index in array 
     * for _tariffIndex Tariff of caller Service Provider (msg.sender)
     */
    function addTariffPayOption(
        uint256 _tariffIndex,
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) external returns(uint256)
    {
        return _addTariffPayOption(
            msg.sender,
            _tariffIndex,
            _paymentToken,
            _paymentAmount,
            _agentFeePercent
        );
    }

    /**
     * @notice Edit tariff PayOption for exact service
     * @dev Call this method from ServiceProvider
     * for edit tariff PayOption 
     *
     * @param _tariffIndex  - index in  `availableTariffs` array 
     * @param _payWithIndex  - index in `tariff.payWith` array 
     * @param _paymentToken - see PayOption notice above
     * @param _paymentAmount - see PayOption notice above
     * @param _agentFeePercent - see PayOption notice above
     * for _tariffIndex Tariff of caller Service Provider (msg.sender)
     */
    function editTariffPayOption(
        uint256 _tariffIndex,
        uint256 _payWithIndex, 
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) external 
    {
        _editTariffPayOption(
            msg.sender,
            _tariffIndex,
            _payWithIndex, 
            _paymentToken,
            _paymentAmount,
            _agentFeePercent
        );
    }

    /**
     * @notice Authorize agent for caller service provider
     * @dev Call this method from ServiceProvider
     *
     * @param _agent  - address of contract that implement Agent role 
     * @param _serviceTariffIndexes  - array of index in `availableTariffs` array
     * that available for given `_agent` 
     * @return full array of actual tarifs for this agent 
     */
    function authorizeAgentForService(
        address _agent,
        uint256[] calldata _serviceTariffIndexes
    ) external virtual returns (uint256[] memory) 
    {
        // remove previouse tariffs
        delete agentServiceRegistry[msg.sender][_agent];
        uint256[] storage currentServiceTariffsOfAgent = agentServiceRegistry[msg.sender][_agent];
        // check that adding tariffs still available
        for(uint256 i; i < _serviceTariffIndexes.length; ++ i) {
            if (availableTariffs[msg.sender][_serviceTariffIndexes[i]].subscription.isAvailable){
                currentServiceTariffsOfAgent.push(_serviceTariffIndexes[i]);
            }
        }
        return currentServiceTariffsOfAgent;
    }
    
     /**
     * @notice By Ticket for subscription
     * @dev Call this method from Agent
     *
     * @param _service  - Service Provider address 
     * @param _tariffIndex  - index in  `availableTariffs` array 
     * @param _payWithIndex  - index in `tariff.payWith` array 
     * @param _buyFor - address for whome this ticket would be bought 
     * @param _payer - address of payer for this ticket
     * @return ticket structure that would be use for validate service process
     */
    function buySubscription(
        address _service,
        uint256 _tariffIndex,
        uint256 _payWithIndex,
        address _buyFor,
        address _payer
    ) external 
      payable
      returns(Ticket memory ticket) {
        // Cant buy ticket for nobody
        require(_buyFor != address(0),'Cant buy ticket for nobody');

        require(
            availableTariffs[_service][_tariffIndex].subscription.isAvailable,
            'This subscription not available'
        );

        // Not used in this implementation
        // require(
        //     availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount > 0,
        //     'This Payment option not available'
        // );

        // Check that agent is authorized for purchace of this service
        require(
            _isAgentAuthorized(msg.sender, _service, _tariffIndex), 
            'Agent not authorized for this service tariff' 
        );
        
        (bool isValid, bool needFix) = _isTicketValid(_buyFor, _service);
        require(!isValid, 'Only one valid ticket at time');

        //lets safe user ticket (only one ticket available in this version)
        ticket = Ticket(
            availableTariffs[_service][_tariffIndex].subscription.ticketValidPeriod + block.timestamp,
            availableTariffs[_service][_tariffIndex].subscription.counter
        );
        userTickets[_buyFor][_service] = ticket;

        // Lets receive payment tokens FROM sender
        if (availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount > 0){
            _processPayment(_service, _tariffIndex, _payWithIndex, _payer);
        }
        emit TicketIssued(_service, msg.sender, _buyFor, _tariffIndex);
    }

    /**
     * @notice Check that `_user` have still valid ticket for this service.
     * Decrement ticket counter in case it > 0
     * @dev Call this method from ServiceProvider
     *
     * @param _user  - address of user who has an ticket and who trying get service 
     * @return ok True in case ticket is valid
     */
    function checkAndFixUserSubscription(
        address _user
    ) external returns (bool ok){
        
        address _service = msg.sender;
        // Check user ticket
        (bool isValid, bool needFix) = _isTicketValid(_user, msg.sender);
        
        // Proxy to previos
        if (!isValid && previousRegistry != address(0)) {
            (isValid, needFix) = ISubscriptionRegistry(previousRegistry).checkUserSubscription(
                _user, 
                _service
            );
            // Case when valid ticket stored in previousManager
            if (isValid ) {
                if (needFix){
                    ISubscriptionRegistry(previousRegistry).fixUserSubscription(
                        _user, 
                        _service
                    );
                }
                ok = true;
                return ok;
            }
        }
        require(isValid,'Valid ticket not found');
        
        // Fix action (for subscription with counter)
        if (needFix){
            _fixUserSubscription(_user, msg.sender);    
        }
                
        ok = true;
    }

     /**
     * @notice Decrement ticket counter in case it > 0
     * @dev Call this method from new SubscriptionRegistry in case of upgrade
     *
     * @param _user  - address of user who has an ticket and who trying get service 
     * @param _serviceFromProxy  - address of service from more new SubscriptionRegistry contract 
     */
    function fixUserSubscription(
        address _user,
        address _serviceFromProxy
    ) public {
        require(proxyRegistry !=address(0) && msg.sender == proxyRegistry,
            'Only for future registry'
        );
        _fixUserSubscription(_user, _serviceFromProxy);
    }

    ////////////////////////////////////////////////////////////////
    
    /**
     * @notice Check that `_user` have still valid ticket for this service.
     * @dev Call this method from any context
     *
     * @param _user  - address of user who has an ticket and who trying get service 
     * @param _service - address of Service Provider
     * @return ok True in case ticket is valid
     * @return needFix True in case ticket has counter > 0
     */
    function checkUserSubscription(
        address _user, 
        address _service
    ) external view returns (bool ok, bool needFix) {
        (ok, needFix)  = _isTicketValid(_user, _service);
        if (!ok && previousRegistry != address(0)) {
            (ok, needFix) = ISubscriptionRegistry(previousRegistry).checkUserSubscription(
                _user, 
                _service
            );
        }
    }

    /**
     * @notice Returns `_user` ticket for this service.
     * @dev Call this method from any context
     *
     * @param _user  - address of user who has an ticket and who trying get service 
     * @param _service - address of Service Provider
     * @return ticket
     */
    function getUserTicketForService(
        address _service,
        address _user
    ) public view returns(Ticket memory) 
    {
        return userTickets[_user][_service];
    }

    /**
     * @notice Returns array of Tariff for `_service`
     * @dev Call this method from any context
     *
     * @param _service - address of Service Provider
     * @return Tariff array
     */
    function getTariffsForService(address _service) external view returns (Tariff[] memory) {
        return availableTariffs[_service];
    }

    /**
     * @notice Returns ticket price include any fees
     * @dev Call this method from any context
     *
     * @param _service - address of Service Provider
     * @param _tariffIndex  - index in  `availableTariffs` array 
     * @param _payWithIndex  - index in `tariff.payWith` array 
     * @return tulpe with payment token an ticket price 
     */
    function getTicketPrice(
        address _service,
        uint256 _tariffIndex,
        uint256 _payWithIndex
    ) public view virtual returns (address, uint256) 
    {
        if (availableTariffs[_service][_tariffIndex].subscription.timelockPeriod != 0)
        {
            return(
                availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken,
                availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
            );
        } else {
            return(
                availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken,
                availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
                + availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
                    *availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].agentFeePercent
                    /PERCENT_DENOMINATOR
                + availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
                        *_platformFeePercent(_service, _tariffIndex, _payWithIndex) 
                        /PERCENT_DENOMINATOR
            );
        }
    }

    /**
     * @notice Returns array of Tariff for `_service` assigned to `_agent`
     * @dev Call this method from any context
     *
     * @param _agent - address of Agent
     * @param _service - address of Service Provider
     * @return tuple with two arrays: indexes and Tariffs
     */
    function getAvailableAgentsTariffForService(
        address _agent, 
        address _service
    ) external view virtual returns(uint256[] memory, Tariff[] memory) 
    {
        //First need get count of tarifs that still available
        uint256 availableCount;
        for (uint256 i; i < agentServiceRegistry[_service][_agent].length; ++i){
            if (availableTariffs[_service][
                  agentServiceRegistry[_service][_agent][i]
                ].subscription.isAvailable
            ) {++availableCount;}
        }
        
        Tariff[]  memory tariffs = new Tariff[](availableCount);
        uint256[] memory indexes = new uint256[](availableCount);
        for (uint256 i; i < agentServiceRegistry[_service][_agent].length; ++i){
            if (availableTariffs[_service][
                  agentServiceRegistry[_service][_agent][i]
                ].subscription.isAvailable
            ) 
            {
                tariffs[availableCount - 1] = availableTariffs[_service][
                  agentServiceRegistry[_service][_agent][i]
                ];
                indexes[availableCount - 1] = agentServiceRegistry[_service][_agent][i];
                --availableCount;
            }
        }
        return (indexes, tariffs);
    }    
    ////////////////////////////////////////////////////////////////
    //////////     Admins                                     //////
    ////////////////////////////////////////////////////////////////

    function setAssetForPaymentState(address _asset, bool _isEnable)
        external onlyOwner 
    {
        whiteListedForPayments[_asset] = _isEnable;
        emit WhitelistPaymentTokenChanged(_asset, _isEnable);
    }

    function setMainWrapper(address _wrapper) external onlyOwner {
        mainWrapper = _wrapper;
    }

    function setPlatformOwner(address _newOwner) external {
        require(msg.sender == platformOwner, 'Only platform owner');
        require(_newOwner != address(0),'Zero platform fee receiver');
        platformOwner = _newOwner;
    }

    function setPlatformFeePercent(uint16 _newPercent) external {
        require(msg.sender == platformOwner, 'Only platform owner');
        platformFeePercent = _newPercent;
        emit PlatfromFeeChanged(platformFeePercent);
    }

    

    function setPreviousRegistry(address _registry) external onlyOwner {
        previousRegistry = _registry;
    }

    function setProxyRegistry(address _registry) external onlyOwner {
        proxyRegistry = _registry;
    }
    /////////////////////////////////////////////////////////////////////
    
    function _processPayment(
        address _service,
        uint256 _tariffIndex,
        uint256 _payWithIndex,
        address _payer
    ) 
        internal 
        virtual 
        returns(bool)
    {
        // there are two payment method for this implementation.
        // 1. with wrap and lock in asset (no fees)
        // 2. simple payment (agent & platform fee enabled)
        if (availableTariffs[_service][_tariffIndex].subscription.timelockPeriod != 0){
            require(msg.value == 0, 'Ether Not accepted in this method');
            // 1. with wrap and lock in asset
            IERC20(
                availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
            ).safeTransferFrom(
                _payer, 
                address(this),
                availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
            );

            // Lets approve received for wrap 
            IERC20(
                availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
            ).safeApprove(
                mainWrapper,
                availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
            );

            // Lets wrap with timelock and appropriate params
            ETypes.INData memory _inData;
            ETypes.AssetItem[] memory _collateralERC20 = new ETypes.AssetItem[](1);
            ETypes.Lock[] memory timeLock =  new ETypes.Lock[](1);
            // Only need set timelock for this wNFT
            timeLock[0] = ETypes.Lock(
                0x00, // timelock
                availableTariffs[_service][_tariffIndex].subscription.timelockPeriod + block.timestamp
            ); 
            _inData = ETypes.INData(
                ETypes.AssetItem(
                    ETypes.Asset(ETypes.AssetType.EMPTY, address(0)),
                    0,0
                ),          // INAsset
                address(0), // Unwrap destinition    
                new ETypes.Fee[](0), // Fees
                //new ETypes.Lock[](0), // Locks
                timeLock,
                new ETypes.Royalty[](0), // Royalties
                ETypes.AssetType.ERC721, // Out type
                0, // Out Balance
                0x0000 // Rules
            );

            _collateralERC20[0] = ETypes.AssetItem(
                ETypes.Asset(
                    ETypes.AssetType.ERC20,
                    availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
                ),
                0,
                availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
            );
            
            ITrustedWrapper(mainWrapper).wrap(
                _inData,
                _collateralERC20,
                _payer
            );

        } else {
            // 2. simple payment
            if (availableTariffs[_service][_tariffIndex]
                .payWith[_payWithIndex]
                .paymentToken != address(0)
            ) 
            {
                // pay with erc20 
                require(msg.value == 0, 'Ether Not accepted in this method');
                // 2.1. Body payment  
                IERC20(
                    availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
                ).safeTransferFrom(
                    _payer, 
                    availableTariffs[_service][_tariffIndex].subscription.beneficiary,
                    availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
                );

                // 2.2. Agent fee payment
                IERC20(
                    availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
                ).safeTransferFrom(
                    _payer, 
                    msg.sender,
                    availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
                     *availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].agentFeePercent
                     /PERCENT_DENOMINATOR
                );

                // 2.3. Platform fee 
                uint256 _pFee = _platformFeePercent(_service, _tariffIndex, _payWithIndex); 
                if (_pFee > 0) {
                    IERC20(
                        availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
                    ).safeTransferFrom(
                        _payer, 
                        platformOwner, //
                        availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
                          *_pFee
                          /PERCENT_DENOMINATOR
                    );
                }

            } else {
                // pay with native token(eth, bnb, etc)
                (, uint256 needPay) = getTicketPrice(_service, _tariffIndex,_payWithIndex);
                require(msg.value >= needPay, 'Not enough ether');
                // 2.4. Body ether payment
                sendValue(
                    payable(availableTariffs[_service][_tariffIndex].subscription.beneficiary),
                    availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
                );

                // 2.5. Agent fee payment
                sendValue(
                    payable(msg.sender),
                    availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
                      *availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].agentFeePercent
                      /PERCENT_DENOMINATOR
                );

                // 2.3. Platform fee 
                uint256 _pFee = _platformFeePercent(_service, _tariffIndex, _payWithIndex); 
                if (_pFee > 0) {

                    sendValue(
                        payable(platformOwner),
                        availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
                          *_pFee
                          /PERCENT_DENOMINATOR
                    );
                }
                // return change
                if  ((msg.value - needPay) > 0) {
                    address payable s = payable(_payer);
                    s.transfer(msg.value - needPay);
                }
            }
        }
    }

    // In this impementation params not used. 
    // Can be ovveriden in other cases
    function _platformFeePercent(
        address _service, 
        uint256 _tariffIndex, 
        uint256  _payWithIndex
    ) internal view virtual returns(uint256) 
    {
        return platformFeePercent;
    }

    function _addTariff(address _service, Tariff calldata _newTariff) 
        internal returns(uint256) 
    {
        require (_newTariff.payWith.length > 0, 'No payment method');
        for (uint256 i; i < _newTariff.payWith.length; ++i){
            require(
                whiteListedForPayments[_newTariff.payWith[i].paymentToken],
                'Not whitelisted for payments'
            );      
        }
        require(
            _newTariff.subscription.ticketValidPeriod > 0 
            || _newTariff.subscription.counter > 0,
            'Tariff has no valid ticket option'  
        );
        availableTariffs[_service].push(_newTariff);
        emit TariffChanged(_service, availableTariffs[_service].length - 1);
        return availableTariffs[_service].length - 1;
    }


    function _editTariff(
        address _service,
        uint256 _tariffIndex, 
        uint256 _timelockPeriod,
        uint256 _ticketValidPeriod,
        uint256 _counter,
        bool _isAvailable,
        address _beneficiary
    ) internal  
    {
        availableTariffs[_service][_tariffIndex].subscription.timelockPeriod    = _timelockPeriod;
        availableTariffs[_service][_tariffIndex].subscription.ticketValidPeriod = _ticketValidPeriod;
        availableTariffs[_service][_tariffIndex].subscription.counter = _counter;
        availableTariffs[_service][_tariffIndex].subscription.isAvailable = _isAvailable;    
        availableTariffs[_service][_tariffIndex].subscription.beneficiary = _beneficiary;    
        emit TariffChanged(_service, _tariffIndex);
    }
   
    function _addTariffPayOption(
        address _service,
        uint256 _tariffIndex,
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) internal returns(uint256)
    {
        require(whiteListedForPayments[_paymentToken], 'Not whitelisted for payments');
        availableTariffs[_service][_tariffIndex].payWith.push(
            PayOption(_paymentToken, _paymentAmount, _agentFeePercent)
        ); 
        emit TariffChanged(_service, _tariffIndex);
        return availableTariffs[_service][_tariffIndex].payWith.length - 1;
    }

    function _editTariffPayOption(
        address _service,
        uint256 _tariffIndex,
        uint256 _payWithIndex, 
        address _paymentToken,
        uint256 _paymentAmount,
        uint16 _agentFeePercent
    ) internal  
    {
        require(whiteListedForPayments[_paymentToken], 'Not whitelisted for payments');
        availableTariffs[_service][_tariffIndex].payWith[_payWithIndex] 
        = PayOption(_paymentToken, _paymentAmount, _agentFeePercent);  
        emit TariffChanged(_service, _tariffIndex);  
    }

    function _fixUserSubscription(
        address _user,
        address _service
    ) internal {
       
        // Fix action (for subscription with counter)
        if (userTickets[_user][_service].countsLeft > 0) {
            -- userTickets[_user][_service].countsLeft; 
        }
    }

        
   function _isTicketValid(address _user, address _service) 
        internal 
        view 
        returns (bool isValid, bool needFix ) 
    {
        isValid =  userTickets[_user][_service].validUntil > block.timestamp 
            || userTickets[_user][_service].countsLeft > 0;
        needFix =  userTickets[_user][_service].countsLeft > 0;   
    }

    function _isAgentAuthorized(
        address _agent, 
        address _service, 
        uint256 _tariffIndex
    ) 
        internal
        view
        returns(bool authorized)
    {
        for (uint256 i; i < agentServiceRegistry[_service][_agent].length; ++ i){
            if (agentServiceRegistry[_service][_agent][i] == _tariffIndex){
                authorized = true;
                return authorized;
            }
        }
    }

    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");
    }
}

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

pragma solidity ^0.8.0;

import "IERC20.sol";
import "draft-IERC20Permit.sol";
import "Address.sol";

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

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

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

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

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

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

    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

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

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

File 11 of 19 : 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 12 of 19 : draft-IERC20Permit.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 IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

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

File 13 of 19 : Address.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 Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [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 Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

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

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

File 14 of 19 : ITrustedWrapper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

import "IWrapper.sol";

interface ITrustedWrapper is IWrapper  {

    function trustedOperator() external view returns(address);    
    
    function wrapUnsafe(
        ETypes.INData calldata _inData, 
        ETypes.AssetItem[] calldata _collateral, 
        address _wrappFor
    ) 
        external
        payable
        returns (ETypes.AssetItem memory); 

    function transferIn(
        ETypes.AssetItem memory _assetItem,
        address _from
    ) 
        external
        payable  
    returns (uint256 _transferedValue);
   
}

File 15 of 19 : IWrapper.sol
// SPDX-License-Identifier: MIT

pragma solidity 0.8.21;

//import "IERC721Enumerable.sol";
import "LibEnvelopTypes.sol";

interface IWrapper  {

    event WrappedV1(
        address indexed inAssetAddress,
        address indexed outAssetAddress, 
        uint256 indexed inAssetTokenId, 
        uint256 outTokenId,
        address wnftFirstOwner,
        uint256 nativeCollateralAmount,
        bytes2  rules
    );

    event UnWrappedV1(
        address indexed wrappedAddress,
        address indexed originalAddress,
        uint256 indexed wrappedId, 
        uint256 originalTokenId, 
        address beneficiary, 
        uint256 nativeCollateralAmount,
        bytes2  rules 
    );

    event CollateralAdded(
        address indexed wrappedAddress,
        uint256 indexed wrappedId,
        uint8   assetType,
        address collateralAddress,
        uint256 collateralTokenId,
        uint256 collateralBalance
    );

    event PartialUnWrapp(
        address indexed wrappedAddress,
        uint256 indexed wrappedId,
        uint256 lastCollateralIndex
    );
    event SuspiciousFail(
        address indexed wrappedAddress,
        uint256 indexed wrappedId, 
        address indexed failedContractAddress
    );

    event EnvelopFee(
        address indexed receiver,
        address indexed wNFTConatract,
        uint256 indexed wNFTTokenId,
        uint256 amount
    );

    function wrap(
        ETypes.INData calldata _inData, 
        ETypes.AssetItem[] calldata _collateral, 
        address _wrappFor
    ) 
        external 
        payable 
    returns (ETypes.AssetItem memory);

    // function wrapUnsafe(
    //     ETypes.INData calldata _inData, 
    //     ETypes.AssetItem[] calldata _collateral, 
    //     address _wrappFor
    // ) 
    //     external 
    //     payable
    // returns (ETypes.AssetItem memory);

    function addCollateral(
        address _wNFTAddress, 
        uint256 _wNFTTokenId, 
        ETypes.AssetItem[] calldata _collateral
    ) external payable;

    // function addCollateralUnsafe(
    //     address _wNFTAddress, 
    //     uint256 _wNFTTokenId, 
    //     ETypes.AssetItem[] calldata _collateral
    // ) 
    //     external 
    //     payable;

    function unWrap(
        address _wNFTAddress, 
        uint256 _wNFTTokenId
    ) external; 

    function unWrap(
        ETypes.AssetType _wNFTType, 
        address _wNFTAddress, 
        uint256 _wNFTTokenId
    ) external; 

    function unWrap(
        ETypes.AssetType _wNFTType, 
        address _wNFTAddress, 
        uint256 _wNFTTokenId, 
        bool _isEmergency
    ) external;

    function chargeFees(
        address _wNFTAddress, 
        uint256 _wNFTTokenId, 
        address _from, 
        address _to,
        bytes1 _feeType
    ) 
        external  
        returns (bool);   

    ////////////////////////////////////////////////////////////////////// 
    
    function MAX_COLLATERAL_SLOTS() external view returns (uint256);
    function protocolTechToken() external view returns (address);
    function protocolWhiteList() external view returns (address);

    function getWrappedToken(address _wNFTAddress, uint256 _wNFTTokenId) 
        external 
        view 
        returns (ETypes.WNFT memory);

    function getOriginalURI(address _wNFTAddress, uint256 _wNFTTokenId) 
        external 
        view 
        returns(string memory); 
    
    function getCollateralBalanceAndIndex(
        address _wNFTAddress, 
        uint256 _wNFTTokenId,
        ETypes.AssetType _collateralType, 
        address _erc,
        uint256 _tokenId
    ) external view returns (uint256, uint256);
   
}

File 16 of 19 : IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

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

pragma solidity ^0.8.0;

import "IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @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 18 of 19 : IERC165.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 IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 19 of 19 : LibEnvelopTypes.sol
// SPDX-License-Identifier: MIT
// ENVELOP(NIFTSY) protocol V1 for NFT. 
pragma solidity 0.8.21;

/// @title Flibrary ETypes in Envelop PrtocolV1 
/// @author Envelop Team
/// @notice This contract implement main protocol's data types
library ETypes {

    enum AssetType {EMPTY, NATIVE, ERC20, ERC721, ERC1155, FUTURE1, FUTURE2, FUTURE3}
    
    struct Asset {
        AssetType assetType;
        address contractAddress;
    }

    struct AssetItem {
        Asset asset;
        uint256 tokenId;
        uint256 amount;
    }

    struct NFTItem {
        address contractAddress;
        uint256 tokenId;   
    }

    struct Fee {
        bytes1 feeType;
        uint256 param;
        address token; 
    }

    struct Lock {
        bytes1 lockType;
        uint256 param; 
    }

    struct Royalty {
        address beneficiary;
        uint16 percent;
    }

    struct WNFT {
        AssetItem inAsset;
        AssetItem[] collateral;
        address unWrapDestination;
        Fee[] fees;
        Lock[] locks;
        Royalty[] royalties;
        bytes2 rules;

    }

    struct INData {
        AssetItem inAsset;
        address unWrapDestination;
        Fee[] fees;
        Lock[] locks;
        Royalty[] royalties;
        AssetType outType;
        uint256 outBalance;      //0- for 721 and any amount for 1155
        bytes2 rules;

    }

    struct WhiteListItem {
        bool enabledForFee;
        bool enabledForCollateral;
        bool enabledRemoveFromCollateral;
        address transferFeeModel;
    }

    struct Rules {
        bytes2 onlythis;
        bytes2 disabled;
    }

}

File 20 of 19 : IUsersSBTCollectionFactory.sol
// SPDX-License-Identifier: MIT
// For access to Factory from external contracts

pragma solidity 0.8.21;

interface IUsersSBTCollectionFactory {
    function deployProxyFor(
        address _implAddress, 
        address _creator,
        string memory name_,
        string memory symbol_,
        string memory _baseurl,
        address _wrapper
    ) external returns(address proxy);
}

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

Contract ABI

[{"inputs":[{"internalType":"address","name":"_subscrRegistry","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"User","type":"address"},{"internalType":"address","name":"Contract","type":"address"}],"name":"Unauthorized","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[{"components":[{"internalType":"enum UsersSBTCollectionRegistry.AssetType","name":"assetType","type":"uint8"},{"internalType":"address","name":"contractAddress","type":"address"}],"internalType":"struct UsersSBTCollectionRegistry.Asset","name":"_impl","type":"tuple"}],"name":"addImplementation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tariffIndex","type":"uint256"},{"internalType":"address","name":"_paymentToken","type":"address"},{"internalType":"uint256","name":"_paymentAmount","type":"uint256"},{"internalType":"uint16","name":"_agentFeePercent","type":"uint16"}],"name":"addPayOption","outputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_agent","type":"address"},{"internalType":"uint256[]","name":"_serviceTariffIndexes","type":"uint256[]"}],"name":"authorizeAgentForService","outputs":[{"internalType":"uint256[]","name":"actualTariffs","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"checkUserSubscription","outputs":[{"internalType":"bool","name":"ok","type":"bool"},{"internalType":"bool","name":"needFix","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"collectionRegistry","outputs":[{"internalType":"enum UsersSBTCollectionRegistry.AssetType","name":"assetType","type":"uint8"},{"internalType":"address","name":"contractAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_implAddress","type":"address"},{"internalType":"address","name":"_creator","type":"address"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"string","name":"_baseurl","type":"string"},{"internalType":"address","name":"_wrapper","type":"address"},{"internalType":"address","name":"_ticketContract","type":"address"},{"components":[{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"useTicket","type":"tuple"},{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"certificate","type":"tuple"},{"internalType":"bytes2","name":"sbtRules","type":"bytes2"},{"internalType":"address","name":"tickets","type":"address"}],"internalType":"struct EventManager.EventDates","name":"_eventDates","type":"tuple"}],"name":"deployNewCollection","outputs":[{"internalType":"address","name":"newCollection","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_implAddress","type":"address"},{"internalType":"address","name":"_creator","type":"address"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"string","name":"_baseurl","type":"string"},{"internalType":"address","name":"_wrapper","type":"address"}],"name":"deployNewCollection","outputs":[{"internalType":"address","name":"newCollection","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_eventContract","type":"address"},{"components":[{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"useTicket","type":"tuple"},{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"certificate","type":"tuple"},{"internalType":"bytes2","name":"sbtRules","type":"bytes2"},{"internalType":"address","name":"tickets","type":"address"}],"internalType":"struct EventManager.EventDates","name":"_newEventDates","type":"tuple"}],"name":"editDatesForEvent","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tariffIndex","type":"uint256"},{"internalType":"uint256","name":"_payWithIndex","type":"uint256"},{"internalType":"address","name":"_paymentToken","type":"address"},{"internalType":"uint256","name":"_paymentAmount","type":"uint256"},{"internalType":"uint16","name":"_agentFeePercent","type":"uint16"}],"name":"editPayOption","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_tariffIndex","type":"uint256"},{"internalType":"uint256","name":"_timelockPeriod","type":"uint256"},{"internalType":"uint256","name":"_ticketValidPeriod","type":"uint256"},{"internalType":"uint256","name":"_counter","type":"uint256"},{"internalType":"bool","name":"_isAvailable","type":"bool"},{"internalType":"address","name":"_beneficiary","type":"address"}],"name":"editServiceTariff","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"events","outputs":[{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"useTicket","type":"tuple"},{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"certificate","type":"tuple"},{"internalType":"bytes2","name":"sbtRules","type":"bytes2"},{"internalType":"address","name":"tickets","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"contract IUsersSBTCollectionFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_eventContract","type":"address"}],"name":"getDataForEvent","outputs":[{"components":[{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"useTicket","type":"tuple"},{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"certificate","type":"tuple"},{"internalType":"bytes2","name":"sbtRules","type":"bytes2"},{"internalType":"address","name":"tickets","type":"address"}],"internalType":"struct EventManager.EventDates","name":"d","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_ticketContract","type":"address"}],"name":"getEventsForTicket","outputs":[{"internalType":"address[]","name":"e","type":"address[]"},{"components":[{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"useTicket","type":"tuple"},{"components":[{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"finish","type":"uint256"}],"internalType":"struct EventManager.Period","name":"certificate","type":"tuple"},{"internalType":"bytes2","name":"sbtRules","type":"bytes2"},{"internalType":"address","name":"tickets","type":"address"}],"internalType":"struct EventManager.EventDates[]","name":"d","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getSupportedImplementation","outputs":[{"components":[{"internalType":"enum UsersSBTCollectionRegistry.AssetType","name":"assetType","type":"uint8"},{"internalType":"address","name":"contractAddress","type":"address"}],"internalType":"struct UsersSBTCollectionRegistry.Asset[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_user","type":"address"}],"name":"getUsersCollections","outputs":[{"components":[{"internalType":"enum UsersSBTCollectionRegistry.AssetType","name":"assetType","type":"uint8"},{"internalType":"address","name":"contractAddress","type":"address"}],"internalType":"struct UsersSBTCollectionRegistry.Asset[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isEnabled","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_impl","type":"address"}],"name":"isImplementationSupported","outputs":[{"internalType":"bool","name":"isSupported","type":"bool"},{"internalType":"uint256","name":"index","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_eventContract","type":"address"}],"name":"isRulesUpdateEnabled","outputs":[{"internalType":"bytes2","name":"rules","type":"bytes2"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_ticketContract","type":"address"},{"internalType":"address","name":"_eventContract","type":"address"}],"name":"isWrapEnabled","outputs":[{"internalType":"bool","name":"enabled","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"uint256","name":"timelockPeriod","type":"uint256"},{"internalType":"uint256","name":"ticketValidPeriod","type":"uint256"},{"internalType":"uint256","name":"counter","type":"uint256"},{"internalType":"bool","name":"isAvailable","type":"bool"},{"internalType":"address","name":"beneficiary","type":"address"}],"internalType":"struct SubscriptionType","name":"subscription","type":"tuple"},{"components":[{"internalType":"address","name":"paymentToken","type":"address"},{"internalType":"uint256","name":"paymentAmount","type":"uint256"},{"internalType":"uint16","name":"agentFeePercent","type":"uint16"}],"internalType":"struct PayOption[]","name":"payWith","type":"tuple[]"}],"internalType":"struct Tariff","name":"_newTariff","type":"tuple"}],"name":"newTariff","outputs":[{"internalType":"uint256","name":"tariffIndex","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"uint256","name":"timelockPeriod","type":"uint256"},{"internalType":"uint256","name":"ticketValidPeriod","type":"uint256"},{"internalType":"uint256","name":"counter","type":"uint256"},{"internalType":"bool","name":"isAvailable","type":"bool"},{"internalType":"address","name":"beneficiary","type":"address"}],"internalType":"struct SubscriptionType","name":"subscription","type":"tuple"},{"components":[{"internalType":"address","name":"paymentToken","type":"address"},{"internalType":"uint256","name":"paymentAmount","type":"uint256"},{"internalType":"uint16","name":"agentFeePercent","type":"uint16"}],"internalType":"struct PayOption[]","name":"payWith","type":"tuple[]"}],"internalType":"struct Tariff","name":"_newTariff","type":"tuple"}],"name":"registerServiceTariff","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_index","type":"uint256"}],"name":"removeImplementationByIndex","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"serviceProvider","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_factory","type":"address"}],"name":"setFactory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_isEnable","type":"bool"}],"name":"setSubscriptionOnOff","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_subscrRegistry","type":"address"}],"name":"setSubscriptionRegistry","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"subscriptionRegistry","outputs":[{"internalType":"contract ISubscriptionRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"supportedImplementations","outputs":[{"internalType":"enum UsersSBTCollectionRegistry.AssetType","name":"assetType","type":"uint8"},{"internalType":"address","name":"contractAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"ticketsForEvents","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60806040526001805460ff60a01b1916600160a01b1790553480156200002457600080fd5b50604051620026bb380380620026bb833981016040819052620000479162000130565b8080806001600160a01b038116620000955760405162461bcd60e51b815260206004820152600d60248201526c4e6f6e207a65726f206f6e6c7960981b604482015260640160405180910390fd5b60008054306001600160a01b031991821617909155600180549091166001600160a01b0392909216919091179055620000d5620000cf3390565b620000de565b50505062000162565b600280546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6000602082840312156200014357600080fd5b81516001600160a01b03811681146200015b57600080fd5b9392505050565b61254980620001726000396000f3fe608060405234801561001057600080fd5b50600436106101fb5760003560e01c80636aa633b61161011a578063abba145b116100ad578063d259c8a51161007c578063d259c8a51461052a578063d376e42214610554578063e1e3c08d14610580578063f2fde38b14610593578063fb8adca4146105a657600080fd5b8063abba145b146104de578063b22f6d26146104f1578063c2666fed14610504578063c45a01551461051757600080fd5b80638da5cb5b116100e95780638da5cb5b14610487578063991f1358146104985780639ec30e4a146104ab578063a3fafd05146104be57600080fd5b80636aa633b614610448578063715018a61461046c57806378451d00146102555780638d69e95e1461047457600080fd5b80632934092f116101925780635bb47808116101615780635bb47808146103d75780635d8a30b4146103ea5780635f098cc6146103fd57806363df3d171461042757600080fd5b80632934092f146102e45780633194bfe1146102f95780633317b649146103b15780635751869b146103c457600080fd5b80631fd340a3116101ce5780631fd340a31461028b5780632063b112146102ab57806320da7170146102be57806326e3c30a146102d157600080fd5b806302f43e591461020057806303153be01461022a5780630c5620d6146102555780631f16aef314610276575b600080fd5b61021361020e36600461182f565b6105b9565b604051610221929190611880565b60405180910390f35b61023d610238366004611a04565b6105ec565b6040516001600160a01b039091168152602001610221565b610268610263366004611bce565b610661565b604051908152602001610221565b610289610284366004611c9c565b61067a565b005b61029e610299366004611cfa565b610698565b6040516102219190611d6c565b6102896102b936600461182f565b610725565b60015461023d906001600160a01b031681565b6102896102df366004611d7a565b610810565b6102ec610975565b6040516102219190611d8c565b610367610307366004611cfa565b60076020908152600091825260409182902082518084018452815481526001820154818401528351808501909452600282015484526003820154928401929092526004015490919060f081901b906201000090046001600160a01b031684565b604080518551815260209586015186820152845191810191909152939092015160608401526001600160f01b03191660808301526001600160a01b031660a082015260c001610221565b6102896103bf366004611deb565b610a11565b6102896103d2366004611e21565b610b56565b6102896103e5366004611cfa565b610b72565b61023d6103f8366004611e73565b610b9c565b61041061040b366004611cfa565b610bd4565b604080519215158352602083019190915201610221565b61043a610435366004611cfa565b610c3d565b604051610221929190611e9f565b60015461045c90600160a01b900460ff1681565b6040519015158152602001610221565b610289610df6565b60005461023d906001600160a01b031681565b6002546001600160a01b031661023d565b61045c6104a6366004611f20565b610e0f565b6102896104b9366004611cfa565b610f21565b6104d16104cc366004611f59565b610f4b565b604051610221919061203a565b6102896104ec36600461204d565b610f66565b6102136104ff366004611e73565b610f8c565b61023d61051236600461206a565b610fcd565b60055461023d906001600160a01b031681565b61053d610538366004611cfa565b6111b3565b604080519215158352901515602083015201610221565b610567610562366004611cfa565b6111c9565b6040516001600160f01b03199091168152602001610221565b6102ec61058e366004611cfa565b611235565b6102896105a1366004611cfa565b6112e7565b6102686105b436600461211d565b611360565b600381815481106105c957600080fd5b60009182526020909120015460ff8116915061010090046001600160a01b031682565b60006105fc898989898989610fcd565b6001600160a01b03848116600090815260066020908152604080832080546001810182559084528284200180546001600160a01b0319169486169485179055928252600790522090915082906106528282612165565b90505098975050505050505050565b600061066b61137f565b610674826113d9565b92915050565b61068261137f565b61069086868686868661144c565b505050505050565b6106a06117db565b506001600160a01b03908116600090815260076020908152604091829020825160c081018452815460808201908152600183015460a08301528152835180850185526002830154815260038301548185015292810192909252600401546001600160f01b031960f082901b169282019290925262010000909104909116606082015290565b61072d61137f565b60035461073c906001906121f8565b81146107da5760038054610752906001906121f8565b815481106107625761076261220b565b906000526020600020016003828154811061077f5761077f61220b565b60009182526020909120825491018054909160ff1690829060ff191660018360078111156107af576107af611848565b021790555090548154610100600160a81b031916610100918290046001600160a01b03169091021790555b60038054806107eb576107eb612221565b600082815260209020810160001990810180546001600160a81b031916905501905550565b61081861137f565b60005b6003548110156108bd576108356040830160208401611cfa565b6001600160a01b0316600382815481106108515761085161220b565b60009182526020909120015461010090046001600160a01b0316036108ad5760405162461bcd60e51b815260206004820152600d60248201526c105b1c9958591e48195e1a5cdd609a1b60448201526064015b60405180910390fd5b6108b681612237565b905061081b565b5060408051808201909152600390806108d96020850185612250565b60078111156108ea576108ea611848565b81526020018360200160208101906109029190611cfa565b6001600160a01b031690528154600181810184556000938452602090932082519101805492939092839160ff199091169083600781111561094557610945611848565b02179055506020919091015181546001600160a01b0390911661010002610100600160a81b031990911617905550565b60606003805480602002602001604051908101604052809291908181526020016000905b82821015610a0857600084815260209020604080518082019091529083018054829060ff1660078111156109cf576109cf611848565b60078111156109e0576109e0611848565b8152905461010090046001600160a01b03166020918201529082526001929092019101610999565b50505050905090565b33600090815260046020908152604080832080548251818502810185019093528083529192909190849084015b82821015610aad57600084815260209020604080518082019091529083018054829060ff166007811115610a7457610a74611848565b6007811115610a8557610a85611848565b8152905461010090046001600160a01b03166020918201529082526001929092019101610a3e565b50505050905060005b8151811015610b2b57836001600160a01b0316828281518110610adb57610adb61220b565b6020026020010151602001516001600160a01b031603610b19576001600160a01b038416600090815260076020526040902083906106908282612165565b80610b2381612237565b915050610ab6565b5060405163295a81c160e01b81523360048201526001600160a01b03841660248201526044016108a4565b610b5e61137f565b610b6b85858585856114d7565b5050505050565b610b7a61137f565b600580546001600160a01b0319166001600160a01b0392909216919091179055565b60066020528160005260406000208181548110610bb857600080fd5b6000918252602090912001546001600160a01b03169150829050565b60008060005b600354811015610c375760038181548110610bf757610bf761220b565b6000918252602090912001546001600160a01b03610100909104811690851603610c275760019250809150610c37565b610c3081612237565b9050610bda565b50915091565b60608060066000846001600160a01b03166001600160a01b03168152602001908152602001600020805480602002602001604051908101604052809291908181526020018280548015610cb957602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610c9b575b50505050509150815167ffffffffffffffff811115610cda57610cda6118c6565b604051908082528060200260200182016040528015610d1357816020015b610d006117db565b815260200190600190039081610cf85790505b50905060005b8251811015610c375760076000848381518110610d3857610d3861220b565b6020908102919091018101516001600160a01b039081168352828201939093526040918201600020825160c081018452815460808201908152600183015460a08301528152835180850185526002830154815260038301548185015292810192909252600401546001600160f01b031960f082901b16928201929092526201000090910490911660608201528251839083908110610dd857610dd861220b565b60200260200101819052508080610dee90612237565b915050610d19565b610dfe61137f565b610e08600061155c565b565b919050565b6001600160a01b038216600090815260066020908152604080832080548251818502810185019093528083528493830182828015610e7657602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610e58575b5050505050905060005b8151811015610f1957836001600160a01b0316828281518110610ea557610ea561220b565b60200260200101516001600160a01b031603610f07576001600160a01b0384166000908152600760205260409020544210801590610efd57506001600160a01b03841660009081526007602052604090206001015442105b15610f0757600192505b80610f1181612237565b915050610e80565b505092915050565b610f2961137f565b600180546001600160a01b0319166001600160a01b0392909216919091179055565b6060610f5561137f565b610f5f83836115ae565b9392505050565b610f6e61137f565b60018054911515600160a01b0260ff60a01b19909216919091179055565b60046020528160005260406000208181548110610fa857600080fd5b60009182526020909120015460ff8116925061010090046001600160a01b0316905082565b6000806000610fdb89610bd4565b91509150816110415760405162461bcd60e51b815260206004820152602c60248201527f5468697320696d706c656d656e746174696f6e2061646472657373206973206e60448201526b1bdd081cdd5c1c1bdc9d195960a21b60648201526084016108a4565b61104a33611628565b50600554604051600162030bd960e01b031981526001600160a01b039091169063fffcf42790611088908c908c908c908c908c908c906004016122b7565b6020604051808303816000875af11580156110a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110cb919061231e565b925060046000896001600160a01b03166001600160a01b031681526020019081526020016000206040518060400160405280600384815481106111105761111061220b565b60009182526020909120015460ff16600781111561113057611130611848565b81526001600160a01b038616602091820152825460018181018555600094855291909320825193018054929390929091839160ff19169083600781111561117957611179611848565b02179055506020919091015181546001600160a01b0390911661010002610100600160a81b03199091161790555090979650505050505050565b6000806111bf836116b5565b9094909350915050565b6001600160a01b038116600090815260076020526040812060020154421080159061120e57506001600160a01b03821660009081526007602052604090206003015442105b15610e0a57506001600160a01b031660009081526007602052604090206004015460f01b90565b6001600160a01b0381166000908152600460209081526040808320805482518185028101850190935280835260609492939192909184015b828210156112dc57600084815260209020604080518082019091529083018054829060ff1660078111156112a3576112a3611848565b60078111156112b4576112b4611848565b8152905461010090046001600160a01b0316602091820152908252600192909201910161126d565b505050509050919050565b6112ef61137f565b6001600160a01b0381166113545760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016108a4565b61135d8161155c565b50565b600061136a61137f565b61137685858585611752565b95945050505050565b6002546001600160a01b03163314610e085760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016108a4565b6001546040516278451d60e81b81526000916001600160a01b0316906378451d009061140990859060040161233b565b6020604051808303816000875af1158015611428573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061067491906123f1565b600154604051631f16aef360e01b81526004810188905260248101879052604481018690526064810185905283151560848201526001600160a01b0383811660a483015290911690631f16aef39060c401600060405180830381600087803b1580156114b757600080fd5b505af11580156114cb573d6000803e3d6000fd5b50505050505050505050565b60015460405163650aac6160e01b815260048101879052602481018690526001600160a01b0385811660448301526064820185905261ffff841660848301529091169063650aac619060a401600060405180830381600087803b15801561153d57600080fd5b505af1158015611551573d6000803e3d6000fd5b505050505050505050565b600280546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60015460405163a3fafd0560e01b81526060916001600160a01b03169063a3fafd05906115e1908690869060040161240a565b6000604051808303816000875af1158015611600573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610f5f9190810190612436565b600154600090600160a01b900460ff16156116ad57600154604051632e5f2cf160e01b81526001600160a01b03848116600483015290911690632e5f2cf1906024016020604051808303816000875af1158015611689573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061067491906124c7565b506001919050565b6001546000908190600160a01b900460ff16156117495760015460405163496d511d60e11b81526001600160a01b038581166004830152306024830152909116906392daa23a906044016040805180830381865afa15801561171b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061173f91906124e4565b9092509050915091565b60019150915091565b600154604051639aab948160e01b8152600481018690526001600160a01b0385811660248301526044820185905261ffff841660648301526000921690639aab9481906084016020604051808303816000875af11580156117b7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061137691906123f1565b6040805160c0810190915260006080820181815260a08301919091528190815260200161181b604051806040016040528060008152602001600081525090565b815260006020820181905260409091015290565b60006020828403121561184157600080fd5b5035919050565b634e487b7160e01b600052602160045260246000fd5b6008811061187c57634e487b7160e01b600052602160045260246000fd5b9052565b6040810161188e828561185e565b6001600160a01b039290921660209190910152919050565b6001600160a01b038116811461135d57600080fd5b8035610e0a816118a6565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff811182821017156118ff576118ff6118c6565b60405290565b6040805190810167ffffffffffffffff811182821017156118ff576118ff6118c6565b60405160a0810167ffffffffffffffff811182821017156118ff576118ff6118c6565b604051601f8201601f1916810167ffffffffffffffff81118282101715611974576119746118c6565b604052919050565b600082601f83011261198d57600080fd5b813567ffffffffffffffff8111156119a7576119a76118c6565b6119ba601f8201601f191660200161194b565b8181528460208386010111156119cf57600080fd5b816020850160208301376000918101602001919091529392505050565b600060c082840312156119fe57600080fd5b50919050565b6000806000806000806000806101a0898b031215611a2157600080fd5b611a2a896118bb565b9750611a3860208a016118bb565b9650604089013567ffffffffffffffff80821115611a5557600080fd5b611a618c838d0161197c565b975060608b0135915080821115611a7757600080fd5b611a838c838d0161197c565b965060808b0135915080821115611a9957600080fd5b50611aa68b828c0161197c565b945050611ab560a08a016118bb565b9250611ac360c08a016118bb565b9150611ad28a60e08b016119ec565b90509295985092959890939650565b801515811461135d57600080fd5b600067ffffffffffffffff821115611b0957611b096118c6565b5060051b60200190565b803561ffff81168114610e0a57600080fd5b600082601f830112611b3657600080fd5b81356020611b4b611b4683611aef565b61194b565b82815260609283028501820192828201919087851115611b6a57600080fd5b8387015b85811015611bc15781818a031215611b865760008081fd5b611b8e6118dc565b8135611b99816118a6565b815281860135868201526040611bb0818401611b13565b908201528452928401928101611b6e565b5090979650505050505050565b600060208284031215611be057600080fd5b813567ffffffffffffffff80821115611bf857600080fd5b9083019081850360c0811215611c0d57600080fd5b611c15611905565b60a0821215611c2357600080fd5b611c2b611928565b91508335825260208401356020830152604084013560408301526060840135611c5381611ae1565b60608301526080840135611c66816118a6565b608083015290815260a08301359082821115611c8157600080fd5b611c8d87838601611b25565b60208201529695505050505050565b60008060008060008060c08789031215611cb557600080fd5b863595506020870135945060408701359350606087013592506080870135611cdc81611ae1565b915060a0870135611cec816118a6565b809150509295509295509295565b600060208284031215611d0c57600080fd5b8135610f5f816118a6565b611d2c82825180518252602090810151910152565b602081810151805160408501529081015160608401525060408101516001600160f01b0319166080830152606001516001600160a01b031660a090910152565b60c081016106748284611d17565b6000604082840312156119fe57600080fd5b602080825282518282018190526000919060409081850190868401855b82811015611dde578151611dbe85825161185e565b8601516001600160a01b0316848701529284019290850190600101611da9565b5091979650505050505050565b60008060e08385031215611dfe57600080fd5b8235611e09816118a6565b9150611e1884602085016119ec565b90509250929050565b600080600080600060a08688031215611e3957600080fd5b85359450602086013593506040860135611e52816118a6565b925060608601359150611e6760808701611b13565b90509295509295909350565b60008060408385031215611e8657600080fd5b8235611e91816118a6565b946020939093013593505050565b604080825283519082018190526000906020906060840190828701845b82811015611ee15781516001600160a01b031684529284019290840190600101611ebc565b5050508381038285015284518082528583019183019060005b81811015611bc157611f0d838551611d17565b9284019260c09290920191600101611efa565b60008060408385031215611f3357600080fd5b8235611f3e816118a6565b91506020830135611f4e816118a6565b809150509250929050565b60008060408385031215611f6c57600080fd5b8235611f77816118a6565b915060208381013567ffffffffffffffff811115611f9457600080fd5b8401601f81018613611fa557600080fd5b8035611fb3611b4682611aef565b81815260059190911b82018301908381019088831115611fd257600080fd5b928401925b82841015611ff057833582529284019290840190611fd7565b80955050505050509250929050565b600081518084526020808501945080840160005b8381101561202f57815187529582019590820190600101612013565b509495945050505050565b602081526000610f5f6020830184611fff565b60006020828403121561205f57600080fd5b8135610f5f81611ae1565b60008060008060008060c0878903121561208357600080fd5b863561208e816118a6565b9550602087013561209e816118a6565b9450604087013567ffffffffffffffff808211156120bb57600080fd5b6120c78a838b0161197c565b955060608901359150808211156120dd57600080fd5b6120e98a838b0161197c565b945060808901359150808211156120ff57600080fd5b5061210c89828a0161197c565b92505060a0870135611cec816118a6565b6000806000806080858703121561213357600080fd5b843593506020850135612145816118a6565b92506040850135915061215a60608601611b13565b905092959194509250565b813581556020820135600182015560408201356002820155606082013560038201556004810160808301356001600160f01b0319811681146121a657600080fd5b815460a08501356121b6816118a6565b62010000600160b01b0360109190911b1660f09290921c6001600160b01b031991909116171790555050565b634e487b7160e01b600052601160045260246000fd5b81810381811115610674576106746121e2565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b600060018201612249576122496121e2565b5060010190565b60006020828403121561226257600080fd5b813560088110610f5f57600080fd5b6000815180845260005b818110156122975760208185018101518683018201520161227b565b506000602082860101526020601f19601f83011685010191505092915050565b600060018060a01b038089168352808816602084015260c060408401526122e160c0840188612271565b83810360608501526122f38188612271565b905083810360808501526123078187612271565b92505080841660a084015250979650505050505050565b60006020828403121561233057600080fd5b8151610f5f816118a6565b602080825282518051838301528082015160408085019190915280820151606080860191909152808301511515608080870191909152909201516001600160a01b0390811660a08601528584015160c080870152805160e08701819052600095949185019386939290916101008901905b808610156123e3578651805186168352888101518984015284015161ffff16848301529587019560019590950194908201906123ac565b509998505050505050505050565b60006020828403121561240357600080fd5b5051919050565b6001600160a01b038316815260406020820181905260009061242e90830184611fff565b949350505050565b6000602080838503121561244957600080fd5b825167ffffffffffffffff81111561246057600080fd5b8301601f8101851361247157600080fd5b805161247f611b4682611aef565b81815260059190911b8201830190838101908783111561249e57600080fd5b928401925b828410156124bc578351825292840192908401906124a3565b979650505050505050565b6000602082840312156124d957600080fd5b8151610f5f81611ae1565b600080604083850312156124f757600080fd5b825161250281611ae1565b6020840151909250611f4e81611ae156fea2646970667358221220f175cf5cdd46228ab32490c5d146c50a3fdcc8081242ea39421520342ab6e78d64736f6c63430008150033000000000000000000000000bde298fcd625d77c30cb6f1ad661a6ca4f41ae67

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101fb5760003560e01c80636aa633b61161011a578063abba145b116100ad578063d259c8a51161007c578063d259c8a51461052a578063d376e42214610554578063e1e3c08d14610580578063f2fde38b14610593578063fb8adca4146105a657600080fd5b8063abba145b146104de578063b22f6d26146104f1578063c2666fed14610504578063c45a01551461051757600080fd5b80638da5cb5b116100e95780638da5cb5b14610487578063991f1358146104985780639ec30e4a146104ab578063a3fafd05146104be57600080fd5b80636aa633b614610448578063715018a61461046c57806378451d00146102555780638d69e95e1461047457600080fd5b80632934092f116101925780635bb47808116101615780635bb47808146103d75780635d8a30b4146103ea5780635f098cc6146103fd57806363df3d171461042757600080fd5b80632934092f146102e45780633194bfe1146102f95780633317b649146103b15780635751869b146103c457600080fd5b80631fd340a3116101ce5780631fd340a31461028b5780632063b112146102ab57806320da7170146102be57806326e3c30a146102d157600080fd5b806302f43e591461020057806303153be01461022a5780630c5620d6146102555780631f16aef314610276575b600080fd5b61021361020e36600461182f565b6105b9565b604051610221929190611880565b60405180910390f35b61023d610238366004611a04565b6105ec565b6040516001600160a01b039091168152602001610221565b610268610263366004611bce565b610661565b604051908152602001610221565b610289610284366004611c9c565b61067a565b005b61029e610299366004611cfa565b610698565b6040516102219190611d6c565b6102896102b936600461182f565b610725565b60015461023d906001600160a01b031681565b6102896102df366004611d7a565b610810565b6102ec610975565b6040516102219190611d8c565b610367610307366004611cfa565b60076020908152600091825260409182902082518084018452815481526001820154818401528351808501909452600282015484526003820154928401929092526004015490919060f081901b906201000090046001600160a01b031684565b604080518551815260209586015186820152845191810191909152939092015160608401526001600160f01b03191660808301526001600160a01b031660a082015260c001610221565b6102896103bf366004611deb565b610a11565b6102896103d2366004611e21565b610b56565b6102896103e5366004611cfa565b610b72565b61023d6103f8366004611e73565b610b9c565b61041061040b366004611cfa565b610bd4565b604080519215158352602083019190915201610221565b61043a610435366004611cfa565b610c3d565b604051610221929190611e9f565b60015461045c90600160a01b900460ff1681565b6040519015158152602001610221565b610289610df6565b60005461023d906001600160a01b031681565b6002546001600160a01b031661023d565b61045c6104a6366004611f20565b610e0f565b6102896104b9366004611cfa565b610f21565b6104d16104cc366004611f59565b610f4b565b604051610221919061203a565b6102896104ec36600461204d565b610f66565b6102136104ff366004611e73565b610f8c565b61023d61051236600461206a565b610fcd565b60055461023d906001600160a01b031681565b61053d610538366004611cfa565b6111b3565b604080519215158352901515602083015201610221565b610567610562366004611cfa565b6111c9565b6040516001600160f01b03199091168152602001610221565b6102ec61058e366004611cfa565b611235565b6102896105a1366004611cfa565b6112e7565b6102686105b436600461211d565b611360565b600381815481106105c957600080fd5b60009182526020909120015460ff8116915061010090046001600160a01b031682565b60006105fc898989898989610fcd565b6001600160a01b03848116600090815260066020908152604080832080546001810182559084528284200180546001600160a01b0319169486169485179055928252600790522090915082906106528282612165565b90505098975050505050505050565b600061066b61137f565b610674826113d9565b92915050565b61068261137f565b61069086868686868661144c565b505050505050565b6106a06117db565b506001600160a01b03908116600090815260076020908152604091829020825160c081018452815460808201908152600183015460a08301528152835180850185526002830154815260038301548185015292810192909252600401546001600160f01b031960f082901b169282019290925262010000909104909116606082015290565b61072d61137f565b60035461073c906001906121f8565b81146107da5760038054610752906001906121f8565b815481106107625761076261220b565b906000526020600020016003828154811061077f5761077f61220b565b60009182526020909120825491018054909160ff1690829060ff191660018360078111156107af576107af611848565b021790555090548154610100600160a81b031916610100918290046001600160a01b03169091021790555b60038054806107eb576107eb612221565b600082815260209020810160001990810180546001600160a81b031916905501905550565b61081861137f565b60005b6003548110156108bd576108356040830160208401611cfa565b6001600160a01b0316600382815481106108515761085161220b565b60009182526020909120015461010090046001600160a01b0316036108ad5760405162461bcd60e51b815260206004820152600d60248201526c105b1c9958591e48195e1a5cdd609a1b60448201526064015b60405180910390fd5b6108b681612237565b905061081b565b5060408051808201909152600390806108d96020850185612250565b60078111156108ea576108ea611848565b81526020018360200160208101906109029190611cfa565b6001600160a01b031690528154600181810184556000938452602090932082519101805492939092839160ff199091169083600781111561094557610945611848565b02179055506020919091015181546001600160a01b0390911661010002610100600160a81b031990911617905550565b60606003805480602002602001604051908101604052809291908181526020016000905b82821015610a0857600084815260209020604080518082019091529083018054829060ff1660078111156109cf576109cf611848565b60078111156109e0576109e0611848565b8152905461010090046001600160a01b03166020918201529082526001929092019101610999565b50505050905090565b33600090815260046020908152604080832080548251818502810185019093528083529192909190849084015b82821015610aad57600084815260209020604080518082019091529083018054829060ff166007811115610a7457610a74611848565b6007811115610a8557610a85611848565b8152905461010090046001600160a01b03166020918201529082526001929092019101610a3e565b50505050905060005b8151811015610b2b57836001600160a01b0316828281518110610adb57610adb61220b565b6020026020010151602001516001600160a01b031603610b19576001600160a01b038416600090815260076020526040902083906106908282612165565b80610b2381612237565b915050610ab6565b5060405163295a81c160e01b81523360048201526001600160a01b03841660248201526044016108a4565b610b5e61137f565b610b6b85858585856114d7565b5050505050565b610b7a61137f565b600580546001600160a01b0319166001600160a01b0392909216919091179055565b60066020528160005260406000208181548110610bb857600080fd5b6000918252602090912001546001600160a01b03169150829050565b60008060005b600354811015610c375760038181548110610bf757610bf761220b565b6000918252602090912001546001600160a01b03610100909104811690851603610c275760019250809150610c37565b610c3081612237565b9050610bda565b50915091565b60608060066000846001600160a01b03166001600160a01b03168152602001908152602001600020805480602002602001604051908101604052809291908181526020018280548015610cb957602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610c9b575b50505050509150815167ffffffffffffffff811115610cda57610cda6118c6565b604051908082528060200260200182016040528015610d1357816020015b610d006117db565b815260200190600190039081610cf85790505b50905060005b8251811015610c375760076000848381518110610d3857610d3861220b565b6020908102919091018101516001600160a01b039081168352828201939093526040918201600020825160c081018452815460808201908152600183015460a08301528152835180850185526002830154815260038301548185015292810192909252600401546001600160f01b031960f082901b16928201929092526201000090910490911660608201528251839083908110610dd857610dd861220b565b60200260200101819052508080610dee90612237565b915050610d19565b610dfe61137f565b610e08600061155c565b565b919050565b6001600160a01b038216600090815260066020908152604080832080548251818502810185019093528083528493830182828015610e7657602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610e58575b5050505050905060005b8151811015610f1957836001600160a01b0316828281518110610ea557610ea561220b565b60200260200101516001600160a01b031603610f07576001600160a01b0384166000908152600760205260409020544210801590610efd57506001600160a01b03841660009081526007602052604090206001015442105b15610f0757600192505b80610f1181612237565b915050610e80565b505092915050565b610f2961137f565b600180546001600160a01b0319166001600160a01b0392909216919091179055565b6060610f5561137f565b610f5f83836115ae565b9392505050565b610f6e61137f565b60018054911515600160a01b0260ff60a01b19909216919091179055565b60046020528160005260406000208181548110610fa857600080fd5b60009182526020909120015460ff8116925061010090046001600160a01b0316905082565b6000806000610fdb89610bd4565b91509150816110415760405162461bcd60e51b815260206004820152602c60248201527f5468697320696d706c656d656e746174696f6e2061646472657373206973206e60448201526b1bdd081cdd5c1c1bdc9d195960a21b60648201526084016108a4565b61104a33611628565b50600554604051600162030bd960e01b031981526001600160a01b039091169063fffcf42790611088908c908c908c908c908c908c906004016122b7565b6020604051808303816000875af11580156110a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110cb919061231e565b925060046000896001600160a01b03166001600160a01b031681526020019081526020016000206040518060400160405280600384815481106111105761111061220b565b60009182526020909120015460ff16600781111561113057611130611848565b81526001600160a01b038616602091820152825460018181018555600094855291909320825193018054929390929091839160ff19169083600781111561117957611179611848565b02179055506020919091015181546001600160a01b0390911661010002610100600160a81b03199091161790555090979650505050505050565b6000806111bf836116b5565b9094909350915050565b6001600160a01b038116600090815260076020526040812060020154421080159061120e57506001600160a01b03821660009081526007602052604090206003015442105b15610e0a57506001600160a01b031660009081526007602052604090206004015460f01b90565b6001600160a01b0381166000908152600460209081526040808320805482518185028101850190935280835260609492939192909184015b828210156112dc57600084815260209020604080518082019091529083018054829060ff1660078111156112a3576112a3611848565b60078111156112b4576112b4611848565b8152905461010090046001600160a01b0316602091820152908252600192909201910161126d565b505050509050919050565b6112ef61137f565b6001600160a01b0381166113545760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016108a4565b61135d8161155c565b50565b600061136a61137f565b61137685858585611752565b95945050505050565b6002546001600160a01b03163314610e085760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016108a4565b6001546040516278451d60e81b81526000916001600160a01b0316906378451d009061140990859060040161233b565b6020604051808303816000875af1158015611428573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061067491906123f1565b600154604051631f16aef360e01b81526004810188905260248101879052604481018690526064810185905283151560848201526001600160a01b0383811660a483015290911690631f16aef39060c401600060405180830381600087803b1580156114b757600080fd5b505af11580156114cb573d6000803e3d6000fd5b50505050505050505050565b60015460405163650aac6160e01b815260048101879052602481018690526001600160a01b0385811660448301526064820185905261ffff841660848301529091169063650aac619060a401600060405180830381600087803b15801561153d57600080fd5b505af1158015611551573d6000803e3d6000fd5b505050505050505050565b600280546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60015460405163a3fafd0560e01b81526060916001600160a01b03169063a3fafd05906115e1908690869060040161240a565b6000604051808303816000875af1158015611600573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610f5f9190810190612436565b600154600090600160a01b900460ff16156116ad57600154604051632e5f2cf160e01b81526001600160a01b03848116600483015290911690632e5f2cf1906024016020604051808303816000875af1158015611689573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061067491906124c7565b506001919050565b6001546000908190600160a01b900460ff16156117495760015460405163496d511d60e11b81526001600160a01b038581166004830152306024830152909116906392daa23a906044016040805180830381865afa15801561171b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061173f91906124e4565b9092509050915091565b60019150915091565b600154604051639aab948160e01b8152600481018690526001600160a01b0385811660248301526044820185905261ffff841660648301526000921690639aab9481906084016020604051808303816000875af11580156117b7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061137691906123f1565b6040805160c0810190915260006080820181815260a08301919091528190815260200161181b604051806040016040528060008152602001600081525090565b815260006020820181905260409091015290565b60006020828403121561184157600080fd5b5035919050565b634e487b7160e01b600052602160045260246000fd5b6008811061187c57634e487b7160e01b600052602160045260246000fd5b9052565b6040810161188e828561185e565b6001600160a01b039290921660209190910152919050565b6001600160a01b038116811461135d57600080fd5b8035610e0a816118a6565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff811182821017156118ff576118ff6118c6565b60405290565b6040805190810167ffffffffffffffff811182821017156118ff576118ff6118c6565b60405160a0810167ffffffffffffffff811182821017156118ff576118ff6118c6565b604051601f8201601f1916810167ffffffffffffffff81118282101715611974576119746118c6565b604052919050565b600082601f83011261198d57600080fd5b813567ffffffffffffffff8111156119a7576119a76118c6565b6119ba601f8201601f191660200161194b565b8181528460208386010111156119cf57600080fd5b816020850160208301376000918101602001919091529392505050565b600060c082840312156119fe57600080fd5b50919050565b6000806000806000806000806101a0898b031215611a2157600080fd5b611a2a896118bb565b9750611a3860208a016118bb565b9650604089013567ffffffffffffffff80821115611a5557600080fd5b611a618c838d0161197c565b975060608b0135915080821115611a7757600080fd5b611a838c838d0161197c565b965060808b0135915080821115611a9957600080fd5b50611aa68b828c0161197c565b945050611ab560a08a016118bb565b9250611ac360c08a016118bb565b9150611ad28a60e08b016119ec565b90509295985092959890939650565b801515811461135d57600080fd5b600067ffffffffffffffff821115611b0957611b096118c6565b5060051b60200190565b803561ffff81168114610e0a57600080fd5b600082601f830112611b3657600080fd5b81356020611b4b611b4683611aef565b61194b565b82815260609283028501820192828201919087851115611b6a57600080fd5b8387015b85811015611bc15781818a031215611b865760008081fd5b611b8e6118dc565b8135611b99816118a6565b815281860135868201526040611bb0818401611b13565b908201528452928401928101611b6e565b5090979650505050505050565b600060208284031215611be057600080fd5b813567ffffffffffffffff80821115611bf857600080fd5b9083019081850360c0811215611c0d57600080fd5b611c15611905565b60a0821215611c2357600080fd5b611c2b611928565b91508335825260208401356020830152604084013560408301526060840135611c5381611ae1565b60608301526080840135611c66816118a6565b608083015290815260a08301359082821115611c8157600080fd5b611c8d87838601611b25565b60208201529695505050505050565b60008060008060008060c08789031215611cb557600080fd5b863595506020870135945060408701359350606087013592506080870135611cdc81611ae1565b915060a0870135611cec816118a6565b809150509295509295509295565b600060208284031215611d0c57600080fd5b8135610f5f816118a6565b611d2c82825180518252602090810151910152565b602081810151805160408501529081015160608401525060408101516001600160f01b0319166080830152606001516001600160a01b031660a090910152565b60c081016106748284611d17565b6000604082840312156119fe57600080fd5b602080825282518282018190526000919060409081850190868401855b82811015611dde578151611dbe85825161185e565b8601516001600160a01b0316848701529284019290850190600101611da9565b5091979650505050505050565b60008060e08385031215611dfe57600080fd5b8235611e09816118a6565b9150611e1884602085016119ec565b90509250929050565b600080600080600060a08688031215611e3957600080fd5b85359450602086013593506040860135611e52816118a6565b925060608601359150611e6760808701611b13565b90509295509295909350565b60008060408385031215611e8657600080fd5b8235611e91816118a6565b946020939093013593505050565b604080825283519082018190526000906020906060840190828701845b82811015611ee15781516001600160a01b031684529284019290840190600101611ebc565b5050508381038285015284518082528583019183019060005b81811015611bc157611f0d838551611d17565b9284019260c09290920191600101611efa565b60008060408385031215611f3357600080fd5b8235611f3e816118a6565b91506020830135611f4e816118a6565b809150509250929050565b60008060408385031215611f6c57600080fd5b8235611f77816118a6565b915060208381013567ffffffffffffffff811115611f9457600080fd5b8401601f81018613611fa557600080fd5b8035611fb3611b4682611aef565b81815260059190911b82018301908381019088831115611fd257600080fd5b928401925b82841015611ff057833582529284019290840190611fd7565b80955050505050509250929050565b600081518084526020808501945080840160005b8381101561202f57815187529582019590820190600101612013565b509495945050505050565b602081526000610f5f6020830184611fff565b60006020828403121561205f57600080fd5b8135610f5f81611ae1565b60008060008060008060c0878903121561208357600080fd5b863561208e816118a6565b9550602087013561209e816118a6565b9450604087013567ffffffffffffffff808211156120bb57600080fd5b6120c78a838b0161197c565b955060608901359150808211156120dd57600080fd5b6120e98a838b0161197c565b945060808901359150808211156120ff57600080fd5b5061210c89828a0161197c565b92505060a0870135611cec816118a6565b6000806000806080858703121561213357600080fd5b843593506020850135612145816118a6565b92506040850135915061215a60608601611b13565b905092959194509250565b813581556020820135600182015560408201356002820155606082013560038201556004810160808301356001600160f01b0319811681146121a657600080fd5b815460a08501356121b6816118a6565b62010000600160b01b0360109190911b1660f09290921c6001600160b01b031991909116171790555050565b634e487b7160e01b600052601160045260246000fd5b81810381811115610674576106746121e2565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b600060018201612249576122496121e2565b5060010190565b60006020828403121561226257600080fd5b813560088110610f5f57600080fd5b6000815180845260005b818110156122975760208185018101518683018201520161227b565b506000602082860101526020601f19601f83011685010191505092915050565b600060018060a01b038089168352808816602084015260c060408401526122e160c0840188612271565b83810360608501526122f38188612271565b905083810360808501526123078187612271565b92505080841660a084015250979650505050505050565b60006020828403121561233057600080fd5b8151610f5f816118a6565b602080825282518051838301528082015160408085019190915280820151606080860191909152808301511515608080870191909152909201516001600160a01b0390811660a08601528584015160c080870152805160e08701819052600095949185019386939290916101008901905b808610156123e3578651805186168352888101518984015284015161ffff16848301529587019560019590950194908201906123ac565b509998505050505050505050565b60006020828403121561240357600080fd5b5051919050565b6001600160a01b038316815260406020820181905260009061242e90830184611fff565b949350505050565b6000602080838503121561244957600080fd5b825167ffffffffffffffff81111561246057600080fd5b8301601f8101851361247157600080fd5b805161247f611b4682611aef565b81815260059190911b8201830190838101908783111561249e57600080fd5b928401925b828410156124bc578351825292840192908401906124a3565b979650505050505050565b6000602082840312156124d957600080fd5b8151610f5f81611ae1565b600080604083850312156124f757600080fd5b825161250281611ae1565b6020840151909250611f4e81611ae156fea2646970667358221220f175cf5cdd46228ab32490c5d146c50a3fdcc8081242ea39421520342ab6e78d64736f6c63430008150033

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

000000000000000000000000bde298fcd625d77c30cb6f1ad661a6ca4f41ae67

-----Decoded View---------------
Arg [0] : _subscrRegistry (address): 0xbdE298FcD625d77C30CB6F1Ad661a6CA4F41aE67

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


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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

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