// File: Address.sol



pragma solidity ^0.5.0;

/**
 * Utility library of inline functions on addresses
 */
library Address {
    /**
     * Returns whether the target address is a contract
     * @dev This function will return false if invoked during the constructor of a contract,
     * as the code is not actually created until after the constructor finishes.
     * @param account address of the account to check
     * @return whether the target address is a contract
     */
    function isContract(address account) internal view returns (bool) {
        uint256 size;
        // XXX Currently there is no better way to check if there is a contract in an address
        // than to check the size of the code at that address.
        // See https://ethereum.stackexchange.com/a/14016/36603
        // for more details about how this works.
        // TODO Check this again before the Serenity release, because all addresses will be
        // contracts then.
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }
}

// File: Decomposer.sol



pragma solidity ^0.5.0;
import "./Folia.sol";

/*
     _                                                    
    | |                                                   
  __| | ___  ___ ___  _ __ ___  _ __   ___  ___  ___ _ __ 
 / _` |/ _ \/ __/ _ \| '_ ` _ \| '_ \ / _ \/ __|/ _ \ '__|
| (_| |  __/ (_| (_) | | | | | | |_) | (_) \__ \  __/ |   
 \__,_|\___|\___\___/|_| |_| |_| .__/ \___/|___/\___|_|   
                               | |                        
                               |_|                        
By Oliver Laric
Produced by Folia.app
*/

contract Decomposer is Folia {
    constructor(address _metadata) public Folia("Decomposer", "DCMP", _metadata){}
}

// File: DecomposerController.sol



pragma solidity ^0.5.0;
/**
 * The FoliaControllerV2 is an upgradeable endpoint for controlling Folia.sol
 */

import "./Decomposer.sol";
import "./SafeMath.sol";
import "./Ownable.sol";
import "./ReentrancyGuard.sol";
import "./IERC721.sol";
import "./IERC165.sol";

interface Punk {
      function punkIndexToAddress(uint256 tokenId) external view returns (address owner);
     // mapping (uint => address) public punkIndexToAddress;
}

contract DecomposerController is Ownable, ReentrancyGuard {

    using SafeMath for uint256;

    event newContract(address contractAddress, uint256 maxEditions, cT contractType);
    event deletedContract(address contractAddress);
    event editionBought(address contractAddress, uint256 tokenId, uint256 newTokenId);
    uint256 public price = 8 * (10**16); // 0.08 Eth
    uint256 public totalMax = 888;
    mapping(address => uint256) public editionsLeft;

    Decomposer public decomposer;

    uint256 public adminSplit = 20;
    address payable public adminWallet;
    address payable public artistWallet;
    bool public paused;

    modifier notPaused() {
        require(!paused, "Must not be paused");
        _;
    }

    constructor(
        Decomposer _decomposer,
        address payable _adminWallet
    ) public {
        decomposer = _decomposer;
        adminWallet = _adminWallet;
        uint256 _maxEditions = 88;

        addContract(0xB77F0b25aF126FCE0ea41e5696F1E5e9102E1D77, _maxEditions, uint8(cT.ERC721)); // 3Words
        addContract(0x123b30E25973FeCd8354dd5f41Cc45A3065eF88C, _maxEditions, uint8(cT.ERC721)); // Alien Frens
        addContract(0xa7d8d9ef8D8Ce8992Df33D8b8CF4Aebabd5bD270, _maxEditions, uint8(cT.ERC721)); // Apparitions by Aaron Penne
        addContract(0xa7d8d9ef8D8Ce8992Df33D8b8CF4Aebabd5bD270, _maxEditions, uint8(cT.ERC721)); // Archetype by Kjetil Golid
        addContract(0x842D8B7B08C154ADc36A4f1186A0f401a10518EA, _maxEditions, uint8(cT.ERC721)); // Autobreeder (lite) by Harm van den Dorpel 
        addContract(0xDFAcD840f462C27b0127FC76b63e7925bEd0F9D5, _maxEditions, uint8(cT.ERC721)); // Avid Lines
        addContract(0xED5AF388653567Af2F388E6224dC7C4b3241C544, _maxEditions, uint8(cT.ERC721)); // Azuki
        addContract(0x8d04a8c79cEB0889Bdd12acdF3Fa9D207eD3Ff63, _maxEditions, uint8(cT.ERC721)); // Blitmap
        addContract(0xba30E5F9Bb24caa003E9f2f0497Ad287FDF95623, _maxEditions, uint8(cT.ERC721)); // Bored Ape Kennel Club
        addContract(0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D, _maxEditions, uint8(cT.ERC721)); // Bored Ape Yacht Club
        addContract(0xfcB1315C4273954F74Cb16D5b663DBF479EEC62e, _maxEditions, uint8(cT.ERC721)); // Capsule House
        addContract(0x059EDD72Cd353dF5106D2B9cC5ab83a52287aC3a, _maxEditions, uint8(cT.ERC721)); // Chromie Squiggle by Snowfro
        addContract(0x91Fba69Ce5071Cf9e828999a0F6006A7F7E2a959, _maxEditions, uint8(cT.ERC721)); // CLASSIFIED | Holly Herndon
        addContract(0x49cF6f5d44E70224e2E23fDcdd2C053F30aDA28B, _maxEditions, uint8(cT.ERC721)); // CLONE X - X TAKASHI MURAKAMI
        addContract(0x1A92f7381B9F03921564a437210bB9396471050C, _maxEditions, uint8(cT.ERC721)); // Cool Cats NFT
        addContract(0xc92cedDfb8dd984A89fb494c376f9A48b999aAFc, _maxEditions, uint8(cT.ERC721)); // Creature World
        addContract(0x1CB1A5e65610AEFF2551A50f76a87a7d3fB649C6, _maxEditions, uint8(cT.ERC721)); // CrypToadz by GREMPLIN
        addContract(0xBACe7E22f06554339911A03B8e0aE28203Da9598, _maxEditions, uint8(cT.ERC721exception)); // CryptoArte
        addContract(0xF7a6E15dfD5cdD9ef12711Bd757a9b6021ABf643, _maxEditions, uint8(cT.ERC721exception)); // CryptoBots
        addContract(0x1981CC36b59cffdd24B01CC5d698daa75e367e04, _maxEditions, uint8(cT.ERC721)); // Crypto.Chicks
        addContract(0x5180db8F5c931aaE63c74266b211F580155ecac8, _maxEditions, uint8(cT.ERC721)); // Crypto Coven
        addContract(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d, _maxEditions, uint8(cT.ERC721exception)); // CryptoKitties
        addContract(0x57a204AA1042f6E66DD7730813f4024114d74f37, _maxEditions, uint8(cT.ERC721)); // CyberKongz
        addContract(0xc1Caf0C19A8AC28c41Fe59bA6c754e4b9bd54dE9, _maxEditions, uint8(cT.ERC721)); // CryptoSkulls
        addContract(0xF87E31492Faf9A91B02Ee0dEAAd50d51d56D5d4d, _maxEditions, uint8(cT.ERC721)); // Decentraland
        addContract(0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e, _maxEditions, uint8(cT.ERC721)); // Doodles
        addContract(0x6CA044FB1cD505c1dB4eF7332e73a236aD6cb71C, _maxEditions, uint8(cT.ERC721)); // DotCom Seance
        addContract(0x4721D66937B16274faC603509E9D61C5372Ff220, _maxEditions, uint8(cT.ERC721)); // Fast Food Frens Collection
        addContract(0xa7d8d9ef8D8Ce8992Df33D8b8CF4Aebabd5bD270, _maxEditions, uint8(cT.ERC721)); // Fidenza by Tyler Hobbs
        addContract(0x90cfCE78f5ED32f9490fd265D16c77a8b5320Bd4, _maxEditions, uint8(cT.ERC721)); // FOMO Dog Club
        addContract(0xa7d8d9ef8D8Ce8992Df33D8b8CF4Aebabd5bD270, _maxEditions, uint8(cT.ERC721)); // Fragments of an Infinite Field by Monica Rizzolli
        addContract(0xC2C747E0F7004F9E8817Db2ca4997657a7746928, _maxEditions, uint8(cT.ERC721)); // Hashmasks
        addContract(0x0c2E57EFddbA8c768147D1fdF9176a0A6EBd5d83, _maxEditions, uint8(cT.ERC721)); // Kaiju Kingz
        addContract(0x9d413B9434c20C73f509505F7fbC6FC591bbf04A, _maxEditions, uint8(cT.ERC721)); // Kudzu
        addContract(0x8943C7bAC1914C9A7ABa750Bf2B6B09Fd21037E0, _maxEditions, uint8(cT.ERC721)); // Lazy Lions
        addContract(0x026224A2940bFE258D0dbE947919B62fE321F042, _maxEditions, uint8(cT.ERC721)); // lobsterdao
        addContract(0x4b3406a41399c7FD2BA65cbC93697Ad9E7eA61e5, _maxEditions, uint8(cT.ERC721)); // LOSTPOETS
        addContract(0x7Bd29408f11D2bFC23c34f18275bBf23bB716Bc7, _maxEditions, uint8(cT.ERC721)); // Meebits
        addContract(0xF7143Ba42d40EAeB49b88DaC0067e54Af042E963, _maxEditions, uint8(cT.ERC721)); // Metasaurs by Dr. DMT
        addContract(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69, _maxEditions, uint8(cT.ERC721)); // MoonCats
        addContract(0x60E4d786628Fea6478F785A6d7e704777c86a7c6, _maxEditions, uint8(cT.ERC721)); // Mutant Ape Yacht Club
        addContract(0x9C8fF314C9Bc7F6e59A9d9225Fb22946427eDC03, _maxEditions, uint8(cT.ERC721)); // Nouns
        addContract(0x4f89Cd0CAE1e54D98db6a80150a824a533502EEa, _maxEditions, uint8(cT.ERC721)); // PEACEFUL GROUPIES
        addContract(0x67D9417C9C3c250f61A83C7e8658daC487B56B09, _maxEditions, uint8(cT.ERC721)); // PhantaBear
        addContract(0x050dc61dFB867E0fE3Cf2948362b6c0F3fAF790b, _maxEditions, uint8(cT.ERC721)); // PixelMap
        addContract(0xBd3531dA5CF5857e7CfAA92426877b022e612cf8, _maxEditions, uint8(cT.ERC721)); // Pudgy Penguins
        addContract(0x51Ae5e2533854495f6c587865Af64119db8F59b4, _maxEditions, uint8(cT.ERC721)); // PunkScapes
        addContract(0x29b7315fc83172CFcb45c2Fb415E91A265fb73f2, _maxEditions, uint8(cT.ERC721)); // Realiti
        addContract(0x8CD3cEA52a45f30Ed7c93a63FB2b5C13B453d5A1, _maxEditions, uint8(cT.ERC721)); // Rebel Society
        addContract(0x3Fe1a4c1481c8351E91B64D5c398b159dE07cbc5, _maxEditions, uint8(cT.ERC721)); // SupDucks
        addContract(0xF4ee95274741437636e748DdAc70818B4ED7d043, _maxEditions, uint8(cT.ERC721)); // The Doge Pound
        addContract(0x5CC5B05a8A13E3fBDB0BB9FcCd98D38e50F90c38, _maxEditions, uint8(cT.ERC721)); // The Sandbox
        addContract(0x11450058d796B02EB53e65374be59cFf65d3FE7f, _maxEditions, uint8(cT.ERC721)); // THE SHIBOSHIS
        addContract(0x7f7685b4CC34BD19E2B712D8a89f34D219E76c35, _maxEditions, uint8(cT.ERC721)); // WomenRise
        addContract(0xe785E82358879F061BC3dcAC6f0444462D4b5330, _maxEditions, uint8(cT.ERC721)); // World of Women
        addContract(0xB67812ce508b9fC190740871032237C24b6896A0, _maxEditions, uint8(cT.ERC721)); // WoW Pixies Official
        addContract(0xd0e7Bc3F1EFc5f098534Bce73589835b8273b9a0, _maxEditions, uint8(cT.ERC721)); // Wrapped CryptoCats Official
        addContract(0x6f9d53BA6c16fcBE66695E860e72a92581b58Aed, _maxEditions, uint8(cT.ERC721)); // Wrapped Pixereum
        
        // // rinkeby
        // addContract(0xF80B749e0d03C005b8EfB7451BC6552555556149, _maxEditions, uint8(cT.ERC721)); // Kudzu

        // folia
        addContract(0xDCe09254dD3592381b6A5b7a848B29890b656e01, _maxEditions, uint8(cT.Folia)); // Emoji Script by Travess Smalley (work 2)
        // rinkeby
        // addContract(0x95793c65c398D0a5EEb92d6b475f4E6a2044Bee1, _maxEditions, uint8(cT.ERC721)); // Emoji Script by Travess Smalley (work 2)

        // non-standard
        addContract(0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB, _maxEditions, uint8(cT.Punk)); // CryptoPunks
        // //rinkeby
        // addContract(0x999426cb37bb8Ea786d3E24F6094004fad686f70, _maxEditions, uint8(cT.Punk)); // rinkeby CryptoPunks
    }

    enum cT {ERC721, Punk, Folia, ERC721exception}
    struct ContractInfo {
      cT _cT;
      uint256 editionsLeft;
    }
    mapping(address => ContractInfo) public aC;

    // can be re-used as an "updateContractEditionSize"
    function addContract(address contractAddress, uint256 maxEditions, uint8 _cT ) public onlyOwner {
      
      if (_cT == uint8(cT.ERC721)) {
        require(IERC165(contractAddress).supportsInterface(0x80ac58cd), "Not an ERC721");
      } else {
        require(_cT == uint8(cT.Punk) || _cT == uint8(cT.Folia) || _cT == uint8(cT.ERC721exception), "Unknown contractType");
      }

      aC[contractAddress]._cT = cT(_cT);
      aC[contractAddress].editionsLeft = maxEditions;
      emit newContract(contractAddress, maxEditions, cT(_cT));
    }
    
    function removeContract(address contractAddress) public onlyOwner {
      delete aC[contractAddress];
      emit deletedContract(contractAddress);
    }

    function updateArtworkPrice(uint256 _price) public onlyOwner {
      price = _price;
    }

    function updateArtistWallet(address payable _artistWallet) public onlyOwner {
      artistWallet = _artistWallet;
    }

    function updateTotalMax(uint256 _totalMax) public onlyOwner {
      totalMax = _totalMax;
    }

    function buy(address recipient, address contractAddress, uint256 tokenId) public payable notPaused nonReentrant returns(bool) {
        require(aC[contractAddress].editionsLeft != 0, "Wrong Contract or No Editions Left");
        aC[contractAddress].editionsLeft -= 1;

        require(msg.value == price, "Wrong price paid");

        if (aC[contractAddress]._cT == cT.Punk) {
          require(Punk(contractAddress).punkIndexToAddress(tokenId) == msg.sender, "Can't mint a token you don't own");
        } else if (aC[contractAddress]._cT == cT.ERC721 || aC[contractAddress]._cT == cT.ERC721exception) {
          require(IERC721(contractAddress).ownerOf(tokenId) == msg.sender, "Can't mint a token you don't own");
        } else if (aC[contractAddress]._cT == cT.Folia) {
          //mainnet
          require(tokenId >= 2000000 && tokenId <= 2000500, "Can't mint this Folia token");

          // rinkeby
          // require(tokenId >= 13000000 && tokenId <= 2000058, "Can't mint this Folia token");
          require(IERC721(contractAddress).ownerOf(tokenId) == msg.sender, "Can't mint a token you don't own");
        }

        uint256 newTokenId = uint256(keccak256(abi.encodePacked(contractAddress, tokenId)));
        decomposer.mint(recipient, newTokenId);

        uint256 adminReceives = msg.value.mul(adminSplit).div(100);
        uint256 artistReceives = msg.value.sub(adminReceives);

        (bool success, ) = adminWallet.call.value(adminReceives)("");
        require(success, "admin failed to receive");

        (success, ) = artistWallet.call.value(artistReceives)("");
        require(success, "artist failed to receive");

        emit editionBought(contractAddress, tokenId, newTokenId);
    }

    function updateAdminSplit(uint256 _adminSplit) public onlyOwner {
        require(_adminSplit <= 100, "SPLIT_MUST_BE_LTE_100");
        adminSplit = _adminSplit;
    }

    function updateAdminWallet(address payable _adminWallet) public onlyOwner {
        adminWallet = _adminWallet;
    }

    function updatePaused(bool _paused) public onlyOwner {
        paused = _paused;
    }
}

// File: DecomposerMetadata.sol



pragma solidity ^0.5.0;
/**
* Metadata contract is upgradeable and returns metadata about Token
*/

import "./Metadata.sol";

contract DecomposerMetadata is Metadata {
    function tokenURI(uint _tokenId) public pure returns (string memory _infoUrl) {
        string memory base = "https://decomposer.folia.app/v1/metadata/";
        string memory id = uint2str(_tokenId);
        return base.toSlice().concat(id.toSlice());
    }
}

// File: ERC165.sol



pragma solidity ^0.5.0;

import "./IERC165.sol";

/**
 * @title ERC165
 * @author Matt Condon (@shrugs)
 * @dev Implements ERC165 using a lookup table.
 */
contract ERC165 is IERC165 {
    bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
    /**
     * 0x01ffc9a7 ===
     *     bytes4(keccak256('supportsInterface(bytes4)'))
     */

    /**
     * @dev a mapping of interface id to whether or not it's supported
     */
    mapping(bytes4 => bool) private _supportedInterfaces;

    /**
     * @dev A contract implementing SupportsInterfaceWithLookup
     * implement ERC165 itself
     */
    constructor () internal {
        _registerInterface(_INTERFACE_ID_ERC165);
    }

    /**
     * @dev implement supportsInterface(bytes4) using a lookup table
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool) {
        return _supportedInterfaces[interfaceId];
    }

    /**
     * @dev internal method for registering an interface
     */
    function _registerInterface(bytes4 interfaceId) internal {
        require(interfaceId != 0xffffffff);
        _supportedInterfaces[interfaceId] = true;
    }
}

// File: ERC721.sol



pragma solidity ^0.5.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./SafeMath.sol";
import "./Address.sol";
import "./ERC165.sol";

/**
 * @title ERC721 Non-Fungible Token Standard basic implementation
 * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
 */
contract ERC721 is ERC165, IERC721 {
    using SafeMath for uint256;
    using Address for address;

    // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
    // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
    bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;

    // Mapping from token ID to owner
    mapping (uint256 => address) private _tokenOwner;

    // Mapping from token ID to approved address
    mapping (uint256 => address) private _tokenApprovals;

    // Mapping from owner to number of owned token
    mapping (address => uint256) private _ownedTokensCount;

    // Mapping from owner to operator approvals
    mapping (address => mapping (address => bool)) private _operatorApprovals;

    bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
    /*
     * 0x80ac58cd ===
     *     bytes4(keccak256('balanceOf(address)')) ^
     *     bytes4(keccak256('ownerOf(uint256)')) ^
     *     bytes4(keccak256('approve(address,uint256)')) ^
     *     bytes4(keccak256('getApproved(uint256)')) ^
     *     bytes4(keccak256('setApprovalForAll(address,bool)')) ^
     *     bytes4(keccak256('isApprovedForAll(address,address)')) ^
     *     bytes4(keccak256('transferFrom(address,address,uint256)')) ^
     *     bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
     *     bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
     */

    constructor () public {
        // register the supported interfaces to conform to ERC721 via ERC165
        _registerInterface(_INTERFACE_ID_ERC721);
    }

    /**
     * @dev Gets the balance of the specified address
     * @param owner address to query the balance of
     * @return uint256 representing the amount owned by the passed address
     */
    function balanceOf(address owner) public view returns (uint256) {
        require(owner != address(0));
        return _ownedTokensCount[owner];
    }

    /**
     * @dev Gets the owner of the specified token ID
     * @param tokenId uint256 ID of the token to query the owner of
     * @return owner address currently marked as the owner of the given token ID
     */
    function ownerOf(uint256 tokenId) public view returns (address) {
        address owner = _tokenOwner[tokenId];
        require(owner != address(0));
        return owner;
    }

    /**
     * @dev Approves another address to transfer the given token ID
     * The zero address indicates there is no approved address.
     * There can only be one approved address per token at a given time.
     * Can only be called by the token owner or an approved operator.
     * @param to address to be approved for the given token ID
     * @param tokenId uint256 ID of the token to be approved
     */
    function approve(address to, uint256 tokenId) public {
        address owner = ownerOf(tokenId);
        require(to != owner);
        require(msg.sender == owner || isApprovedForAll(owner, msg.sender));

        _tokenApprovals[tokenId] = to;
        emit Approval(owner, to, tokenId);
    }

    /**
     * @dev Gets the approved address for a token ID, or zero if no address set
     * Reverts if the token ID does not exist.
     * @param tokenId uint256 ID of the token to query the approval of
     * @return address currently approved for the given token ID
     */
    function getApproved(uint256 tokenId) public view returns (address) {
        require(_exists(tokenId));
        return _tokenApprovals[tokenId];
    }

    /**
     * @dev Sets or unsets the approval of a given operator
     * An operator is allowed to transfer all tokens of the sender on their behalf
     * @param to operator address to set the approval
     * @param approved representing the status of the approval to be set
     */
    function setApprovalForAll(address to, bool approved) public {
        require(to != msg.sender);
        _operatorApprovals[msg.sender][to] = approved;
        emit ApprovalForAll(msg.sender, to, approved);
    }

    /**
     * @dev Tells whether an operator is approved by a given owner
     * @param owner owner address which you want to query the approval of
     * @param operator operator address which you want to query the approval of
     * @return bool whether the given operator is approved by the given owner
     */
    function isApprovedForAll(address owner, address operator) public view returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev Transfers the ownership of a given token ID to another address
     * Usage of this method is discouraged, use `safeTransferFrom` whenever possible
     * Requires the msg sender to be the owner, approved, or operator
     * @param from current owner of the token
     * @param to address to receive the ownership of the given token ID
     * @param tokenId uint256 ID of the token to be transferred
    */
    function transferFrom(address from, address to, uint256 tokenId) public {
        require(_isApprovedOrOwner(msg.sender, tokenId));

        _transferFrom(from, to, tokenId);
    }

    /**
     * @dev Safely transfers the ownership of a given token ID to another address
     * If the target address is a contract, it must implement `onERC721Received`,
     * which is called upon a safe transfer, and return the magic value
     * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
     * the transfer is reverted.
     *
     * Requires the msg sender to be the owner, approved, or operator
     * @param from current owner of the token
     * @param to address to receive the ownership of the given token ID
     * @param tokenId uint256 ID of the token to be transferred
    */
    function safeTransferFrom(address from, address to, uint256 tokenId) public {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev Safely transfers the ownership of a given token ID to another address
     * If the target address is a contract, it must implement `onERC721Received`,
     * which is called upon a safe transfer, and return the magic value
     * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
     * the transfer is reverted.
     * Requires the msg sender to be the owner, approved, or operator
     * @param from current owner of the token
     * @param to address to receive the ownership of the given token ID
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes data to send along with a safe transfer check
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
        transferFrom(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, _data));
    }

    /**
     * @dev Returns whether the specified token exists
     * @param tokenId uint256 ID of the token to query the existence of
     * @return whether the token exists
     */
    function _exists(uint256 tokenId) internal view returns (bool) {
        address owner = _tokenOwner[tokenId];
        return owner != address(0);
    }

    /**
     * @dev Returns whether the given spender can transfer a given token ID
     * @param spender address of the spender to query
     * @param tokenId uint256 ID of the token to be transferred
     * @return bool whether the msg.sender is approved for the given token ID,
     *    is an operator of the owner, or is the owner of the token
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
        address owner = ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
    }

    /**
     * @dev Internal function to mint a new token
     * Reverts if the given token ID already exists
     * @param to The address that will own the minted token
     * @param tokenId uint256 ID of the token to be minted
     */
    function _mint(address to, uint256 tokenId) internal {
        require(to != address(0));
        require(!_exists(tokenId));

        _tokenOwner[tokenId] = to;
        _ownedTokensCount[to] = _ownedTokensCount[to].add(1);

        emit Transfer(address(0), to, tokenId);
    }

    /**
     * @dev Internal function to burn a specific token
     * Reverts if the token does not exist
     * Deprecated, use _burn(uint256) instead.
     * @param owner owner of the token to burn
     * @param tokenId uint256 ID of the token being burned
     */
    function _burn(address owner, uint256 tokenId) internal {
        require(ownerOf(tokenId) == owner);

        _clearApproval(tokenId);

        _ownedTokensCount[owner] = _ownedTokensCount[owner].sub(1);
        _tokenOwner[tokenId] = address(0);

        emit Transfer(owner, address(0), tokenId);
    }

    /**
     * @dev Internal function to burn a specific token
     * Reverts if the token does not exist
     * @param tokenId uint256 ID of the token being burned
     */
    function _burn(uint256 tokenId) internal {
        _burn(ownerOf(tokenId), tokenId);
    }

    /**
     * @dev Internal function to transfer ownership of a given token ID to another address.
     * As opposed to transferFrom, this imposes no restrictions on msg.sender.
     * @param from current owner of the token
     * @param to address to receive the ownership of the given token ID
     * @param tokenId uint256 ID of the token to be transferred
    */
    function _transferFrom(address from, address to, uint256 tokenId) internal {
        require(ownerOf(tokenId) == from);
        require(to != address(0));

        _clearApproval(tokenId);

        _ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
        _ownedTokensCount[to] = _ownedTokensCount[to].add(1);

        _tokenOwner[tokenId] = to;

        emit Transfer(from, to, tokenId);
    }

    /**
     * @dev Internal function to invoke `onERC721Received` on a target address
     * The call is not executed if the target address is not a contract
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
        internal returns (bool)
    {
        if (!to.isContract()) {
            return true;
        }

        bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
        return (retval == _ERC721_RECEIVED);
    }

    /**
     * @dev Private function to clear current approval of a given token ID
     * @param tokenId uint256 ID of the token to be transferred
     */
    function _clearApproval(uint256 tokenId) private {
        if (_tokenApprovals[tokenId] != address(0)) {
            _tokenApprovals[tokenId] = address(0);
        }
    }
}

// File: ERC721Enumerable.sol



pragma solidity ^0.5.0;

import "./IERC721Enumerable.sol";
import "./ERC721.sol";
import "./ERC165.sol";

/**
 * @title ERC-721 Non-Fungible Token with optional enumeration extension logic
 * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
 */
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
    // Mapping from owner to list of owned token IDs
    mapping(address => uint256[]) private _ownedTokens;

    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;

    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;

    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;

    bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
    /**
     * 0x780e9d63 ===
     *     bytes4(keccak256('totalSupply()')) ^
     *     bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
     *     bytes4(keccak256('tokenByIndex(uint256)'))
     */

    /**
     * @dev Constructor function
     */
    constructor () public {
        // register the supported interface to conform to ERC721 via ERC165
        _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
    }

    /**
     * @dev Gets the token ID at a given index of the tokens list of the requested owner
     * @param owner address owning the tokens list to be accessed
     * @param index uint256 representing the index to be accessed of the requested tokens list
     * @return uint256 token ID at the given index of the tokens list owned by the requested address
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
        require(index < balanceOf(owner));
        return _ownedTokens[owner][index];
    }

    /**
     * @dev Gets the total amount of tokens stored by the contract
     * @return uint256 representing the total amount of tokens
     */
    function totalSupply() public view returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev Gets the token ID at a given index of all the tokens in this contract
     * Reverts if the index is greater or equal to the total number of tokens
     * @param index uint256 representing the index to be accessed of the tokens list
     * @return uint256 token ID at the given index of the tokens list
     */
    function tokenByIndex(uint256 index) public view returns (uint256) {
        require(index < totalSupply());
        return _allTokens[index];
    }

    /**
     * @dev Internal function to transfer ownership of a given token ID to another address.
     * As opposed to transferFrom, this imposes no restrictions on msg.sender.
     * @param from current owner of the token
     * @param to address to receive the ownership of the given token ID
     * @param tokenId uint256 ID of the token to be transferred
    */
    function _transferFrom(address from, address to, uint256 tokenId) internal {
        super._transferFrom(from, to, tokenId);

        _removeTokenFromOwnerEnumeration(from, tokenId);

        _addTokenToOwnerEnumeration(to, tokenId);
    }

    /**
     * @dev Internal function to mint a new token
     * Reverts if the given token ID already exists
     * @param to address the beneficiary that will own the minted token
     * @param tokenId uint256 ID of the token to be minted
     */
    function _mint(address to, uint256 tokenId) internal {
        super._mint(to, tokenId);

        _addTokenToOwnerEnumeration(to, tokenId);

        _addTokenToAllTokensEnumeration(tokenId);
    }

    /**
     * @dev Internal function to burn a specific token
     * Reverts if the token does not exist
     * Deprecated, use _burn(uint256) instead
     * @param owner owner of the token to burn
     * @param tokenId uint256 ID of the token being burned
     */
    function _burn(address owner, uint256 tokenId) internal {
        super._burn(owner, tokenId);

        _removeTokenFromOwnerEnumeration(owner, tokenId);
        // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
        _ownedTokensIndex[tokenId] = 0;

        _removeTokenFromAllTokensEnumeration(tokenId);
    }

    /**
     * @dev Gets the list of token IDs of the requested owner
     * @param owner address owning the tokens
     * @return uint256[] List of token IDs owned by the requested address
     */
    function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
        return _ownedTokens[owner];
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        _ownedTokensIndex[tokenId] = _ownedTokens[to].length;
        _ownedTokens[to].push(tokenId);
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the _ownedTokensIndex mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        _ownedTokens[from].length--;

        // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occcupied by
        // lasTokenId, or just over the end of the array if the token was the last one).
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length.sub(1);
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        _allTokens.length--;
        _allTokensIndex[tokenId] = 0;
    }
}

// File: ERC721Full.sol



pragma solidity ^0.5.0;

import "./ERC721.sol";
import "./ERC721Enumerable.sol";
import "./ERC721Metadata.sol";

/**
 * @title Full ERC721 Token
 * This implementation includes all the required and some optional functionality of the ERC721 standard
 * Moreover, it includes approve all functionality using operator terminology
 * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
 */
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
    constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) {
        // solhint-disable-previous-line no-empty-blocks
    }
}

// File: ERC721Metadata.sol



pragma solidity ^0.5.0;

import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "./ERC165.sol";

contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Optional mapping for token URIs
    mapping(uint256 => string) private _tokenURIs;

    bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
    /**
     * 0x5b5e139f ===
     *     bytes4(keccak256('name()')) ^
     *     bytes4(keccak256('symbol()')) ^
     *     bytes4(keccak256('tokenURI(uint256)'))
     */

    /**
     * @dev Constructor function
     */
    constructor (string memory name, string memory symbol) public {
        _name = name;
        _symbol = symbol;

        // register the supported interfaces to conform to ERC721 via ERC165
        _registerInterface(_INTERFACE_ID_ERC721_METADATA);
    }

    /**
     * @dev Gets the token name
     * @return string representing the token name
     */
    function name() external view returns (string memory) {
        return _name;
    }

    /**
     * @dev Gets the token symbol
     * @return string representing the token symbol
     */
    function symbol() external view returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns an URI for a given token ID
     * Throws if the token ID does not exist. May return an empty string.
     * @param tokenId uint256 ID of the token to query
     */
    function tokenURI(uint256 tokenId) external view returns (string memory) {
        require(_exists(tokenId));
        return _tokenURIs[tokenId];
    }

    /**
     * @dev Internal function to set the token URI for a given token
     * Reverts if the token ID does not exist
     * @param tokenId uint256 ID of the token to set its URI
     * @param uri string URI to assign
     */
    function _setTokenURI(uint256 tokenId, string memory uri) internal {
        require(_exists(tokenId));
        _tokenURIs[tokenId] = uri;
    }

    /**
     * @dev Internal function to burn a specific token
     * Reverts if the token does not exist
     * Deprecated, use _burn(uint256) instead
     * @param owner owner of the token to burn
     * @param tokenId uint256 ID of the token being burned by the msg.sender
     */
    function _burn(address owner, uint256 tokenId) internal {
        super._burn(owner, tokenId);

        // Clear metadata (if any)
        if (bytes(_tokenURIs[tokenId]).length != 0) {
            delete _tokenURIs[tokenId];
        }
    }
}

// File: Folia.sol



pragma solidity ^0.5.0;
import "./ERC721Full.sol";
import "./IERC20.sol";
import "./Ownable.sol";
import "./Roles.sol";
import "./Metadata.sol";



/**
 * The Token contract does this and that...
 */
contract Folia is ERC721Full, Ownable {
    using Roles for Roles.Role;
    Roles.Role private _admins;
    uint8 admins;

    address public metadata;
    address public controller;

    modifier onlyAdminOrController() {
        require((_admins.has(msg.sender) || msg.sender == controller), "DOES_NOT_HAVE_ADMIN_OR_CONTROLLER_ROLE");
        _;
    }

    constructor(string memory name, string memory symbol, address _metadata) public ERC721Full(name, symbol) {
        metadata = _metadata;
        _admins.add(msg.sender);
        admins += 1;
    }

    function mint(address recepient, uint256 tokenId) public onlyAdminOrController {
        _mint(recepient, tokenId);
    }
    function burn(uint256 tokenId) public onlyAdminOrController {
        _burn(ownerOf(tokenId), tokenId);
    }
    function updateMetadata(address _metadata) public onlyAdminOrController {
        metadata = _metadata;
    }
    function updateController(address _controller) public onlyAdminOrController {
        controller = _controller;
    }

    function addAdmin(address _admin) public onlyOwner {
        _admins.add(_admin);
        admins += 1;
    }
    function removeAdmin(address _admin) public onlyOwner {
        require(admins > 1, "CANT_REMOVE_LAST_ADMIN");
        _admins.remove(_admin);
        admins -= 1;
    }

    function tokenURI(uint _tokenId) external view returns (string memory _infoUrl) {
        return Metadata(metadata).tokenURI(_tokenId);
    }

    /**
    * @dev Moves Eth to a certain address for use in the FoliaController
    * @param _to The address to receive the Eth.
    * @param _amount The amount of Eth to be transferred.
    */
    function moveEth(address payable _to, uint256 _amount) public onlyAdminOrController {
        require(_amount <= address(this).balance);
        _to.transfer(_amount);
    }
    /**
    * @dev Moves Token to a certain address for use in the FoliaController
    * @param _to The address to receive the Token.
    * @param _amount The amount of Token to be transferred.
    * @param _token The address of the Token to be transferred.
    */
    function moveToken(address _to, uint256 _amount, address _token) public onlyAdminOrController returns (bool) {
        require(_amount <= IERC20(_token).balanceOf(address(this)));
        return IERC20(_token).transfer(_to, _amount);
    }

}

// File: IERC165.sol



pragma solidity ^0.5.0;

/**
 * @title IERC165
 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
 */
interface IERC165 {
    /**
     * @notice Query if a contract implements an interface
     * @param interfaceId The interface identifier, as specified in ERC-165
     * @dev Interface identification is specified in ERC-165. This function
     * uses less than 30,000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: IERC20.sol



pragma solidity ^0.5.0;

/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
interface IERC20 {
    function transfer(address to, uint256 value) external returns (bool);

    function approve(address spender, uint256 value) external returns (bool);

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

    function totalSupply() external view returns (uint256);

    function balanceOf(address who) external view returns (uint256);

    function allowance(address owner, address spender) external view returns (uint256);

    event Transfer(address indexed from, address indexed to, uint256 value);

    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// File: IERC721.sol



pragma solidity ^0.5.0;

import "./IERC165.sol";

/**
 * @title ERC721 Non-Fungible Token Standard basic interface
 * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
 */
contract IERC721 is IERC165 {
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    function balanceOf(address owner) public view returns (uint256 balance);
    function ownerOf(uint256 tokenId) public view returns (address owner);

    function approve(address to, uint256 tokenId) public;
    function getApproved(uint256 tokenId) public view returns (address operator);

    function setApprovalForAll(address operator, bool _approved) public;
    function isApprovedForAll(address owner, address operator) public view returns (bool);

    function transferFrom(address from, address to, uint256 tokenId) public;
    function safeTransferFrom(address from, address to, uint256 tokenId) public;

    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}

// File: IERC721Enumerable.sol



pragma solidity ^0.5.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
 */
contract IERC721Enumerable is IERC721 {
    function totalSupply() public view returns (uint256);
    function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);

    function tokenByIndex(uint256 index) public view returns (uint256);
}

// File: IERC721Metadata.sol



pragma solidity ^0.5.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
 */
contract IERC721Metadata is IERC721 {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

// File: IERC721Receiver.sol



pragma solidity ^0.5.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
contract IERC721Receiver {
    /**
     * @notice Handle the receipt of an NFT
     * @dev The ERC721 smart contract calls this function on the recipient
     * after a `safeTransfer`. This function MUST return the function selector,
     * otherwise the caller will revert the transaction. The selector to be
     * returned can be obtained as `this.onERC721Received.selector`. This
     * function MAY throw to revert and reject the transfer.
     * Note: the ERC721 contract address is always the message sender.
     * @param operator The address which called `safeTransferFrom` function
     * @param from The address which previously owned the token
     * @param tokenId The NFT identifier which is being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
     */
    function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
    public returns (bytes4);
}

// File: Metadata.sol



pragma solidity ^0.5.0;
/**
* Metadata contract is upgradeable and returns metadata about Token
*/

import "./strings.sol";

contract Metadata {
    using strings for *;

    function tokenURI(uint _tokenId) public pure returns (string memory _infoUrl) {
        string memory base = "https://folia.app/v1/metadata/";
        string memory id = uint2str(_tokenId);
        return base.toSlice().concat(id.toSlice());
    }
    function uint2str(uint i) internal pure returns (string memory) {
        if (i == 0) return "0";
        uint j = i;
        uint length;
        while (j != 0) {
            length++;
            j /= 10;
        }
        bytes memory bstr = new bytes(length);
        uint k = length - 1;
        while (i != 0) {
            uint _uint = 48 + i % 10;
            bstr[k--] = toBytes(_uint)[31];
            i /= 10;
        }
        return string(bstr);
    }
    function toBytes(uint256 x) public pure returns (bytes memory b) {
        b = new bytes(32);
        assembly { mstore(add(b, 32), x) }
    }
}

// File: Ownable.sol



pragma solidity ^0.5.0;

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 */
contract Ownable {
    address private _owner;

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

    /**
     * @dev The Ownable constructor sets the original `owner` of the contract to the sender
     * account.
     */
    constructor () internal {
        _owner = msg.sender;
        emit OwnershipTransferred(address(0), _owner);
    }

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

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

    /**
     * @return true if `msg.sender` is the owner of the contract.
     */
    function isOwner() public view returns (bool) {
        return msg.sender == _owner;
    }

    /**
     * @dev Allows the current owner to relinquish control of the contract.
     * @notice Renouncing to ownership will leave the contract without an owner.
     * It will not be possible to call the functions with the `onlyOwner`
     * modifier anymore.
     */
    function renounceOwnership() public onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    /**
     * @dev Allows the current owner to transfer control of the contract to a newOwner.
     * @param newOwner The address to transfer ownership to.
     */
    function transferOwnership(address newOwner) public onlyOwner {
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers control of the contract to a newOwner.
     * @param newOwner The address to transfer ownership to.
     */
    function _transferOwnership(address newOwner) internal {
        require(newOwner != address(0));
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

// File: ReentrancyGuard.sol



pragma solidity ^0.5.0;

/**
 * @title Helps contracts guard against reentrancy attacks.
 * @author Remco Bloemen <remco@2π.com>, Eenae <alexey@mixbytes.io>
 * @dev If you mark a function `nonReentrant`, you should also
 * mark it `external`.
 */
contract ReentrancyGuard {
    /// @dev counter to allow mutex lock with only one SSTORE operation
    uint256 private _guardCounter;

    constructor () internal {
        // The counter starts at one to prevent changing it from zero to a non-zero
        // value, which is a more expensive operation.
        _guardCounter = 1;
    }

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

// File: Roles.sol



pragma solidity ^0.5.0;

/**
 * @title Roles
 * @dev Library for managing addresses assigned to a Role.
 */
library Roles {
    struct Role {
        mapping (address => bool) bearer;
    }

    /**
     * @dev give an account access to this role
     */
    function add(Role storage role, address account) internal {
        require(account != address(0));
        require(!has(role, account));

        role.bearer[account] = true;
    }

    /**
     * @dev remove an account's access to this role
     */
    function remove(Role storage role, address account) internal {
        require(account != address(0));
        require(has(role, account));

        role.bearer[account] = false;
    }

    /**
     * @dev check if an account has this role
     * @return bool
     */
    function has(Role storage role, address account) internal view returns (bool) {
        require(account != address(0));
        return role.bearer[account];
    }
}

// File: SafeMath.sol



pragma solidity ^0.5.0;

/**
 * @title SafeMath
 * @dev Unsigned math operations with safety checks that revert on error
 */
library SafeMath {
    /**
    * @dev Multiplies two unsigned integers, reverts on overflow.
    */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b);

        return c;
    }

    /**
    * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
    */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        // Solidity only automatically asserts when dividing by 0
        require(b > 0);
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
    * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
    */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a);
        uint256 c = a - b;

        return c;
    }

    /**
    * @dev Adds two unsigned integers, reverts on overflow.
    */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a);

        return c;
    }

    /**
    * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
    * reverts when dividing by zero.
    */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b != 0);
        return a % b;
    }
}

// File: strings.sol



/*
 * @title String & slice utility library for Solidity contracts.
 * @author Nick Johnson <arachnid@notdot.net>
 */

pragma solidity ^0.5.0;

library strings {
    struct slice {
        uint _len;
        uint _ptr;
    }

    function memcpy(uint dest, uint src, uint len) private pure {
        // Copy word-length chunks while possible
        for (; len >= 32; len -= 32) {
            assembly {
                mstore(dest, mload(src))
            }
            dest += 32;
            src += 32;
        }

        // Copy remaining bytes
        uint mask = 256 ** (32 - len) - 1;
        assembly {
            let srcpart := and(mload(src), not(mask))
            let destpart := and(mload(dest), mask)
            mstore(dest, or(destpart, srcpart))
        }
    }

    /*
     * @dev Returns a slice containing the entire string.
     * @param self The string to make a slice from.
     * @return A newly allocated slice containing the entire string.
     */
    function toSlice(string memory self) internal pure returns (slice memory) {
        uint ptr;
        assembly {
            ptr := add(self, 0x20)
        }
        return slice(bytes(self).length, ptr);
    }

    /*
     * @dev Returns a newly allocated string containing the concatenation of
     *      `self` and `other`.
     * @param self The first slice to concatenate.
     * @param other The second slice to concatenate.
     * @return The concatenation of the two strings.
     */
    function concat(slice memory self, slice memory other) internal pure returns (string memory) {
        string memory ret = new string(self._len + other._len);
        uint retptr;
        assembly {
            retptr := add(ret, 32)
        }
        memcpy(retptr, self._ptr, self._len);
        memcpy(retptr + self._len, other._ptr, other._len);
        return ret;
    }
}