Goerli Testnet

Contract

0x46c3369dEce07176Ad7164906D3593AA4C126d35

Overview

ETH Balance

0 ETH

Token Holdings

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Value
Create Or Return...103896872024-01-17 14:24:4886 days ago1705501488IN
0x46c3369d...A4C126d35
0 ETH0.000172011.50000001
Create Or Return...103413872024-01-08 10:54:0095 days ago1704711240IN
0x46c3369d...A4C126d35
0 ETH0.000172011.50000001
Start Sale103259562024-01-05 11:24:1298 days ago1704453852IN
0x46c3369d...A4C126d35
0 ETH0.000520831.5
Claim Results102906512023-12-29 19:04:36105 days ago1703876676IN
0x46c3369d...A4C126d35
0 ETH0.000106451.50000006
Start Sale102429542023-12-20 15:01:48114 days ago1703084508IN
0x46c3369d...A4C126d35
0 ETH0.00067151.50000001
Create Or Return...102004112023-12-12 11:38:24122 days ago1702381104IN
0x46c3369d...A4C126d35
0 ETH0.000172011.50000002
Create Or Return...99969422023-11-06 15:43:12158 days ago1699285392IN
0x46c3369d...A4C126d35
0 ETH0.000172011.50000001
Create Or Return...99959522023-11-06 11:28:24158 days ago1699270104IN
0x46c3369d...A4C126d35
0 ETH0.000172011.5
Create Or Return...99959282023-11-06 11:22:24158 days ago1699269744IN
0x46c3369d...A4C126d35
0 ETH0.000036071.50000001
Create Or Return...99959282023-11-06 11:22:24158 days ago1699269744IN
0x46c3369d...A4C126d35
0 ETH0.000172011.50000001
Settle99955682023-11-06 9:53:12158 days ago1699264392IN
0x46c3369d...A4C126d35
0 ETH0.000055561.50000001
Claim Results99736512023-11-02 12:44:48162 days ago1698929088IN
0x46c3369d...A4C126d35
0 ETH0.000103061.50000001
Settle99736492023-11-02 12:44:24162 days ago1698929064IN
0x46c3369d...A4C126d35
0 ETH0.000055561.50000001
Claim99728572023-11-02 9:14:48162 days ago1698916488IN
0x46c3369d...A4C126d35
0 ETH00.00000157
Settle99728562023-11-02 9:14:24162 days ago1698916464IN
0x46c3369d...A4C126d35
0 ETH00.00000157
Claim99728432023-11-02 9:11:00162 days ago1698916260IN
0x46c3369d...A4C126d35
0 ETH00.00000158
Claim Results99696662023-11-01 18:37:00163 days ago1698863820IN
0x46c3369d...A4C126d35
0 ETH0.000110241.5
Settle99693312023-11-01 17:05:48163 days ago1698858348IN
0x46c3369d...A4C126d35
0 ETH0.000055551.50000001
Place Bid99686402023-11-01 13:57:48163 days ago1698847068IN
0x46c3369d...A4C126d35
0 ETH0.000260321.5
Place Bid99684822023-11-01 13:18:00163 days ago1698844680IN
0x46c3369d...A4C126d35
0 ETH00.00000001
Start Sale99684722023-11-01 13:14:12163 days ago1698844452IN
0x46c3369d...A4C126d35
0 ETH00.00000001
Place Bid99684612023-11-01 13:10:48163 days ago1698844248IN
0x46c3369d...A4C126d35
0 ETH00.00000001
Place Bid99680372023-11-01 11:16:36163 days ago1698837396IN
0x46c3369d...A4C126d35
0 ETH0.000208841.50000001
Place Bid99679782023-11-01 11:02:48163 days ago1698836568IN
0x46c3369d...A4C126d35
0 ETH0.000285771.50000001
Start Sale99634272023-10-31 15:48:00164 days ago1698767280IN
0x46c3369d...A4C126d35
0 ETH0.000502351.50000001
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Txn Hash Block From To Value
103896872024-01-17 14:24:4886 days ago1705501488
0x46c3369d...A4C126d35
0 ETH
103896872024-01-17 14:24:4886 days ago1705501488
0x46c3369d...A4C126d35
 Contract Creation0 ETH
103413872024-01-08 10:54:0095 days ago1704711240
0x46c3369d...A4C126d35
0 ETH
103413872024-01-08 10:54:0095 days ago1704711240
0x46c3369d...A4C126d35
 Contract Creation0 ETH
103259562024-01-05 11:24:1298 days ago1704453852
0x46c3369d...A4C126d35
0 ETH
103259562024-01-05 11:24:1298 days ago1704453852
0x46c3369d...A4C126d35
0 ETH
103259562024-01-05 11:24:1298 days ago1704453852
0x46c3369d...A4C126d35
0 ETH
103259562024-01-05 11:24:1298 days ago1704453852
0x46c3369d...A4C126d35
0 ETH
103259562024-01-05 11:24:1298 days ago1704453852
0x46c3369d...A4C126d35
0 ETH
103259562024-01-05 11:24:1298 days ago1704453852
0x46c3369d...A4C126d35
0 ETH
102906512023-12-29 19:04:36105 days ago1703876676
0x46c3369d...A4C126d35
0 ETH
102429542023-12-20 15:01:48114 days ago1703084508
0x46c3369d...A4C126d35
0 ETH
102429542023-12-20 15:01:48114 days ago1703084508
0x46c3369d...A4C126d35
0 ETH
102429542023-12-20 15:01:48114 days ago1703084508
0x46c3369d...A4C126d35
0 ETH
102429542023-12-20 15:01:48114 days ago1703084508
0x46c3369d...A4C126d35
0 ETH
102429542023-12-20 15:01:48114 days ago1703084508
0x46c3369d...A4C126d35
 Contract Creation0 ETH
102429542023-12-20 15:01:48114 days ago1703084508
0x46c3369d...A4C126d35
0 ETH
102429542023-12-20 15:01:48114 days ago1703084508
0x46c3369d...A4C126d35
0 ETH
102429542023-12-20 15:01:48114 days ago1703084508
0x46c3369d...A4C126d35
0 ETH
102429542023-12-20 15:01:48114 days ago1703084508
0x46c3369d...A4C126d35
0 ETH
102004112023-12-12 11:38:24122 days ago1702381104
0x46c3369d...A4C126d35
0 ETH
102004112023-12-12 11:38:24122 days ago1702381104
0x46c3369d...A4C126d35
 Contract Creation0 ETH
99969422023-11-06 15:43:12158 days ago1699285392
0x46c3369d...A4C126d35
0 ETH
99969422023-11-06 15:43:12158 days ago1699285392
0x46c3369d...A4C126d35
 Contract Creation0 ETH
99959522023-11-06 11:28:24158 days ago1699270104
0x46c3369d...A4C126d35
0 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
StakedLockingCrowdSale

Compiler Version
v0.8.18+commit.87f61d96

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 38 : StakedLockingCrowdSale.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { FixedPointMathLib } from "solmate/utils/FixedPointMathLib.sol";
import { TokenVesting } from "@moleculeprotocol/token-vesting/TokenVesting.sol";
import { TimelockedToken } from "../TimelockedToken.sol";
import { LockingCrowdSale, UnsupportedInitializer, InvalidDuration } from "./LockingCrowdSale.sol";
import { CrowdSale, Sale, BadDecimals } from "./CrowdSale.sol";

struct StakingInfo {
    //e.g. VITA DAO token
    IERC20Metadata stakedToken;
    TokenVesting stakesVestingContract;
    //fix price (always expressed at 1e18): stake tokens / bid token
    //see https://github.com/moleculeprotocol/IPNFT/pull/100
    uint256 wadFixedStakedPerBidPrice;
}

error IncompatibleVestingContract();
error UnmanageableVestingContract();
error UnsupportedVestingContract();
error BadPrice();

/**
 * @title StakedLockingCrowdSale
 * @author molecule.to
 * @notice a fixed price sales base contract that locks the sold tokens in a configured locking contract and requires vesting another ("dao") token for a certain period of time to participate
 */
contract StakedLockingCrowdSale is LockingCrowdSale, Ownable {
    using SafeERC20 for IERC20Metadata;
    using FixedPointMathLib for uint256;

    mapping(uint256 => StakingInfo) public salesStaking;
    mapping(uint256 => mapping(address => uint256)) internal stakes;
    mapping(address => bool) public trustedVestingContracts;

    event Started(
        uint256 indexed saleId,
        address indexed issuer,
        Sale sale,
        StakingInfo staking,
        TimelockedToken lockingToken,
        uint256 lockingDuration,
        uint256 stakingDuration
    );
    event Staked(uint256 indexed saleId, address indexed bidder, uint256 stakedAmount, uint256 price);
    event ClaimedStakes(uint256 indexed saleId, address indexed claimer, uint256 stakesClaimed, uint256 stakesRefunded);
    event UpdatedTrustedTokenVestings(TokenVesting indexed tokenVesting, bool trusted);

    /// @dev disable parent sale starting functions
    function startSale(Sale calldata, uint256) public pure override returns (uint256) {
        revert UnsupportedInitializer();
    }

    constructor() Ownable() { }

    /**
     * [H-01]
     * @notice this contract can only vest stakes for contracts that it knows so unknown actors cannot start crowdsales with malicious contracts
     * @param stakesVestingContract the
     */
    function trustVestingContract(TokenVesting stakesVestingContract) external onlyOwner {
        if (!stakesVestingContract.hasRole(stakesVestingContract.ROLE_CREATE_SCHEDULE(), address(this))) {
            revert UnmanageableVestingContract();
        }
        trustedVestingContracts[address(stakesVestingContract)] = true;
        emit UpdatedTrustedTokenVestings(stakesVestingContract, true);
    }

    function untrustVestingContract(TokenVesting stakesVestingContract) external onlyOwner {
        trustedVestingContracts[address(stakesVestingContract)] = false;
        emit UpdatedTrustedTokenVestings(stakesVestingContract, false);
    }

    /**
     * @notice if lockingContract is 0x0, a new timelocked token vesting contract clone is automatically created
     *
     * @param sale sale configuration
     * @param stakedToken the ERC20 contract for staking tokens
     * @param stakesVestingContract the TokenVesting contract for vested staking tokens
     * @param wadFixedStakedPerBidPrice the 10e18 based float price for stakes/bid tokens
     * @param lockingDuration duration in seconds until stakes and auction tokens are vested or locked after the sale has settled
     *        NOTE: If `lockingDuration` is < 7 days, the the vesting contract schedules will stil have a 7 days cliff as required by the underlying TokenVesting contract.
     *        timelocks for auction tokens can be >= 0
     * @return saleId
     */
    function startSale(
        Sale calldata sale,
        IERC20Metadata stakedToken,
        TokenVesting stakesVestingContract,
        uint256 wadFixedStakedPerBidPrice,
        uint256 lockingDuration
    ) public returns (uint256 saleId) {
        if (IERC20Metadata(address(stakedToken)).decimals() != 18) {
            revert BadDecimals();
        }

        // [H-01] we only open crowdsales with vesting contracts that we know
        if (!trustedVestingContracts[address(stakesVestingContract)]) {
            revert UnsupportedVestingContract();
        }

        if (address(stakesVestingContract.nativeToken()) != address(stakedToken)) {
            revert IncompatibleVestingContract();
        }

        if (wadFixedStakedPerBidPrice == 0) {
            revert BadPrice();
        }

        //if the bidding token (eg USDC) does not come with 18 decimals, we're adjusting the price here.
        //see https://github.com/moleculeprotocol/IPNFT/pull/100
        if (sale.biddingToken.decimals() != 18) {
            wadFixedStakedPerBidPrice = (wadFixedStakedPerBidPrice * 10 ** 18) / 10 ** sale.biddingToken.decimals();
        }

        saleId = uint256(keccak256(abi.encode(sale)));
        salesStaking[saleId] = StakingInfo(stakedToken, stakesVestingContract, wadFixedStakedPerBidPrice);
        super.startSale(sale, lockingDuration);
    }

    /**
     * @return uint256 how many stakingTokens `bidder` has staked into sale `saleId`
     */
    function stakesOf(uint256 saleId, address bidder) external view returns (uint256) {
        return stakes[saleId][bidder];
    }

    /**
     * @dev emits a custom event for this crowdsale class
     */
    function _afterSaleStarted(uint256 saleId) internal virtual override {
        uint256 stakingDuration = salesLockingDuration[saleId] < 7 days ? 7 days : salesLockingDuration[saleId];
        emit Started(
            saleId,
            msg.sender,
            _sales[saleId],
            salesStaking[saleId],
            lockingContracts[address(_sales[saleId].auctionToken)],
            salesLockingDuration[saleId],
            stakingDuration
        );
    }

    /**
     * @dev computes stake returns for a bidder
     *
     * @param saleId sale id
     * @param refunds amount of bidding tokens being refunded
     * @return refundedStakes wei value of refunded staking tokens
     * @return vestedStakes wei value of staking tokens returned wrapped as vesting tokens
     */
    function getClaimableStakes(uint256 saleId, uint256 refunds) public view virtual returns (uint256 refundedStakes, uint256 vestedStakes) {
        StakingInfo storage staking = salesStaking[saleId];

        refundedStakes = refunds.mulWadDown(staking.wadFixedStakedPerBidPrice);
        vestedStakes = stakes[saleId][msg.sender] - refundedStakes;
    }

    /**
     * @dev calculates the amount of required staking tokens using the provided fix price
     *      will revert if bidder hasn't approved / owns a sufficient amount of staking tokens
     */
    function _bid(uint256 saleId, uint256 biddingTokenAmount) internal virtual override {
        StakingInfo storage staking = salesStaking[saleId];

        uint256 stakedTokenAmount = biddingTokenAmount.mulWadDown(staking.wadFixedStakedPerBidPrice);

        stakes[saleId][msg.sender] += stakedTokenAmount;

        staking.stakedToken.safeTransferFrom(msg.sender, address(this), stakedTokenAmount);

        super._bid(saleId, biddingTokenAmount);
        emit Staked(saleId, msg.sender, stakedTokenAmount, staking.wadFixedStakedPerBidPrice);
    }

    /**
     * @notice refunds stakes and locks active stakes in vesting contract
     * @dev super.claim transitively calls LockingCrowdSale:_claimAuctionTokens
     * @inheritdoc CrowdSale
     */
    function claim(uint256 saleId, uint256 tokenAmount, uint256 refunds) internal virtual override {
        uint256 duration = salesLockingDuration[saleId];
        StakingInfo storage staking = salesStaking[saleId];
        (uint256 refundedStakes, uint256 vestedStakes) = getClaimableStakes(saleId, refunds);

        //EFFECTS
        //this prevents msg.sender to claim twice
        stakes[saleId][msg.sender] = 0;

        // INTERACTIONS
        super.claim(saleId, tokenAmount, refunds);

        if (refundedStakes != 0) {
            staking.stakedToken.safeTransfer(msg.sender, refundedStakes);
        }

        emit ClaimedStakes(saleId, msg.sender, vestedStakes, refundedStakes);

        if (vestedStakes == 0) {
            return;
        }

        //the minimum vesting duration of `TokenVesting` is 7 days
        uint256 _duration = duration < 7 days ? 7 days : duration;
        if (block.timestamp > _sales[saleId].closingTime + _duration) {
            //no need for vesting when duration already expired.
            staking.stakedToken.safeTransfer(msg.sender, vestedStakes);
        } else {
            staking.stakedToken.safeTransfer(address(staking.stakesVestingContract), vestedStakes);
            staking.stakesVestingContract.createVestingSchedule(msg.sender, _sales[saleId].closingTime, _duration, _duration, 60, false, vestedStakes);
        }
    }

    /**
     * @notice will additionally charge back all staked tokens
     * @inheritdoc CrowdSale
     */
    function claimFailed(uint256 saleId) internal override returns (uint256 auctionTokens, uint256 refunds) {
        uint256 refundableStakes = stakes[saleId][msg.sender];
        stakes[saleId][msg.sender] = 0;

        (auctionTokens, refunds) = super.claimFailed(saleId);
        emit ClaimedStakes(saleId, msg.sender, 0, refundableStakes);

        salesStaking[saleId].stakedToken.safeTransfer(msg.sender, refundableStakes);
    }
}

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

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

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

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

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

File 6 of 38 : FixedPointMathLib.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
    /*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
    }

    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
    }

    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
    }

    function powWad(int256 x, int256 y) internal pure returns (int256) {
        // Equivalent to x to the power of y because x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)
        return expWad((lnWad(x) * y) / int256(WAD)); // Using ln(x) means x must be greater than 0.
    }

    function expWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is < 0.5 we return zero. This happens when
            // x <= floor(log(0.5e18) * 1e18) ~ -42e18
            if (x <= -42139678854452767551) return 0;

            // When the result is > (2**255 - 1) / 1e18 we can not represent it as an
            // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.
            if (x >= 135305999368893231589) revert("EXP_OVERFLOW");

            // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96
            // for more intermediate precision and a binary basis. This base conversion
            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
            x = (x << 78) / 5**18;

            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
            int256 k = ((x << 96) / 54916777467707473351141471128 + 2**95) >> 96;
            x = x - k * 54916777467707473351141471128;

            // k is in the range [-61, 195].

            // Evaluate using a (6, 7)-term rational approximation.
            // p is made monic, we'll multiply by a scale factor later.
            int256 y = x + 1346386616545796478920950773328;
            y = ((y * x) >> 96) + 57155421227552351082224309758442;
            int256 p = y + x - 94201549194550492254356042504812;
            p = ((p * y) >> 96) + 28719021644029726153956944680412240;
            p = p * x + (4385272521454847904659076985693276 << 96);

            // We leave p in 2**192 basis so we don't need to scale it back up for the division.
            int256 q = x - 2855989394907223263936484059900;
            q = ((q * x) >> 96) + 50020603652535783019961831881945;
            q = ((q * x) >> 96) - 533845033583426703283633433725380;
            q = ((q * x) >> 96) + 3604857256930695427073651918091429;
            q = ((q * x) >> 96) - 14423608567350463180887372962807573;
            q = ((q * x) >> 96) + 26449188498355588339934803723976023;

            assembly {
                // Div in assembly because solidity adds a zero check despite the unchecked.
                // The q polynomial won't have zeros in the domain as all its roots are complex.
                // No scaling is necessary because p is already 2**96 too large.
                r := sdiv(p, q)
            }

            // r should be in the range (0.09, 0.25) * 2**96.

            // We now need to multiply r by:
            // * the scale factor s = ~6.031367120.
            // * the 2**k factor from the range reduction.
            // * the 1e18 / 2**96 factor for base conversion.
            // We do this all at once, with an intermediate result in 2**213
            // basis, so the final right shift is always by a positive amount.
            r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k));
        }
    }

    function lnWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            require(x > 0, "UNDEFINED");

            // We want to convert x from 10**18 fixed point to 2**96 fixed point.
            // We do this by multiplying by 2**96 / 10**18. But since
            // ln(x * C) = ln(x) + ln(C), we can simply do nothing here
            // and add ln(2**96 / 10**18) at the end.

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            int256 k = int256(log2(uint256(x))) - 96;
            x <<= uint256(159 - k);
            x = int256(uint256(x) >> 159);

            // Evaluate using a (8, 8)-term rational approximation.
            // p is made monic, we will multiply by a scale factor later.
            int256 p = x + 3273285459638523848632254066296;
            p = ((p * x) >> 96) + 24828157081833163892658089445524;
            p = ((p * x) >> 96) + 43456485725739037958740375743393;
            p = ((p * x) >> 96) - 11111509109440967052023855526967;
            p = ((p * x) >> 96) - 45023709667254063763336534515857;
            p = ((p * x) >> 96) - 14706773417378608786704636184526;
            p = p * x - (795164235651350426258249787498 << 96);

            // We leave p in 2**192 basis so we don't need to scale it back up for the division.
            // q is monic by convention.
            int256 q = x + 5573035233440673466300451813936;
            q = ((q * x) >> 96) + 71694874799317883764090561454958;
            q = ((q * x) >> 96) + 283447036172924575727196451306956;
            q = ((q * x) >> 96) + 401686690394027663651624208769553;
            q = ((q * x) >> 96) + 204048457590392012362485061816622;
            q = ((q * x) >> 96) + 31853899698501571402653359427138;
            q = ((q * x) >> 96) + 909429971244387300277376558375;
            assembly {
                // Div in assembly because solidity adds a zero check despite the unchecked.
                // The q polynomial is known not to have zeros in the domain.
                // No scaling required because p is already 2**96 too large.
                r := sdiv(p, q)
            }

            // r is in the range (0, 0.125) * 2**96

            // Finalization, we need to:
            // * multiply by the scale factor s = 5.549…
            // * add ln(2**96 / 10**18)
            // * add k * ln(2)
            // * multiply by 10**18 / 2**96 = 5**18 >> 78

            // mul s * 5e18 * 2**96, base is now 5**18 * 2**192
            r *= 1677202110996718588342820967067443963516166;
            // add ln(2) * k * 5e18 * 2**192
            r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;
            // add ln(2**96 / 10**18) * 5e18 * 2**192
            r += 600920179829731861736702779321621459595472258049074101567377883020018308;
            // base conversion: mul 2**18 / 2**192
            r >>= 174;
        }
    }

    /*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        assembly {
            // Store x * y in z for now.
            z := mul(x, y)

            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                revert(0, 0)
            }

            // Divide z by the denominator.
            z := div(z, denominator)
        }
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        assembly {
            // Store x * y in z for now.
            z := mul(x, y)

            // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
            if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
                revert(0, 0)
            }

            // First, divide z - 1 by the denominator and add 1.
            // We allow z - 1 to underflow if z is 0, because we multiply the
            // end result by 0 if z is zero, ensuring we return 0 if z is zero.
            z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
        }
    }

    function rpow(
        uint256 x,
        uint256 n,
        uint256 scalar
    ) internal pure returns (uint256 z) {
        assembly {
            switch x
            case 0 {
                switch n
                case 0 {
                    // 0 ** 0 = 1
                    z := scalar
                }
                default {
                    // 0 ** n = 0
                    z := 0
                }
            }
            default {
                switch mod(n, 2)
                case 0 {
                    // If n is even, store scalar in z for now.
                    z := scalar
                }
                default {
                    // If n is odd, store x in z for now.
                    z := x
                }

                // Shifting right by 1 is like dividing by 2.
                let half := shr(1, scalar)

                for {
                    // Shift n right by 1 before looping to halve it.
                    n := shr(1, n)
                } n {
                    // Shift n right by 1 each iteration to halve it.
                    n := shr(1, n)
                } {
                    // Revert immediately if x ** 2 would overflow.
                    // Equivalent to iszero(eq(div(xx, x), x)) here.
                    if shr(128, x) {
                        revert(0, 0)
                    }

                    // Store x squared.
                    let xx := mul(x, x)

                    // Round to the nearest number.
                    let xxRound := add(xx, half)

                    // Revert if xx + half overflowed.
                    if lt(xxRound, xx) {
                        revert(0, 0)
                    }

                    // Set x to scaled xxRound.
                    x := div(xxRound, scalar)

                    // If n is even:
                    if mod(n, 2) {
                        // Compute z * x.
                        let zx := mul(z, x)

                        // If z * x overflowed:
                        if iszero(eq(div(zx, x), z)) {
                            // Revert if x is non-zero.
                            if iszero(iszero(x)) {
                                revert(0, 0)
                            }
                        }

                        // Round to the nearest number.
                        let zxRound := add(zx, half)

                        // Revert if zx + half overflowed.
                        if lt(zxRound, zx) {
                            revert(0, 0)
                        }

                        // Return properly scaled zxRound.
                        z := div(zxRound, scalar)
                    }
                }
            }
        }
    }

    /*//////////////////////////////////////////////////////////////
                        GENERAL NUMBER UTILITIES
    //////////////////////////////////////////////////////////////*/

    function sqrt(uint256 x) internal pure returns (uint256 z) {
        assembly {
            let y := x // We start y at x, which will help us make our initial estimate.

            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // We check y >= 2^(k + 8) but shift right by k bits
            // each branch to ensure that if x >= 256, then y >= 256.
            if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                y := shr(128, y)
                z := shl(64, z)
            }
            if iszero(lt(y, 0x1000000000000000000)) {
                y := shr(64, y)
                z := shl(32, z)
            }
            if iszero(lt(y, 0x10000000000)) {
                y := shr(32, y)
                z := shl(16, z)
            }
            if iszero(lt(y, 0x1000000)) {
                y := shr(16, y)
                z := shl(8, z)
            }

            // Goal was to get z*z*y within a small factor of x. More iterations could
            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).
            // We ensured y >= 256 so that the relative difference between y and y+1 is small.
            // That's not possible if x < 256 but we can just verify those cases exhaustively.

            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.

            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.

            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.

            // There is no overflow risk here since y < 2^136 after the first branch above.
            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If x+1 is a perfect square, the Babylonian method cycles between
            // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
            z := sub(z, lt(div(x, z), z))
        }
    }

    function log2(uint256 x) internal pure returns (uint256 r) {
        require(x > 0, "UNDEFINED");

        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            r := or(r, shl(2, lt(0xf, shr(r, x))))
            r := or(r, shl(1, lt(0x3, shr(r, x))))
            r := or(r, lt(0x1, shr(r, x)))
        }
    }

    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            // z will equal 0 if y is 0, unlike in Solidity where it will revert.
            z := mod(x, y)
        }
    }

    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            // z will equal 0 if y is 0, unlike in Solidity where it will revert.
            z := div(x, y)
        }
    }

    /// @dev Will return 0 instead of reverting if y is zero.
    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly {
            // Add 1 to x * y if x % y > 0.
            z := add(gt(mod(x, y), 0), div(x, y))
        }
    }
}

File 7 of 38 : TokenVesting.sol
// contracts/TokenVesting.sol
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.18;

import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { AccessControl } from "@openzeppelin/contracts/access/AccessControl.sol";

import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/security/Pausable.sol";

/// @title TokenVesting - On-Chain vesting scheme enabled by smart contracts.
/// The TokenVesting contract can release its token balance gradually like a
/// typical vesting scheme, with a cliff and vesting period. The contract owner
/// can create vesting schedules for different users, even multiple for the same person.
/// Vesting schedules are optionally revokable by the owner. Additionally the
/// smart contract functions as an ERC20 compatible non-transferable virtual
/// token which can be used e.g. for governance.
/// This work is based on the TokenVesting contract by Abdelhamid Bakhta
/// (https://github.com/abdelhamidbakhta/token-vesting-contracts)
/// and was extended with the virtual token functionality and partially rewritten.
/// @author Schmackofant - [email protected]

contract TokenVesting is IERC20Metadata, Ownable, ReentrancyGuard, Pausable, AccessControl {
    using SafeERC20 for IERC20Metadata;

    /// @notice The ERC20 name of the virtual token
    string public override name;

    /// @notice The ERC20 symbol of the virtual token
    string public override symbol;

    /// @notice The ERC20 number of decimals of the virtual token
    /// @dev This contract only supports native tokens with 18 decimals
    uint8 public constant override decimals = 18;

    enum Status {
        INITIALIZED, //0
        REVOKED
    }

    /**
     * @dev vesting schedule struct
     * @param cliff cliff period in seconds
     * @param start start time of the vesting period
     * @param duration duration of the vesting period in seconds
     * @param slicePeriodSeconds duration of a slice period for the vesting in seconds
     * @param amountTotal total amount of tokens to be released at the end of the vesting
     * @param released amount of tokens released so far
     * @param status schedule status (initialized, revoked)
     * @param beneficiary address of beneficiary of the vesting schedule
     * @param revokable whether or not the vesting is revokable
     */
    struct VestingSchedule {
        uint256 cliff;
        uint256 start;
        uint256 duration;
        uint256 slicePeriodSeconds;
        uint256 amountTotal;
        uint256 released;
        Status status;
        address beneficiary;
        bool revokable;
    }

    /// @notice address of the ERC20 native token
    IERC20Metadata public immutable nativeToken;

    /// @dev This mapping is used to keep track of the vesting schedule ids
    bytes32[] public vestingSchedulesIds;

    /// @dev This mapping is used to keep track of the vesting schedules
    mapping(bytes32 => VestingSchedule) private vestingSchedules;

    /// @notice total amount of native tokens in all vesting schedules
    uint256 public vestingSchedulesTotalAmount;

    /// @notice This mapping is used to keep track of the number of vesting schedules for each beneficiary
    mapping(address => uint256) public holdersVestingScheduleCount;

    /// @dev This mapping is used to keep track of the total amount of vested tokens for each beneficiary
    mapping(address => uint256) private holdersVestedAmount;

    bytes32 public constant ROLE_CREATE_SCHEDULE = keccak256("ROLE_CREATE_SCHEDULE");

    event ScheduleCreated(
        bytes32 indexed scheduleId,
        address indexed beneficiary,
        uint256 amount,
        uint256 start,
        uint256 cliff,
        uint256 duration,
        uint256 slicePeriodSeconds,
        bool revokable
    );
    event TokensReleased(bytes32 indexed scheduleId, address indexed beneficiary, uint256 amount);
    event ScheduleRevoked(bytes32 indexed scheduleId);

    /**
     * @dev Reverts if the vesting schedule does not exist or has been revoked.
     */
    modifier onlyIfVestingScheduleNotRevoked(bytes32 vestingScheduleId) {
        // Check if schedule exists
        if (vestingSchedules[vestingScheduleId].duration == 0) revert InvalidSchedule();
        //slither-disable-next-line incorrect-equality
        if (vestingSchedules[vestingScheduleId].status == Status.REVOKED) revert ScheduleWasRevoked();
        _;
    }

    /// @dev This error is fired when trying to perform an action that is not
    /// supported by the contract, like transfers and approvals. These actions
    /// will never be supported.
    error NotSupported();

    error DecimalsError();
    error InsufficientTokensInContract();
    error InsufficientReleasableTokens();
    error InvalidSchedule();
    error InvalidDuration();
    error InvalidAmount();
    error InvalidSlicePeriod();
    error InvalidStart();
    error DurationShorterThanCliff();
    error NotRevokable();
    error Unauthorized();
    error ScheduleWasRevoked();
    error TooManySchedulesForBeneficiary();

    /**
     * @notice Creates a vesting contract.
     * @param token_ address of the ERC20 native token contract
     * @param _name name of the virtual token
     * @param _symbol symbol of the virtual token
     */
    constructor(IERC20Metadata token_, string memory _name, string memory _symbol) {
        nativeToken = token_;
        if (nativeToken.decimals() != 18) revert DecimalsError();
        name = _name;
        symbol = _symbol;
        _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
        _grantRole(ROLE_CREATE_SCHEDULE, _msgSender());
    }

    /// @dev All types of transfers are permanently disabled.
    function transferFrom(address, address, uint256) public pure override returns (bool) {
        revert NotSupported();
    }

    /// @dev All types of transfers are permanently disabled.
    function transfer(address, uint256) public pure override returns (bool) {
        revert NotSupported();
    }

    /// @dev All types of approvals are permanently disabled to reduce code
    /// size.
    function approve(address, uint256) public pure override returns (bool) {
        revert NotSupported();
    }

    /// @dev Approvals cannot be set, so allowances are always zero.
    function allowance(address, address) public pure override returns (uint256) {
        return 0;
    }

    /// @notice Returns the amount of virtual tokens in existence
    function totalSupply() public view override returns (uint256) {
        return vestingSchedulesTotalAmount;
    }

    /// @notice Returns the sum of virtual tokens for a user
    /// @param user The user for whom the balance is calculated
    /// @return Balance of the user
    function balanceOf(address user) public view override returns (uint256) {
        return holdersVestedAmount[user];
    }

    /**
     * @notice Returns the vesting schedule information for a given holder and index.
     * @return the vesting schedule structure information
     */
    function getVestingScheduleByAddressAndIndex(address holder, uint256 index) external view returns (VestingSchedule memory) {
        return getVestingSchedule(computeVestingScheduleIdForAddressAndIndex(holder, index));
    }

    /**
     * @notice Public function for creating a vesting schedule (only callable by contract owner)
     * @param _beneficiary address of the beneficiary to whom vested tokens are transferred
     * @param _start start time of the vesting period
     * @param _cliff duration in seconds of the cliff in which tokens will begin to vest
     * @param _duration duration in seconds of the period in which the tokens will vest
     * @param _slicePeriodSeconds duration of a slice period for the vesting in seconds
     * @param _revokable whether the vesting is revokable or not
     * @param _amount total amount of tokens to be released at the end of the vesting
     */
    function createVestingSchedule(
        address _beneficiary,
        uint256 _start,
        uint256 _cliff,
        uint256 _duration,
        uint256 _slicePeriodSeconds,
        bool _revokable,
        uint256 _amount
    ) external onlyRole(ROLE_CREATE_SCHEDULE) {
        _createVestingSchedule(_beneficiary, _start, _cliff, _duration, _slicePeriodSeconds, _revokable, _amount);
    }

    /**
     * @notice Creates a new vesting schedule for a beneficiary.
     * @param _beneficiary address of the beneficiary to whom vested tokens are transferred
     * @param _start start time of the vesting period
     * @param _cliff duration in seconds of the cliff in which tokens will begin to vest
     * @param _duration duration in seconds of the period in which the tokens will vest
     * @param _slicePeriodSeconds duration of a slice period for the vesting in seconds
     * @param _revokable whether the vesting is revokable or not
     * @param _amount total amount of tokens to be released at the end of the vesting
     */
    function _createVestingSchedule(
        address _beneficiary,
        uint256 _start,
        uint256 _cliff,
        uint256 _duration,
        uint256 _slicePeriodSeconds,
        bool _revokable,
        uint256 _amount
    ) internal {
        if (getWithdrawableAmount() < _amount) revert InsufficientTokensInContract();

        // _start should be no further away than 30 weeks
        if (_start > block.timestamp + 30 weeks) revert InvalidStart();

        // _duration should be at least 7 days and max 50 years
        if (_duration < 7 days || _duration > 50 * (365 days)) revert InvalidDuration();

        if (_amount == 0) revert InvalidAmount();

        // _slicePeriodSeconds should be at least 60 seconds
        if (_slicePeriodSeconds == 0 || _slicePeriodSeconds > 60) revert InvalidSlicePeriod();

        // _duration must be longer than _cliff
        if (_duration < _cliff) revert DurationShorterThanCliff();

        if (_amount > 2 ** 200) revert InvalidAmount();
        if (holdersVestingScheduleCount[_beneficiary] >= 100) revert TooManySchedulesForBeneficiary();

        bytes32 vestingScheduleId = computeVestingScheduleIdForAddressAndIndex(_beneficiary, holdersVestingScheduleCount[_beneficiary]);
        vestingSchedules[vestingScheduleId] =
            VestingSchedule(_start + _cliff, _start, _duration, _slicePeriodSeconds, _amount, 0, Status.INITIALIZED, _beneficiary, _revokable);
        vestingSchedulesTotalAmount = vestingSchedulesTotalAmount + _amount;
        vestingSchedulesIds.push(vestingScheduleId);
        ++holdersVestingScheduleCount[_beneficiary];
        holdersVestedAmount[_beneficiary] = holdersVestedAmount[_beneficiary] + _amount;
        emit ScheduleCreated(vestingScheduleId, _beneficiary, _amount, _start, _cliff, _duration, _slicePeriodSeconds, _revokable);
    }

    /**
     * @notice Revokes the vesting schedule for given identifier.
     * @param vestingScheduleId the vesting schedule identifier
     */
    function revoke(bytes32 vestingScheduleId) external onlyOwner onlyIfVestingScheduleNotRevoked(vestingScheduleId) {
        VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
        if (!vestingSchedule.revokable) revert NotRevokable();
        if (_computeReleasableAmount(vestingSchedule) > 0) {
            _release(vestingScheduleId, _computeReleasableAmount(vestingSchedule));
        }
        uint256 unreleased = vestingSchedule.amountTotal - vestingSchedule.released;
        vestingSchedulesTotalAmount = vestingSchedulesTotalAmount - unreleased;
        holdersVestedAmount[vestingSchedule.beneficiary] = holdersVestedAmount[vestingSchedule.beneficiary] - unreleased;
        vestingSchedule.status = Status.REVOKED;
        emit ScheduleRevoked(vestingScheduleId);
    }

    /**
     * @notice Pauses or unpauses the release of tokens and claiming of schedules
     * @param paused true if the release of tokens and claiming of schedules should be paused, false otherwise
     */
    function setPaused(bool paused) external onlyOwner {
        if (paused) {
            _pause();
        } else {
            _unpause();
        }
    }

    /**
     * @notice Withdraw the specified amount if possible.
     * @param amount the amount to withdraw
     */
    function withdraw(uint256 amount) external nonReentrant onlyOwner {
        if (amount > getWithdrawableAmount()) revert InsufficientTokensInContract();
        nativeToken.safeTransfer(owner(), amount);
    }

    /**
     * @notice Internal function for releasing vested amount of tokens.
     * @param vestingScheduleId the vesting schedule identifier
     * @param amount the amount to release
     */
    function _release(bytes32 vestingScheduleId, uint256 amount) internal {
        VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId];
        bool isBeneficiary = msg.sender == vestingSchedule.beneficiary;
        bool isOwner = msg.sender == owner();
        if (!isBeneficiary && !isOwner) revert Unauthorized();
        if (amount > _computeReleasableAmount(vestingSchedule)) revert InsufficientReleasableTokens();
        vestingSchedule.released = vestingSchedule.released + amount;
        vestingSchedulesTotalAmount = vestingSchedulesTotalAmount - amount;
        holdersVestedAmount[vestingSchedule.beneficiary] = holdersVestedAmount[vestingSchedule.beneficiary] - amount;
        emit TokensReleased(vestingScheduleId, vestingSchedule.beneficiary, amount);
        nativeToken.safeTransfer(vestingSchedule.beneficiary, amount);
    }

    /**
     * @notice Release vested amount of tokens.
     * @param vestingScheduleId the vesting schedule identifier
     * @param amount the amount to release
     */
    function release(bytes32 vestingScheduleId, uint256 amount) external nonReentrant onlyIfVestingScheduleNotRevoked(vestingScheduleId) {
        _release(vestingScheduleId, amount);
    }

    /**
     * @notice Release all available tokens for holder address
     * @param holder address of the holder & beneficiary
     */
    function releaseAvailableTokensForHolder(address holder) external nonReentrant {
        if (msg.sender != holder && msg.sender != owner()) revert Unauthorized();
        uint256 vestingScheduleCount = holdersVestingScheduleCount[holder];
        for (uint256 i = 0; i < vestingScheduleCount; i++) {
            bytes32 vestingScheduleId = computeVestingScheduleIdForAddressAndIndex(holder, i);
            uint256 releasable = computeReleasableAmount(vestingScheduleId);
            if (releasable > 0) {
                _release(vestingScheduleId, releasable);
            }
        }
    }

    /**
     * @notice Returns the array of vesting schedule ids
     * @return vestingSchedulesIds
     */
    function getVestingSchedulesIds() external view returns (bytes32[] memory) {
        return vestingSchedulesIds;
    }

    /**
     * @notice Computes the vested amount of tokens for the given vesting schedule identifier.
     * @return the vested amount
     */
    function computeReleasableAmount(bytes32 vestingScheduleId) public view onlyIfVestingScheduleNotRevoked(vestingScheduleId) returns (uint256) {
        return _computeReleasableAmount(vestingSchedules[vestingScheduleId]);
    }

    /**
     * @notice Returns the vesting schedule information for a given identifier.
     * @return the vesting schedule structure information
     */
    function getVestingSchedule(bytes32 vestingScheduleId) public view returns (VestingSchedule memory) {
        return vestingSchedules[vestingScheduleId];
    }

    /**
     * @notice Returns the amount of native tokens that can be withdrawn by the owner.
     * @return the amount of tokens
     */
    function getWithdrawableAmount() public view returns (uint256) {
        return nativeToken.balanceOf(address(this)) - vestingSchedulesTotalAmount;
    }

    /**
     * @notice Computes the vesting schedule identifier for an address and an index.
     */
    function computeVestingScheduleIdForAddressAndIndex(address holder, uint256 index) public pure returns (bytes32) {
        return keccak256(abi.encodePacked(holder, index));
    }

    /**
     * @dev Computes the releasable amount of tokens for a vesting schedule.
     * @return the amount of releasable tokens
     */
    function _computeReleasableAmount(VestingSchedule storage vestingSchedule) internal view returns (uint256) {
        uint256 currentTime = block.timestamp;
        //slither-disable-next-line incorrect-equality
        if (currentTime < vestingSchedule.cliff || vestingSchedule.status == Status.REVOKED) {
            return 0;
        } else if (currentTime >= vestingSchedule.start + vestingSchedule.duration) {
            return vestingSchedule.amountTotal - vestingSchedule.released;
        } else {
            uint256 timeFromStart = currentTime - vestingSchedule.start;
            uint256 secondsPerSlice = vestingSchedule.slicePeriodSeconds;
            uint256 vestedSlicePeriods = timeFromStart / secondsPerSlice;
            // Disable warning: duration and token amounts are checked in schedule creation and prevent underflow/overflow
            //slither-disable-next-line divide-before-multiply
            uint256 vestedSeconds = vestedSlicePeriods * secondsPerSlice;
            // Disable warning: duration and token amounts are checked in schedule creation and prevent underflow/overflow
            //slither-disable-next-line divide-before-multiply
            uint256 vestedAmount = vestingSchedule.amountTotal * vestedSeconds / vestingSchedule.duration;
            return vestedAmount - vestingSchedule.released;
        }
    }
}

File 8 of 38 : TimelockedToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import { IERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import { IERC20MetadataUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

struct Schedule {
    uint64 expiresAt;
    address beneficiary;
    uint256 amount;
}

error NotSupported();
error ScheduleOutOfRange();
error StillLocked();
error DuplicateSchedule();

/**
 * @title TimelockedToken
 * @author molecule.to
 * @notice wraps & locks an underlying ERC20 token for a scheduled amount of time
 * @dev we were considering EIP-1132 but use a far more reduced interface that requires tracing due unlocking schedules off chain
 */
contract TimelockedToken is IERC20MetadataUpgradeable, Initializable {
    using SafeERC20 for IERC20Metadata;

    IERC20Metadata public underlyingToken;
    uint256 public totalSupply;
    mapping(address => uint256) balances;
    mapping(bytes32 => Schedule) public schedules;

    event ScheduleCreated(bytes32 indexed scheduleId, address indexed beneficiary, address indexed creator, uint256 amount, uint64 expiresAt);
    event ScheduleReleased(bytes32 indexed scheduleId, address indexed beneficiary, uint256 amount);

    function initialize(IERC20Metadata underlyingToken_) external initializer {
        underlyingToken = underlyingToken_;
    }

    /**
     * @inheritdoc IERC20MetadataUpgradeable
     */
    function name() external view returns (string memory) {
        return string.concat("Locked ", underlyingToken.name());
    }

    /**
     * @inheritdoc IERC20MetadataUpgradeable
     */
    function symbol() external view returns (string memory) {
        return string.concat("l", underlyingToken.symbol());
    }

    /**
     * @inheritdoc IERC20MetadataUpgradeable
     */
    function decimals() external view returns (uint8) {
        return underlyingToken.decimals();
    }
    /**
     * @inheritdoc IERC20Upgradeable
     */

    function transfer(address, uint256) external pure returns (bool) {
        revert NotSupported();
    }

    /**
     * @inheritdoc IERC20Upgradeable
     */
    function approve(address, uint256) external pure returns (bool) {
        revert NotSupported();
    }

    /**
     * @inheritdoc IERC20Upgradeable
     */
    function transferFrom(address, address, uint256) external pure returns (bool) {
        revert NotSupported();
    }

    /**
     * @inheritdoc IERC20Upgradeable
     */
    function allowance(address, address) external pure returns (uint256) {
        return 0;
    }

    /**
     * @inheritdoc IERC20Upgradeable
     */
    function balanceOf(address account) external view returns (uint256) {
        return balances[account];
    }

    /**
     * @notice lock `amount` tokens for `beneficiary` to withdraw until `expiresAt`
     * @param beneficiary the account that will be able to unlock `amount` after `expiresAt`
     * @param amount the amount to be locked
     * @param expiresAt the timestamp when `amount` should become unlockable
     * @return scheduleId the schedule's id. Must be tracked off chain
     */
    function lock(address beneficiary, uint256 amount, uint64 expiresAt) external returns (bytes32 scheduleId) {
        if (expiresAt < block.timestamp + 15 minutes || expiresAt > block.timestamp + 5 * 365 days) {
            revert ScheduleOutOfRange();
        }

        scheduleId = keccak256(abi.encodePacked(msg.sender, beneficiary, amount, expiresAt));
        if (schedules[scheduleId].beneficiary != address(0)) {
            revert DuplicateSchedule();
        }

        schedules[scheduleId] = Schedule(expiresAt, beneficiary, amount);
        balances[beneficiary] += amount;
        totalSupply += amount;
        emit ScheduleCreated(scheduleId, beneficiary, msg.sender, amount, expiresAt);

        underlyingToken.safeTransferFrom(msg.sender, address(this), amount);
    }

    /**
     * @notice releases the amount tracked by schedule `scheduleId` if schedule's date has expired
     * @param scheduleId the schedule's id
     */
    function release(bytes32 scheduleId) public {
        Schedule memory schedule = schedules[scheduleId];
        if (schedule.expiresAt > block.timestamp) {
            revert StillLocked();
        }
        totalSupply -= schedule.amount;
        balances[schedule.beneficiary] -= schedule.amount;
        emit ScheduleReleased(scheduleId, schedule.beneficiary, schedule.amount);
        delete schedules[scheduleId];

        underlyingToken.safeTransfer(schedule.beneficiary, schedule.amount);
    }

    /**
     * @notice releases many schedules at once, reverts when any of them is invalid
     * @param scheduleIds the schedule ids to release
     */
    function releaseMany(bytes32[] calldata scheduleIds) external {
        for (uint256 i = 0; i < scheduleIds.length; i++) {
            release(scheduleIds[i]);
        }
    }
}

File 9 of 38 : LockingCrowdSale.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";

import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
import { TimelockedToken } from "../TimelockedToken.sol";
import { CrowdSale, Sale } from "./CrowdSale.sol";

error UnsupportedInitializer();
error InvalidDuration();

/**
 * @title LockingCrowdSale
 * @author molecule.to
 * @notice a fixed price sales base contract that locks the sold tokens in a configured vesting scheme
 */
contract LockingCrowdSale is CrowdSale {
    using SafeERC20 for IERC20Metadata;

    mapping(uint256 => uint256) public salesLockingDuration;

    /// @notice map from token address to locked token contracts for reusability
    mapping(address => TimelockedToken) public lockingContracts;

    address immutable lockingTokenImplementation = address(new TimelockedToken());

    event Started(uint256 indexed saleId, address indexed issuer, Sale sale, TimelockedToken lockingToken, uint256 lockingDuration);
    event LockingContractCreated(TimelockedToken indexed lockingContract, IERC20Metadata indexed underlyingToken);

    /// @dev disable parent sale starting functions
    function startSale(Sale calldata) public pure override returns (uint256) {
        revert UnsupportedInitializer();
    }

    /**
     * @notice allows anyone to create a timelocked token that's controlled by this sale contract
     *         helpful if you want to reuse the timelocked token for your own custom schedules
     *         before having created any crowdsale on it.
     * @param underlyingToken the token a timelocked token contract is created for
     * @return lockedTokenContract the timelocked token contract either having been created or already existing
     */
    function createOrReturnTimelockContract(IERC20Metadata underlyingToken) public returns (TimelockedToken lockedTokenContract) {
        lockedTokenContract = lockingContracts[address(underlyingToken)];

        if (address(lockedTokenContract) == address(0)) {
            lockedTokenContract = _makeNewLockedTokenContract(underlyingToken);
            lockingContracts[address(underlyingToken)] = lockedTokenContract;
        }
    }

    /**
     * @notice will instantiate a new TimelockedToken when none exists yet
     *
     * @param sale sale configuration
     * @param lockingDuration duration after which the receiver can redeem their tokens
     * @return saleId the newly created sale's id
     */
    function startSale(Sale calldata sale, uint256 lockingDuration) public virtual returns (uint256 saleId) {
        saleId = uint256(keccak256(abi.encode(sale)));

        if (lockingDuration > 366 days) {
            revert InvalidDuration();
        }
        createOrReturnTimelockContract(sale.auctionToken);

        salesLockingDuration[saleId] = lockingDuration;
        saleId = super.startSale(sale);
    }

    function _afterSaleStarted(uint256 saleId) internal virtual override {
        emit Started(saleId, msg.sender, _sales[saleId], lockingContracts[address(_sales[saleId].auctionToken)], salesLockingDuration[saleId]);
    }

    function _afterSaleSettled(uint256 saleId) internal override {
        Sale storage sale = _sales[saleId];
        TimelockedToken lockingContract = lockingContracts[address(sale.auctionToken)];
        uint256 currentAllowance = sale.auctionToken.allowance(address(this), address(lockingContract));
        sale.auctionToken.forceApprove(address(lockingContract), currentAllowance + sale.salesAmount);
    }

    /**
     * @dev will send auction tokens to the configured timelock contract.
     *
     * @param saleId sale id
     * @param tokenAmount amount of tokens to vest
     */
    function _claimAuctionTokens(uint256 saleId, uint256 tokenAmount) internal virtual override {
        uint256 duration = salesLockingDuration[saleId];
        TimelockedToken lockingContract = lockingContracts[address(_sales[saleId].auctionToken)];

        //the vesting start time is the official auction closing time
        if (block.timestamp > _sales[saleId].closingTime + duration) {
            //no need for vesting when cliff already expired.
            _sales[saleId].auctionToken.safeTransfer(msg.sender, tokenAmount);
        } else {
            lockingContract.lock(msg.sender, tokenAmount, SafeCast.toUint64(_sales[saleId].closingTime + duration));
        }
    }

    /**
     * @dev deploys a new timelocked token contract for the auctionToken
     *      to save on gas and improve UX, this should only be called once per auctionToken.
     *      If a timelocked token contract already exists for auctionToken, you can provide it when initializing the sale.
     * @param auctionToken the auction token that a timelocked token contract is created for
     * @return lockedTokenContract address of the new timelocked token contract
     */
    function _makeNewLockedTokenContract(IERC20Metadata auctionToken) private returns (TimelockedToken lockedTokenContract) {
        lockedTokenContract = TimelockedToken(Clones.clone(lockingTokenImplementation));
        lockedTokenContract.initialize(auctionToken);
        emit LockingContractCreated(lockedTokenContract, auctionToken);
    }
}

File 10 of 38 : CrowdSale.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import { FixedPointMathLib } from "solmate/utils/FixedPointMathLib.sol";
import { IPermissioner } from "../Permissioner.sol";
import { Molecules } from "../Molecules.sol";

enum SaleState {
    UNKNOWN,
    RUNNING,
    SETTLED,
    FAILED
}

struct Sale {
    IERC20Metadata auctionToken;
    IERC20Metadata biddingToken;
    address beneficiary;
    //how many bidding tokens to collect
    uint256 fundingGoal;
    //how many auction tokens to sell
    uint256 salesAmount;
    //a timestamp
    uint64 closingTime;
    //can be address(0) if there are no rules to enforce on token actions
    IPermissioner permissioner;
}

struct SaleInfo {
    SaleState state;
    uint256 total;
    uint256 surplus;
    bool claimed;
}

error BadDecimals();
error BadSalesAmount();
error BadSaleDuration();
error SaleAlreadyActive();
error SaleClosedForBids();

error BidTooLow();
error SaleNotFund(uint256);
error SaleNotConcluded();
error BadSaleState(SaleState expected, SaleState actual);
error AlreadyClaimed();

/**
 * @title CrowdSale
 * @author molecule.to
 * @notice a fixed price sales base contract
 */
contract CrowdSale is ReentrancyGuard {
    using SafeERC20 for IERC20Metadata;
    using FixedPointMathLib for uint256;

    mapping(uint256 => Sale) internal _sales;
    mapping(uint256 => SaleInfo) internal _saleInfo;

    mapping(uint256 => mapping(address => uint256)) internal _contributions;

    event Started(uint256 indexed saleId, address indexed issuer, Sale sale);
    event Settled(uint256 indexed saleId, uint256 totalBids, uint256 surplus);
    /// @notice emitted when participants of the sale claim their tokens
    event Claimed(uint256 indexed saleId, address indexed claimer, uint256 claimed, uint256 refunded);
    event Bid(uint256 indexed saleId, address indexed bidder, uint256 amount);
    event Failed(uint256 indexed saleId);

    /// @notice emitted when sales owner / beneficiary claims `fundingGoal` `biddingTokens` after a successful sale
    event ClaimedFundingGoal(uint256 indexed saleId);

    /// @notice emitted when sales owner / beneficiary claims `salesAmount` `auctionTokens` after a non successful sale
    event ClaimedAuctionTokens(uint256 indexed saleId);

    /**
     * @notice bidding tokens can have arbitrary decimals, auctionTokens must be 18 decimals
     *         if no beneficiary is provided, the beneficiary will be set to msg.sender
     *         caller must approve `sale.fundingGoal` auctionTokens before calling this.
     * @param sale the sale's base configuration.
     * @return saleId
     */
    function startSale(Sale calldata sale) public virtual returns (uint256 saleId) {
        //[M-02]
        if (sale.closingTime < block.timestamp || sale.closingTime > block.timestamp + 180 days) {
            revert BadSaleDuration();
        }

        if (sale.auctionToken.decimals() != 18) {
            revert BadDecimals();
        }

        //close to 0 cases lead to precision issues.Using 0.01 bidding tokens as minimium funding goal
        if (sale.fundingGoal < 10 ** (sale.biddingToken.decimals() - 2) || sale.salesAmount < 0.5 ether) {
            revert BadSalesAmount();
        }

        saleId = uint256(keccak256(abi.encode(sale)));
        if (address(_sales[saleId].auctionToken) != address(0)) {
            revert SaleAlreadyActive();
        }

        _sales[saleId] = sale;
        _saleInfo[saleId] = SaleInfo(SaleState.RUNNING, 0, 0, false);

        sale.auctionToken.safeTransferFrom(msg.sender, address(this), sale.salesAmount);
        _afterSaleStarted(saleId);
    }

    /**
     * @return SaleInfo information about the sale
     */
    function getSaleInfo(uint256 saleId) external view returns (SaleInfo memory) {
        return _saleInfo[saleId];
    }

    /**
     * @param saleId sale id
     * @param contributor address
     * @return uint256 the amount of bidding tokens `contributor` has bid into the sale
     */
    function contribution(uint256 saleId, address contributor) external view returns (uint256) {
        return _contributions[saleId][contributor];
    }

    /**
     * @dev even though `auctionToken` is casted to `Molecules` this should still work with IPNFT agnostic tokens
     * @param saleId the sale id
     * @param biddingTokenAmount the amount of bidding tokens
     * @param permission bytes are handed over to a configured permissioner contract. Set to 0x0 / "" / [] if not needed
     */
    function placeBid(uint256 saleId, uint256 biddingTokenAmount, bytes calldata permission) public {
        if (biddingTokenAmount == 0) {
            revert BidTooLow();
        }

        Sale storage sale = _sales[saleId];
        if (sale.fundingGoal == 0) {
            revert SaleNotFund(saleId);
        }

        // @notice: while the general rule is that no bids aren't accepted past the sale's closing time
        //          it's still possible for derived contracts to fail a sale early by changing the sale's state
        if (block.timestamp > sale.closingTime || _saleInfo[saleId].state != SaleState.RUNNING) {
            revert SaleClosedForBids();
        }

        if (address(sale.permissioner) != address(0)) {
            sale.permissioner.accept(Molecules(address(sale.auctionToken)), msg.sender, permission);
        }

        _bid(saleId, biddingTokenAmount);
    }

    /**
     * @notice anyone can call this for the beneficiary.
     *         Releases raised funds to beneficiary when funding goal was met
     *         Returns all auction tokens to beneficiary (auctioneer) when funding goal was not met
     * @param saleId the sale id
     */
    function settle(uint256 saleId) public virtual nonReentrant {
        Sale storage sale = _sales[saleId];
        SaleInfo storage saleInfo = _saleInfo[saleId];

        if (block.timestamp < sale.closingTime) {
            revert SaleNotConcluded();
        }

        if (saleInfo.state != SaleState.RUNNING) {
            revert BadSaleState(SaleState.RUNNING, saleInfo.state);
        }

        if (saleInfo.total < sale.fundingGoal) {
            saleInfo.state = SaleState.FAILED;
            emit Failed(saleId);
            return;
        }
        saleInfo.state = SaleState.SETTLED;
        saleInfo.surplus = saleInfo.total - sale.fundingGoal;

        emit Settled(saleId, saleInfo.total, saleInfo.surplus);
        _afterSaleSettled(saleId);
    }

    /**
     * @notice [L-02] lets the auctioneer pull the results of a succeeded / failed crowdsale
     *         only callable once after the sale was settled
     *         this is callable by anonye
     * @param saleId the sale id
     */
    function claimResults(uint256 saleId) external virtual {
        SaleInfo storage saleInfo = _saleInfo[saleId];
        if (saleInfo.claimed) {
            revert AlreadyClaimed();
        }
        saleInfo.claimed = true;

        Sale storage sale = _sales[saleId];
        if (saleInfo.state == SaleState.SETTLED) {
            //transfer funds to issuer / beneficiary
            emit ClaimedFundingGoal(saleId);
            sale.biddingToken.safeTransfer(sale.beneficiary, sale.fundingGoal);
        } else if (saleInfo.state == SaleState.FAILED) {
            //return auction tokens
            emit ClaimedAuctionTokens(saleId);
            sale.auctionToken.safeTransfer(sale.beneficiary, sale.salesAmount);
        } else {
            revert BadSaleState(SaleState.SETTLED, saleInfo.state);
        }
    }

    function _afterSaleSettled(uint256 saleId) internal virtual { }

    /**
     * @dev computes commitment ratio of bidder
     *
     * @param saleId sale id
     * @param bidder bidder
     * @return auctionTokens wei value of auction tokens to return
     * @return refunds wei value of bidding tokens to return
     */
    function getClaimableAmounts(uint256 saleId, address bidder) public view virtual returns (uint256 auctionTokens, uint256 refunds) {
        SaleInfo storage saleInfo = _saleInfo[saleId];
        uint256 biddingRatio = (saleInfo.total == 0) ? 0 : _contributions[saleId][bidder].divWadDown(saleInfo.total);
        auctionTokens = biddingRatio.mulWadDown(_sales[saleId].salesAmount);

        if (saleInfo.surplus != 0) {
            refunds = biddingRatio.mulWadDown(saleInfo.surplus);
        }
    }

    /**
     * @dev even though `auctionToken` is casted to `Molecules` this should still work with IPNFT agnostic tokens
     * @notice public method that refunds and lets user redeem their sales shares
     * @param saleId the sale id
     * @param permission. bytes are handed over to a configured permissioner contract
     */
    function claim(uint256 saleId, bytes memory permission) external nonReentrant returns (uint256 auctionTokens, uint256 refunds) {
        SaleState currentState = _saleInfo[saleId].state;
        if (currentState == SaleState.FAILED) {
            return claimFailed(saleId);
        }
        //[L-05]
        if (currentState != SaleState.SETTLED) {
            revert BadSaleState(SaleState.SETTLED, currentState);
        }

        Sale storage sales = _sales[saleId];
        //we're not querying the permissioner if the sale has failed.
        if (address(sales.permissioner) != address(0)) {
            sales.permissioner.accept(Molecules(address(sales.auctionToken)), msg.sender, permission);
        }
        (auctionTokens, refunds) = getClaimableAmounts(saleId, msg.sender);
        //a reentrancy won't have any effect after setting this to 0.
        _contributions[saleId][msg.sender] = 0;
        claim(saleId, auctionTokens, refunds);
    }

    /**
     * @dev will send `tokenAmount` auction tokens and `refunds` bidding tokens to msg.sender
     *      This trusts the caller to have checked the amount
     *
     * @param saleId sale id
     * @param tokenAmount amount of tokens to claim.
     * @param refunds biddingTokens to refund
     */
    function claim(uint256 saleId, uint256 tokenAmount, uint256 refunds) internal virtual {
        //the sender has claimed already
        if (tokenAmount == 0) {
            return;
        }
        emit Claimed(saleId, msg.sender, tokenAmount, refunds);

        if (refunds != 0) {
            _sales[saleId].biddingToken.safeTransfer(msg.sender, refunds);
        }
        _claimAuctionTokens(saleId, tokenAmount);
    }

    /**
     * @dev lets users claim back refunds when the sale has failed
     *
     * @param saleId sale id
     * @return auctionTokens the amount of auction tokens claimed (0)
     * @return refunds the amount of bidding tokens refunded
     */
    function claimFailed(uint256 saleId) internal virtual returns (uint256 auctionTokens, uint256 refunds) {
        uint256 _contribution = _contributions[saleId][msg.sender];
        _contributions[saleId][msg.sender] = 0;
        emit Claimed(saleId, msg.sender, 0, _contribution);
        _sales[saleId].biddingToken.safeTransfer(msg.sender, _contribution);
        return (0, _contribution);
    }

    /**
     * @dev internal bid method
     * increases bidder's contribution counter
     * increases sale's bid total
     *
     * @param saleId sale id
     * @param biddingTokenAmount the amount of tokens bid to the sale
     */
    function _bid(uint256 saleId, uint256 biddingTokenAmount) internal virtual {
        _saleInfo[saleId].total += biddingTokenAmount;
        _contributions[saleId][msg.sender] += biddingTokenAmount;
        _sales[saleId].biddingToken.safeTransferFrom(msg.sender, address(this), biddingTokenAmount);
        emit Bid(saleId, msg.sender, biddingTokenAmount);
    }

    /**
     * @dev overridden in LockingCrowdSale (will lock auction tokens in vested contract)
     */
    function _claimAuctionTokens(uint256 saleId, uint256 tokenAmount) internal virtual {
        _sales[saleId].auctionToken.safeTransfer(msg.sender, tokenAmount);
    }

    /**
     * @dev allows us to emit different events per derived contract
     */
    function _afterSaleStarted(uint256 saleId) internal virtual {
        emit Started(saleId, msg.sender, _sales[saleId]);
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

File 14 of 38 : 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 15 of 38 : AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";

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

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

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

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

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

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

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

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

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

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

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

        _revokeRole(role, account);
    }

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

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

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

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

File 17 of 38 : Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

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

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

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

File 20 of 38 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

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

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

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

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

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

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

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

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

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

File 21 of 38 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 22 of 38 : Clones.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol)

pragma solidity ^0.8.0;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        require(instance != address(0), "ERC1167: create2 failed");
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

File 23 of 38 : Permissioner.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import { SignatureChecker } from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import { Molecules, Metadata } from "./Molecules.sol";

error InvalidSignature();
error Denied();

interface IPermissioner {
    /**
     * @notice reverts when `_for` may not interact with `tokenContract`
     * @param tokenContract IMolecules
     * @param _for address
     * @param data bytes
     */
    function accept(Molecules tokenContract, address _for, bytes calldata data) external;
}

contract BlindPermissioner is IPermissioner {
    function accept(Molecules tokenContract, address _for, bytes calldata data) external {
        //empty
    }
}

contract ForbidAllPermissioner is IPermissioner {
    function accept(Molecules, address, bytes calldata) external pure {
        revert Denied();
    }
}

contract TermsAcceptedPermissioner is IPermissioner {
    event TermsAccepted(address indexed tokenContract, address indexed signer, bytes signature);

    /**
     * @notice checks validity signer`'s `signature` of `specificTermsV1` on `moleculesId` and emits an event
     *         reverts when `signature` can't be verified
     * @dev the signature itself or whether it has already been presented is not stored on chain
     *      uses OZ:`SignatureChecker` under the hood and also supports EIP1271 signatures
     *
     * @param tokenContract Molecules
     * @param _for address the account that has created `signature`
     * @param signature bytes encoded signature, for eip155: `abi.encodePacked(r, s, v)`
     */
    function accept(Molecules tokenContract, address _for, bytes calldata signature) external {
        if (!isValidSignature(tokenContract, _for, signature)) {
            revert InvalidSignature();
        }
        emit TermsAccepted(address(tokenContract), _for, signature);
    }

    /**
     * @notice checks whether `signer`'s `signature` of `specificTermsV1` on `moleculeId` is valid
     * @param tokenContract Molecules
     */
    function isValidSignature(Molecules tokenContract, address signer, bytes calldata signature) public view returns (bool) {
        bytes32 termsHash = ECDSA.toEthSignedMessageHash(bytes(specificTermsV1(tokenContract)));
        return SignatureChecker.isValidSignatureNow(signer, termsHash, signature);
    }

    function specificTermsV1(Metadata memory metadata) public view returns (string memory) {
        return string.concat(
            "As a molecule holder of IPNFT #",
            Strings.toString(metadata.ipnftId),
            ", I accept all terms that I've read here: ipfs://",
            metadata.agreementCid,
            "\n\n",
            "Chain Id: ",
            Strings.toString(block.chainid),
            "\n",
            "Version: 1"
        );
    }

    /**
     * @notice this yields the message text that claimers must present as signed message to burn their molecules and claim shares
     * @param tokenContract ISynthesizedToken
     */
    function specificTermsV1(Molecules tokenContract) public view returns (string memory) {
        return (specificTermsV1(tokenContract.metadata()));
    }
}

File 24 of 38 : Molecules.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import { ERC20BurnableUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { Base64 } from "@openzeppelin/contracts/utils/Base64.sol";

struct Metadata {
    uint256 ipnftId;
    address originalOwner;
    string agreementCid;
}

error TokenCapped();
error OnlyIssuerOrOwner();

/**
 * @title Molecules
 * @author molecule.to
 * @notice this is a template contract that's spawned by the Synthesizer
 * @notice the owner of this contract is always the Synthesizer contract.
 *         the issuer of a token bears the right to increase the supply as long as the token is not capped.
 */
contract Molecules is ERC20BurnableUpgradeable, OwnableUpgradeable {
    event Capped(uint256 atSupply);

    //this will only go up.
    uint256 public totalIssued;
    /**
     * @notice when true, no one can ever mint tokens again.
     */
    bool public capped;
    Metadata internal _metadata;

    function initialize(string calldata name, string calldata symbol, Metadata calldata metadata_) external initializer {
        __Ownable_init();
        __ERC20_init(name, symbol);
        _metadata = metadata_;
    }

    modifier onlyIssuerOrOwner() {
        if (_msgSender() != _metadata.originalOwner && _msgSender() != owner()) {
            revert OnlyIssuerOrOwner();
        }
        _;
    }

    function issuer() external view returns (address) {
        return _metadata.originalOwner;
    }

    function metadata() external view returns (Metadata memory) {
        return _metadata;
    }
    /**
     * @notice Molecules are identified by the original token holder and the underlying token id
     * @return uint256 a token hash that's unique for [`originaOwner`,`ipnftid`]
     */

    function hash() external view returns (uint256) {
        return uint256(keccak256(abi.encodePacked(_metadata.originalOwner, _metadata.ipnftId)));
    }

    /**
     * @notice we deliberately allow the synthesis initializer to increase the supply of Molecules at will as long as the underlying asset has not been sold yet
     * @param receiver address
     * @param amount uint256
     */
    function issue(address receiver, uint256 amount) external onlyIssuerOrOwner {
        if (capped) revert TokenCapped();
        totalIssued += amount;
        _mint(receiver, amount);
    }

    /**
     * @notice mark this token as capped. After calling this, no new tokens can be `issue`d
     */
    function cap() external onlyIssuerOrOwner {
        capped = true;
        emit Capped(totalIssued);
    }

    /**
     * @notice contract metadata, compatible to ERC1155
     * @return string base64 encoded data url
     */
    function uri() external view returns (string memory) {
        string memory tokenId = Strings.toString(_metadata.ipnftId);

        string memory props = string.concat(
            '"properties": {',
            '"ipnft_id": ',
            tokenId,
            ',"agreement_content": "ipfs://',
            _metadata.agreementCid,
            '","original_owner": "',
            Strings.toHexString(_metadata.originalOwner),
            '","erc20_contract": "',
            Strings.toHexString(address(this)),
            '","supply": "',
            Strings.toString(totalIssued),
            '"}'
        );

        return string.concat(
            "data:application/json;base64,",
            Base64.encode(
                bytes(
                    string.concat(
                        '{"name": "Molecules of IPNFT #',
                        tokenId,
                        '","description": "Molecules, derived from IP-NFTs, are ERC-20 tokens governing IP pools.","decimals": 18,"external_url": "https://molecule.to","image": "",',
                        props,
                        "}"
                    )
                )
            )
        );
    }
}

File 25 of 38 : IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 26 of 38 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

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

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

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

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

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

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

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

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

pragma solidity ^0.8.0;

import "./IERC165.sol";

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

File 28 of 38 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

File 29 of 38 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

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

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

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

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

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

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

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

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

        return (signer, RecoverError.NoError);
    }

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

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

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

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Data with intended validator, created from a
     * `validator` and `data` according to the version 0 of EIP-191.
     *
     * See {recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x00", validator, data));
    }
}

File 30 of 38 : SignatureChecker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/SignatureChecker.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";
import "../../interfaces/IERC1271.sol";

/**
 * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
 * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
 * Argent and Gnosis Safe.
 *
 * _Available since v4.1._
 */
library SignatureChecker {
    /**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
        (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
        return
            (error == ECDSA.RecoverError.NoError && recovered == signer) ||
            isValidERC1271SignatureNow(signer, hash, signature);
    }

    /**
     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
     * against the signer smart contract using ERC1271.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidERC1271SignatureNow(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        (bool success, bytes memory result) = signer.staticcall(
            abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
        );
        return (success &&
            result.length >= 32 &&
            abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
    }
}

File 31 of 38 : ERC20BurnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)

pragma solidity ^0.8.0;

import "../ERC20Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";

/**
 * @dev Extension of {ERC20} that allows token holders to destroy both their own
 * tokens and those that they have an allowance for, in a way that can be
 * recognized off-chain (via event analysis).
 */
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
    function __ERC20Burnable_init() internal onlyInitializing {
    }

    function __ERC20Burnable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Destroys `amount` tokens from the caller.
     *
     * See {ERC20-_burn}.
     */
    function burn(uint256 amount) public virtual {
        _burn(_msgSender(), amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, deducting from the caller's
     * allowance.
     *
     * See {ERC20-_burn} and {ERC20-allowance}.
     *
     * Requirements:
     *
     * - the caller must have allowance for ``accounts``'s tokens of at least
     * `amount`.
     */
    function burnFrom(address account, uint256 amount) public virtual {
        _spendAllowance(account, _msgSender(), amount);
        _burn(account, amount);
    }

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

File 32 of 38 : OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _owner;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }

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

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

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

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

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

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

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

File 33 of 38 : Base64.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides a set of functions to operate with Base64 strings.
 *
 * _Available since v4.5._
 */
library Base64 {
    /**
     * @dev Base64 Encoding/Decoding Table
     */
    string internal constant _TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

    /**
     * @dev Converts a `bytes` to its Bytes64 `string` representation.
     */
    function encode(bytes memory data) internal pure returns (string memory) {
        /**
         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
         */
        if (data.length == 0) return "";

        // Loads the table into memory
        string memory table = _TABLE;

        // Encoding takes 3 bytes chunks of binary data from `bytes` data parameter
        // and split into 4 numbers of 6 bits.
        // The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up
        // - `data.length + 2`  -> Round up
        // - `/ 3`              -> Number of 3-bytes chunks
        // - `4 *`              -> 4 characters for each chunk
        string memory result = new string(4 * ((data.length + 2) / 3));

        /// @solidity memory-safe-assembly
        assembly {
            // Prepare the lookup table (skip the first "length" byte)
            let tablePtr := add(table, 1)

            // Prepare result pointer, jump over length
            let resultPtr := add(result, 32)

            // Run over the input, 3 bytes at a time
            for {
                let dataPtr := data
                let endPtr := add(data, mload(data))
            } lt(dataPtr, endPtr) {

            } {
                // Advance 3 bytes
                dataPtr := add(dataPtr, 3)
                let input := mload(dataPtr)

                // To write each character, shift the 3 bytes (18 bits) chunk
                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)
                // and apply logical AND with 0x3F which is the number of
                // the previous character in the ASCII table prior to the Base64 Table
                // The result is then added to the table to get the character to write,
                // and finally write it in the result pointer but with a left shift
                // of 256 (1 byte) - 8 (1 ASCII char) = 248 bits

                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance

                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
                resultPtr := add(resultPtr, 1) // Advance
            }

            // When data `bytes` is not exactly 3 bytes long
            // it is padded with `=` characters at the end
            switch mod(mload(data), 3)
            case 1 {
                mstore8(sub(resultPtr, 1), 0x3d)
                mstore8(sub(resultPtr, 2), 0x3d)
            }
            case 2 {
                mstore8(sub(resultPtr, 1), 0x3d)
            }
        }

        return result;
    }
}

File 34 of 38 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 35 of 38 : SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

File 36 of 38 : 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 37 of 38 : IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 *
 * _Available since v4.1._
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

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

pragma solidity ^0.8.0;

import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";

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

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

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

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

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

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

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

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

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

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

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

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

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

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

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

        return true;
    }

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

        _beforeTokenTransfer(from, to, amount);

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

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Settings
{
  "remappings": [
    "@moleculeprotocol/token-vesting/=lib/token-vesting-contract/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@prb/math/=lib/prb-math/src/",
    "ERC721B/=lib/ERC721B/contracts/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "erc721b/=lib/ERC721B/contracts/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts/contracts/",
    "safe-contracts/=lib/safe-contracts/contracts/",
    "safe-global/safe-contracts/=lib/safe-contracts/contracts/",
    "solady/=lib/token-vesting-contract/lib/solady/src/",
    "solmate/=lib/solmate/src/",
    "token-vesting-contract/=lib/token-vesting-contract/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "paris",
  "libraries": {}
}

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AlreadyClaimed","type":"error"},{"inputs":[],"name":"BadDecimals","type":"error"},{"inputs":[],"name":"BadPrice","type":"error"},{"inputs":[],"name":"BadSaleDuration","type":"error"},{"inputs":[{"internalType":"enum SaleState","name":"expected","type":"uint8"},{"internalType":"enum SaleState","name":"actual","type":"uint8"}],"name":"BadSaleState","type":"error"},{"inputs":[],"name":"BadSalesAmount","type":"error"},{"inputs":[],"name":"BidTooLow","type":"error"},{"inputs":[],"name":"IncompatibleVestingContract","type":"error"},{"inputs":[],"name":"InvalidDuration","type":"error"},{"inputs":[],"name":"SaleAlreadyActive","type":"error"},{"inputs":[],"name":"SaleClosedForBids","type":"error"},{"inputs":[],"name":"SaleNotConcluded","type":"error"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"SaleNotFund","type":"error"},{"inputs":[],"name":"UnmanageableVestingContract","type":"error"},{"inputs":[],"name":"UnsupportedInitializer","type":"error"},{"inputs":[],"name":"UnsupportedVestingContract","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"},{"indexed":true,"internalType":"address","name":"bidder","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Bid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"},{"indexed":true,"internalType":"address","name":"claimer","type":"address"},{"indexed":false,"internalType":"uint256","name":"claimed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"refunded","type":"uint256"}],"name":"Claimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"}],"name":"ClaimedAuctionTokens","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"}],"name":"ClaimedFundingGoal","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"},{"indexed":true,"internalType":"address","name":"claimer","type":"address"},{"indexed":false,"internalType":"uint256","name":"stakesClaimed","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"stakesRefunded","type":"uint256"}],"name":"ClaimedStakes","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"}],"name":"Failed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract TimelockedToken","name":"lockingContract","type":"address"},{"indexed":true,"internalType":"contract IERC20Metadata","name":"underlyingToken","type":"address"}],"name":"LockingContractCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalBids","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"surplus","type":"uint256"}],"name":"Settled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"},{"indexed":true,"internalType":"address","name":"bidder","type":"address"},{"indexed":false,"internalType":"uint256","name":"stakedAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"},{"indexed":true,"internalType":"address","name":"issuer","type":"address"},{"components":[{"internalType":"contract IERC20Metadata","name":"auctionToken","type":"address"},{"internalType":"contract IERC20Metadata","name":"biddingToken","type":"address"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"uint256","name":"fundingGoal","type":"uint256"},{"internalType":"uint256","name":"salesAmount","type":"uint256"},{"internalType":"uint64","name":"closingTime","type":"uint64"},{"internalType":"contract IPermissioner","name":"permissioner","type":"address"}],"indexed":false,"internalType":"struct Sale","name":"sale","type":"tuple"},{"components":[{"internalType":"contract IERC20Metadata","name":"stakedToken","type":"address"},{"internalType":"contract TokenVesting","name":"stakesVestingContract","type":"address"},{"internalType":"uint256","name":"wadFixedStakedPerBidPrice","type":"uint256"}],"indexed":false,"internalType":"struct StakingInfo","name":"staking","type":"tuple"},{"indexed":false,"internalType":"contract TimelockedToken","name":"lockingToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"lockingDuration","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"stakingDuration","type":"uint256"}],"name":"Started","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"},{"indexed":true,"internalType":"address","name":"issuer","type":"address"},{"components":[{"internalType":"contract IERC20Metadata","name":"auctionToken","type":"address"},{"internalType":"contract IERC20Metadata","name":"biddingToken","type":"address"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"uint256","name":"fundingGoal","type":"uint256"},{"internalType":"uint256","name":"salesAmount","type":"uint256"},{"internalType":"uint64","name":"closingTime","type":"uint64"},{"internalType":"contract IPermissioner","name":"permissioner","type":"address"}],"indexed":false,"internalType":"struct Sale","name":"sale","type":"tuple"},{"indexed":false,"internalType":"contract TimelockedToken","name":"lockingToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"lockingDuration","type":"uint256"}],"name":"Started","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"saleId","type":"uint256"},{"indexed":true,"internalType":"address","name":"issuer","type":"address"},{"components":[{"internalType":"contract IERC20Metadata","name":"auctionToken","type":"address"},{"internalType":"contract IERC20Metadata","name":"biddingToken","type":"address"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"uint256","name":"fundingGoal","type":"uint256"},{"internalType":"uint256","name":"salesAmount","type":"uint256"},{"internalType":"uint64","name":"closingTime","type":"uint64"},{"internalType":"contract IPermissioner","name":"permissioner","type":"address"}],"indexed":false,"internalType":"struct Sale","name":"sale","type":"tuple"}],"name":"Started","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"contract TokenVesting","name":"tokenVesting","type":"address"},{"indexed":false,"internalType":"bool","name":"trusted","type":"bool"}],"name":"UpdatedTrustedTokenVestings","type":"event"},{"inputs":[{"internalType":"uint256","name":"saleId","type":"uint256"},{"internalType":"bytes","name":"permission","type":"bytes"}],"name":"claim","outputs":[{"internalType":"uint256","name":"auctionTokens","type":"uint256"},{"internalType":"uint256","name":"refunds","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"saleId","type":"uint256"}],"name":"claimResults","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"saleId","type":"uint256"},{"internalType":"address","name":"contributor","type":"address"}],"name":"contribution","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IERC20Metadata","name":"underlyingToken","type":"address"}],"name":"createOrReturnTimelockContract","outputs":[{"internalType":"contract TimelockedToken","name":"lockedTokenContract","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"saleId","type":"uint256"},{"internalType":"address","name":"bidder","type":"address"}],"name":"getClaimableAmounts","outputs":[{"internalType":"uint256","name":"auctionTokens","type":"uint256"},{"internalType":"uint256","name":"refunds","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"saleId","type":"uint256"},{"internalType":"uint256","name":"refunds","type":"uint256"}],"name":"getClaimableStakes","outputs":[{"internalType":"uint256","name":"refundedStakes","type":"uint256"},{"internalType":"uint256","name":"vestedStakes","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"saleId","type":"uint256"}],"name":"getSaleInfo","outputs":[{"components":[{"internalType":"enum SaleState","name":"state","type":"uint8"},{"internalType":"uint256","name":"total","type":"uint256"},{"internalType":"uint256","name":"surplus","type":"uint256"},{"internalType":"bool","name":"claimed","type":"bool"}],"internalType":"struct SaleInfo","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"lockingContracts","outputs":[{"internalType":"contract TimelockedToken","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"saleId","type":"uint256"},{"internalType":"uint256","name":"biddingTokenAmount","type":"uint256"},{"internalType":"bytes","name":"permission","type":"bytes"}],"name":"placeBid","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"salesLockingDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"salesStaking","outputs":[{"internalType":"contract IERC20Metadata","name":"stakedToken","type":"address"},{"internalType":"contract TokenVesting","name":"stakesVestingContract","type":"address"},{"internalType":"uint256","name":"wadFixedStakedPerBidPrice","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"saleId","type":"uint256"}],"name":"settle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"saleId","type":"uint256"},{"internalType":"address","name":"bidder","type":"address"}],"name":"stakesOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Metadata","name":"auctionToken","type":"address"},{"internalType":"contract IERC20Metadata","name":"biddingToken","type":"address"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"uint256","name":"fundingGoal","type":"uint256"},{"internalType":"uint256","name":"salesAmount","type":"uint256"},{"internalType":"uint64","name":"closingTime","type":"uint64"},{"internalType":"contract IPermissioner","name":"permissioner","type":"address"}],"internalType":"struct Sale","name":"sale","type":"tuple"},{"internalType":"contract IERC20Metadata","name":"stakedToken","type":"address"},{"internalType":"contract TokenVesting","name":"stakesVestingContract","type":"address"},{"internalType":"uint256","name":"wadFixedStakedPerBidPrice","type":"uint256"},{"internalType":"uint256","name":"lockingDuration","type":"uint256"}],"name":"startSale","outputs":[{"internalType":"uint256","name":"saleId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Metadata","name":"auctionToken","type":"address"},{"internalType":"contract IERC20Metadata","name":"biddingToken","type":"address"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"uint256","name":"fundingGoal","type":"uint256"},{"internalType":"uint256","name":"salesAmount","type":"uint256"},{"internalType":"uint64","name":"closingTime","type":"uint64"},{"internalType":"contract IPermissioner","name":"permissioner","type":"address"}],"internalType":"struct Sale","name":"","type":"tuple"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"startSale","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"contract IERC20Metadata","name":"auctionToken","type":"address"},{"internalType":"contract IERC20Metadata","name":"biddingToken","type":"address"},{"internalType":"address","name":"beneficiary","type":"address"},{"internalType":"uint256","name":"fundingGoal","type":"uint256"},{"internalType":"uint256","name":"salesAmount","type":"uint256"},{"internalType":"uint64","name":"closingTime","type":"uint64"},{"internalType":"contract IPermissioner","name":"permissioner","type":"address"}],"internalType":"struct Sale","name":"","type":"tuple"}],"name":"startSale","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract TokenVesting","name":"stakesVestingContract","type":"address"}],"name":"trustVestingContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"trustedVestingContracts","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract TokenVesting","name":"stakesVestingContract","type":"address"}],"name":"untrustVestingContract","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60a06040526040516200001290620000b2565b604051809103906000f0801580156200002f573d6000803e3d6000fd5b506001600160a01b03166080523480156200004957600080fd5b5060016000556200005a3362000060565b620000c0565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6110a78062002ce683390190565b608051612c0a620000dc60003960006116a00152612c0a6000f3fe608060405234801561001057600080fd5b50600436106101425760003560e01c80638df82800116100b8578063b503a3c71161007c578063b503a3c71461034b578063b8ddb9101461035e578063cc80e7771461036c578063ccee0b9b1461037f578063dfa3a43214610392578063f2fde38b146103c857600080fd5b80638df82800146102df5780638fa26185146102f257806392360bb114610305578063a2da203714610325578063a6bae3cf1461033857600080fd5b80634074d3f81161010a5780634074d3f8146101fe57806347a5098d1461026057806364b3b84414610273578063715018a614610293578063799320d11461029b5780638da5cb5b146102ce57600080fd5b8063044d587f1461014757806323772d921461016d578063320780c81461018257806338561e0c146101c357806338926b6d146101d6575b600080fd5b61015a61015536600461240b565b6103db565b6040519081526020015b60405180910390f35b61018061017b366004612469565b610709565b005b6101ab610190366004612469565b6005602052600090815260409020546001600160a01b031681565b6040516001600160a01b039091168152602001610164565b6101806101d1366004612469565b610767565b6101e96101e436600461249c565b6108ba565b60408051928352602083019190915201610164565b61023a61020c366004612556565b6007602052600090815260409020805460018201546002909201546001600160a01b03918216929091169083565b604080516001600160a01b03948516815293909216602084015290820152606001610164565b6101e961026e36600461256f565b610a26565b610286610281366004612556565b610ac6565b60405161016491906125d7565b610180610b59565b6102be6102a9366004612469565b60096020526000908152604090205460ff1681565b6040519015158152602001610164565b6006546001600160a01b03166101ab565b6101806102ed366004612556565b610b6d565b610180610300366004612610565b610cca565b61015a610313366004612556565b60046020526000908152604090205481565b61015a61033336600461256f565b610e1d565b61015a61034636600461268f565b610e47565b6101ab610359366004612469565b610e62565b61015a6103463660046126bb565b6101e961037a3660046126d7565b610ec1565b61018061038d366004612556565b610f14565b61015a6103a036600461256f565b60009182526003602090815260408084206001600160a01b0393909316845291905290205490565b6101806103d6366004612469565b61106d565b6000846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561041b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061043f91906126f9565b60ff1660121461046257604051630456c65960e51b815260040160405180910390fd5b6001600160a01b03841660009081526009602052604090205460ff1661049b5760405163ee70b1c360e01b815260040160405180910390fd5b846001600160a01b0316846001600160a01b031663e1758bd86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104e3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610507919061271c565b6001600160a01b03161461052e57604051631a9f5c0560e11b815260040160405180910390fd5b8260000361054f5760405163fd1ee34960e01b815260040160405180910390fd5b61055f6040870160208801612469565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561059c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105c091906126f9565b60ff16601214610665576105da6040870160208801612469565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610617573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061063b91906126f9565b61064690600a612833565b61065884670de0b6b3a7640000612842565b6106629190612859565b92505b856040516020016106769190612890565b60408051808303601f1901815282825280516020918201206060840183526001600160a01b0389811685528881168386019081528585018981526000848152600790955294909320945185546001600160a01b03199081169183169190911786559251600186018054909416911617909155905160029092019190915590506106ff86836110e3565b5095945050505050565b610711611168565b6001600160a01b0381166000818152600960209081526040808320805460ff19169055519182527f50fb816a31ab5c5d6d46d597369943c0b750211947ceb7eea0a5addace02044091015b60405180910390a250565b61076f611168565b806001600160a01b03166391d14854826001600160a01b0316633c8241a16040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107e0919061292d565b6040516001600160e01b031960e084901b1681526004810191909152306024820152604401602060405180830381865afa158015610822573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108469190612946565b6108635760405163e4e6118f60e01b815260040160405180910390fd5b6001600160a01b038116600081815260096020908152604091829020805460ff1916600190811790915591519182527f50fb816a31ab5c5d6d46d597369943c0b750211947ceb7eea0a5addace020440910161075c565b6000806108c56111c2565b60008481526002602052604090205460ff1660038160038111156108eb576108eb61259f565b03610903576108f98561121b565b9250925050610a15565b60028160038111156109175761091761259f565b146109435760028160405163f4345bc960e01b815260040161093a929190612968565b60405180910390fd5b60008581526001602052604090206005810154600160401b90046001600160a01b0316156109de5760058101548154604051632fc848ed60e01b81526001600160a01b03600160401b909304831692632fc848ed926109ab9291169033908a906004016129d3565b600060405180830381600087803b1580156109c557600080fd5b505af11580156109d9573d6000803e3d6000fd5b505050505b6109e88633610a26565b60008881526003602090815260408083203384529091528120559094509250610a128685856112b2565b50505b610a1f6001600055565b9250929050565b60008281526002602052604081206001810154829190829015610a7957600182015460008781526003602090815260408083206001600160a01b038a168452909152902054610a749161149c565b610a7c565b60005b600087815260016020526040902060040154909150610a9c9082906114b1565b93508160020154600014610abd576002820154610aba9082906114b1565b92505b50509250929050565b604080516080810182526000808252602082018190529181018290526060810191909152600082815260026020526040908190208151608081019092528054829060ff166003811115610b1b57610b1b61259f565b6003811115610b2c57610b2c61259f565b8152600182015460208201526002820154604082015260039091015460ff16151560609091015292915050565b610b61611168565b610b6b60006114c6565b565b610b756111c2565b6000818152600160209081526040808320600290925290912060058201546001600160401b0316421015610bbc57604051630cea94ad60e31b815260040160405180910390fd5b6001815460ff166003811115610bd457610bd461259f565b14610bfd57805460405163f4345bc960e01b815261093a9160019160ff90911690600401612968565b816003015481600101541015610c4a57805460ff1916600317815560405183907fc77ea6414b21b2cf2170f259ee35ec16a7cbf16eeace77cc3ae8c6d52556881a90600090a25050610cbd565b805460ff1916600217815560038201546001820154610c6991906129ff565b60028201819055600182015460408051918252602082019290925284917f321f57f44af402708b8b3bad0bd10012cd568d8696946e26edeb86178bb7c27e910160405180910390a2610cba83611518565b50505b610cc76001600055565b50565b82600003610ceb57604051635069375b60e11b815260040160405180910390fd5b60008481526001602052604081206003810154909103610d2157604051637d600f6d60e11b81526004810186905260240161093a565b60058101546001600160401b0316421180610d5f5750600160008681526002602052604090205460ff166003811115610d5c57610d5c61259f565b14155b15610d7d57604051630bffe79960e01b815260040160405180910390fd5b6005810154600160401b90046001600160a01b031615610e0c5760058101548154604051632fc848ed60e01b81526001600160a01b03600160401b909304831692632fc848ed92610dd992911690339088908890600401612a12565b600060405180830381600087803b158015610df357600080fd5b505af1158015610e07573d6000803e3d6000fd5b505050505b610e1685856115db565b5050505050565b60008281526008602090815260408083206001600160a01b03851684529091529020545b92915050565b600060405163dc05711160e01b815260040160405180910390fd5b6001600160a01b038082166000908152600560205260409020541680610ebc57610e8b82611699565b6001600160a01b03838116600090815260056020526040902080546001600160a01b03191691831691909117905590505b919050565b60008281526007602052604081206002810154829190610ee29085906114b1565b6000868152600860209081526040808320338452909152902054909350610f0a9084906129ff565b9150509250929050565b6000818152600260205260409020600381015460ff1615610f4857604051630c8d9eab60e31b815260040160405180910390fd5b60038101805460ff191660019081179091556000838152602091909152604090206002825460ff166003811115610f8157610f8161259f565b03610fdd5760405183907f0cf39eedb483dd8d759788bf84c9a69e9dc611bc2da361ea04b62245015867f290600090a2600281015460038201546001830154610fd8926001600160a01b0391821692911690611760565b505050565b6003825460ff166003811115610ff557610ff561259f565b036110495760405183907f17da104c9f3b96f1a4d40b8f500c6ad4497b9fc0910a7fa050e5188628fb05a190600090a2600281015460048201548254610fd8926001600160a01b0391821692911690611760565b815460405163f4345bc960e01b815261093a9160029160ff90911690600401612968565b611075611168565b6001600160a01b0381166110da5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161093a565b610cc7816114c6565b6000826040516020016110f69190612890565b6040516020818303038152906040528051906020012060001c90506301e2850082111561113657604051637616640160e01b815260040160405180910390fd5b6111466103596020850185612469565b506000818152600460205260409020829055611161836117c3565b9392505050565b6006546001600160a01b03163314610b6b5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161093a565b6002600054036112145760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015260640161093a565b6002600055565b60008181526008602090815260408083203384529091528120805490829055819061124584611ab3565b604080516000815260208101859052929550909350339186917f80d231c3431de24ab93b46f175dcb0c3e4d22a5d14e0be106fd53ea1b60bcc0f910160405180910390a36000848152600760205260409020546112ac906001600160a01b03163383611760565b50915091565b600083815260046020908152604080832054600790925282209091806112d88786610ec1565b60008981526008602090815260408083203384529091528120559092509050611302878787611b42565b811561131e57825461131e906001600160a01b03163384611760565b6040805182815260208101849052339189917f80d231c3431de24ab93b46f175dcb0c3e4d22a5d14e0be106fd53ea1b60bcc0f910160405180910390a38060000361136c5750505050505050565b600062093a80851061137e5784611383565b62093a805b6000898152600160205260409020600501549091506113ac9082906001600160401b0316612a5e565b4211156113ce5783546113c9906001600160a01b03163384611760565b611492565b600184015484546113ec916001600160a01b03918216911684611760565b60018481015460008a815260209290925260408083206005015490516317e289e960e01b81523360048201526001600160401b0390911660248201526044810184905260648101849052603c608482015260a481019290925260c482018490526001600160a01b0316906317e289e99060e401600060405180830381600087803b15801561147957600080fd5b505af115801561148d573d6000803e3d6000fd5b505050505b5050505050505050565b600061116183670de0b6b3a764000084611bc3565b60006111618383670de0b6b3a7640000611bc3565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600081815260016020908152604080832080546001600160a01b039081168086526005909452828520549251636eb1769f60e11b815230600482015292166024830181905290939092909163dd62ed3e90604401602060405180830381865afa158015611589573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115ad919061292d565b90506115d5828460040154836115c39190612a5e565b85546001600160a01b03169190611be2565b50505050565b600082815260076020526040812060028101549091906115fc9084906114b1565b600085815260086020908152604080832033845290915281208054929350839290919061162a908490612a5e565b90915550508154611646906001600160a01b0316333084611c71565b6116508484611ca9565b6002820154604080518381526020810192909252339186917f17700ceb1658b18206f427c1578048e87504106b14ec69e9b4586d9a95174a32910160405180910390a350505050565b60006116c47f0000000000000000000000000000000000000000000000000000000000000000611d61565b60405163189acdbd60e31b81526001600160a01b0384811660048301529192509082169063c4d66de890602401600060405180830381600087803b15801561170b57600080fd5b505af115801561171f573d6000803e3d6000fd5b50506040516001600160a01b038086169350841691507f0310432d7f6807c3b1be0e54000e643522a00a5db4a8ab89f15a30415b5eabcb90600090a3919050565b6040516001600160a01b038316602482015260448101829052610fd890849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152611df6565b6000426117d660c0840160a08501612a71565b6001600160401b0316108061180e57506117f34262ed4e00612a5e565b61180360c0840160a08501612a71565b6001600160401b0316115b1561182c5760405163eb468ebd60e01b815260040160405180910390fd5b6118396020830183612469565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611876573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061189a91906126f9565b60ff166012146118bd57604051630456c65960e51b815260040160405180910390fd5b60026118cf6040840160208501612469565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561190c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061193091906126f9565b61193a9190612a8e565b61194590600a612833565b8260600135108061196157506706f05b59d3b200008260800135105b1561197f57604051633e8bac2560e21b815260040160405180910390fd5b816040516020016119909190612890565b60408051601f198184030181529181528151602092830120600081815260019093529120549091506001600160a01b0316156119df5760405163e794df0960e01b815260040160405180910390fd5b600081815260016020526040902082906119f98282612ad4565b5050604080516080810190915280600181526000602080830182905260408084018390526060909301829052848252600290522081518154829060ff19166001836003811115611a4b57611a4b61259f565b02179055506020828101516001830155604083015160028301556060909201516003909101805460ff1916911515919091179055611aaa9033903090608086013590611a9990870187612469565b6001600160a01b0316929190611c71565b610ebc81611ecb565b60008181526003602090815260408083203380855290835281842080549085905582518581529384018190528493909286917fd9cb1e2714d65a111c0f20f060176ad657496bd47a3de04ec7c3d4ca232112ac910160405180910390a360008481526001602081905260409091200154611b37906001600160a01b03163383611760565b600094909350915050565b81600003611b4f57505050565b6040805183815260208101839052339185917fd9cb1e2714d65a111c0f20f060176ad657496bd47a3de04ec7c3d4ca232112ac910160405180910390a38015611bb95760008381526001602081905260409091200154611bb9906001600160a01b03163383611760565b610fd88383611ff1565b828202811515841585830485141716611bdb57600080fd5b0492915050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052611c33848261213b565b6115d5576040516001600160a01b038416602482015260006044820152611c6790859063095ea7b360e01b9060640161178c565b6115d58482611df6565b6040516001600160a01b03808516602483015283166044820152606481018290526115d59085906323b872dd60e01b9060840161178c565b60008281526002602052604081206001018054839290611cca908490612a5e565b9091555050600082815260036020908152604080832033845290915281208054839290611cf8908490612a5e565b909155505060008281526001602081905260409091200154611d25906001600160a01b0316333084611c71565b604051818152339083907fdcd726e11f8b5e160f00290f0fe3a1abb547474e53a8e7a8f49a85e7b1ca3199906020015b60405180910390a35050565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008260601b60e81c176000526e5af43d82803e903d91602b57fd5bf38260781b17602052603760096000f090506001600160a01b038116610ebc5760405162461bcd60e51b8152602060048201526016602482015275115490cc4c4d8dce8818dc99585d194819985a5b195960521b604482015260640161093a565b6000611e4b826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166121e29092919063ffffffff16565b9050805160001480611e6c575080806020019051810190611e6c9190612946565b610fd85760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161093a565b60008181526004602052604081205462093a8011611ef757600082815260046020526040902054611efc565b62093a805b60008381526001602081815260408084206007835281852081546001600160a01b039081168088526005808752858920548c8a52600480895299879020548751938452868a0154851698840198909852600280870154851684890152600387015460608501529986015460808401529401546001600160401b03811660a083015290941c811660c08501528154811660e08501529481015485166101008401529490940154610120820152929091166101408301526101608201526101808101829052909150339083907fae74ea7bd2d650ccd85bd50a9ab8edbab2e1963361fed65904e07cd746006f7c906101a001611d55565b600082815260046020908152604080832054600180845282852080546001600160a01b03908116875260058087529487205496899052919094529190920154919216906120489083906001600160401b0316612a5e565b42111561207757600084815260016020526040902054612072906001600160a01b03163385611760565b6115d5565b6000848152600160205260409020600501546001600160a01b03821690635b1fc7f290339086906120bb906120b69088906001600160401b0316612a5e565b6121f9565b6040516001600160e01b031960e086901b1681526001600160a01b03909316600484015260248301919091526001600160401b031660448201526064016020604051808303816000875af1158015612117573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e16919061292d565b6000806000846001600160a01b0316846040516121589190612ba5565b6000604051808303816000865af19150503d8060008114612195576040519150601f19603f3d011682016040523d82523d6000602084013e61219a565b606091505b50915091508180156121c45750805115806121c45750808060200190518101906121c49190612946565b80156121d957506001600160a01b0385163b15155b95945050505050565b60606121f18484600085612265565b949350505050565b60006001600160401b038211156122615760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203660448201526534206269747360d01b606482015260840161093a565b5090565b6060824710156122c65760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161093a565b600080866001600160a01b031685876040516122e29190612ba5565b60006040518083038185875af1925050503d806000811461231f576040519150601f19603f3d011682016040523d82523d6000602084013e612324565b606091505b509150915061233587838387612340565b979650505050505050565b606083156123af5782516000036123a8576001600160a01b0385163b6123a85760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161093a565b50816121f1565b6121f183838151156123c45781518083602001fd5b8060405162461bcd60e51b815260040161093a9190612bc1565b600060e082840312156123f057600080fd5b50919050565b6001600160a01b0381168114610cc757600080fd5b6000806000806000610160868803121561242457600080fd5b61242e87876123de565b945060e086013561243e816123f6565b935061010086013561244f816123f6565b949793965093946101208101359450610140013592915050565b60006020828403121561247b57600080fd5b8135611161816123f6565b634e487b7160e01b600052604160045260246000fd5b600080604083850312156124af57600080fd5b8235915060208301356001600160401b03808211156124cd57600080fd5b818501915085601f8301126124e157600080fd5b8135818111156124f3576124f3612486565b604051601f8201601f19908116603f0116810190838211818310171561251b5761251b612486565b8160405282815288602084870101111561253457600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b60006020828403121561256857600080fd5b5035919050565b6000806040838503121561258257600080fd5b823591506020830135612594816123f6565b809150509250929050565b634e487b7160e01b600052602160045260246000fd5b600481106125d357634e487b7160e01b600052602160045260246000fd5b9052565b60006080820190506125ea8284516125b5565b602083015160208301526040830151604083015260608301511515606083015292915050565b6000806000806060858703121561262657600080fd5b843593506020850135925060408501356001600160401b038082111561264b57600080fd5b818701915087601f83011261265f57600080fd5b81358181111561266e57600080fd5b88602082850101111561268057600080fd5b95989497505060200194505050565b60008061010083850312156126a357600080fd5b6126ad84846123de565b9460e0939093013593505050565b600060e082840312156126cd57600080fd5b61116183836123de565b600080604083850312156126ea57600080fd5b50508035926020909101359150565b60006020828403121561270b57600080fd5b815160ff8116811461116157600080fd5b60006020828403121561272e57600080fd5b8151611161816123f6565b634e487b7160e01b600052601160045260246000fd5b600181815b8085111561278a57816000190482111561277057612770612739565b8085161561277d57918102915b93841c9390800290612754565b509250929050565b6000826127a157506001610e41565b816127ae57506000610e41565b81600181146127c457600281146127ce576127ea565b6001915050610e41565b60ff8411156127df576127df612739565b50506001821b610e41565b5060208310610133831016604e8410600b841016171561280d575081810a610e41565b612817838361274f565b806000190482111561282b5761282b612739565b029392505050565b600061116160ff841683612792565b8082028115828204841417610e4157610e41612739565b60008261287657634e487b7160e01b600052601260045260246000fd5b500490565b6001600160401b0381168114610cc757600080fd5b60e08101823561289f816123f6565b6001600160a01b0390811683526020840135906128bb826123f6565b90811660208401526040840135906128d2826123f6565b8082166040850152606085013560608501526080850135608085015260a085013591506128fe8261287b565b6001600160401b03821660a085015260c0850135915061291d826123f6565b80821660c0850152505092915050565b60006020828403121561293f57600080fd5b5051919050565b60006020828403121561295857600080fd5b8151801515811461116157600080fd5b6040810161297682856125b5565b61116160208301846125b5565b60005b8381101561299e578181015183820152602001612986565b50506000910152565b600081518084526129bf816020860160208601612983565b601f01601f19169290920160200192915050565b6001600160a01b038481168252831660208201526060604082018190526000906121d9908301846129a7565b81810381811115610e4157610e41612739565b6001600160a01b0385811682528416602082015260606040820181905281018290526000828460808401376000608084840101526080601f19601f850116830101905095945050505050565b80820180821115610e4157610e41612739565b600060208284031215612a8357600080fd5b81356111618161287b565b60ff8281168282160390811115610e4157610e41612739565b80546001600160a01b0319166001600160a01b0392909216919091179055565b60008135610e41816123f6565b8135612adf816123f6565b612ae98183612aa7565b506020820135612af8816123f6565b612b058160018401612aa7565b506040820135612b14816123f6565b612b218160028401612aa7565b5060608201356003820155608082013560048201556005810160a0830135612b488161287b565b6001600160401b0381166001600160401b031983541617825550610fd8612b7160c08501612ac7565b82805468010000000000000000600160e01b03191660409290921b68010000000000000000600160e01b0316919091179055565b60008251612bb7818460208701612983565b9190910192915050565b60208152600061116160208301846129a756fea2646970667358221220a5a1ac180e7b7db8c99018ab323ec3d95f94273de78d23fe760de101558b11a164736f6c63430008120033608060405234801561001057600080fd5b50611087806100206000396000f3fe608060405234801561001057600080fd5b50600436106100f55760003560e01c806367d42a8b11610097578063a9059cbb11610066578063a9059cbb14610118578063c4d66de814610217578063d1e16bfa1461022a578063dd62ed3e1461029c57600080fd5b806367d42a8b146101be5780636d0358d7146101d357806370a08231146101e657806395d89b411461020f57600080fd5b806323b872dd116100d357806323b872dd146101525780632495a59914610160578063313ce567146101915780635b1fc7f2146101ab57600080fd5b806306fdde03146100fa578063095ea7b31461011857806318160ddd1461013b575b600080fd5b6101026102af565b60405161010f9190610c8a565b60405180910390f35b61012b610126366004610cd5565b610350565b604051901515815260200161010f565b61014460015481565b60405190815260200161010f565b61012b610126366004610d01565b600054610179906201000090046001600160a01b031681565b6040516001600160a01b03909116815260200161010f565b61019961036b565b60405160ff909116815260200161010f565b6101446101b9366004610d42565b6103e8565b6101d16101cc366004610d91565b6105f9565b005b6101d16101e1366004610daa565b610757565b6101446101f4366004610e1f565b6001600160a01b031660009081526002602052604090205490565b61010261079a565b6101d1610225366004610e1f565b610827565b61026e610238366004610d91565b6003602052600090815260409020805460019091015467ffffffffffffffff821691600160401b90046001600160a01b03169083565b6040805167ffffffffffffffff90941684526001600160a01b0390921660208401529082015260600161010f565b6101446102aa366004610e3c565b610957565b6060600060029054906101000a90046001600160a01b03166001600160a01b03166306fdde036040518163ffffffff1660e01b8152600401600060405180830381865afa158015610304573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261032c9190810190610e8b565b60405160200161033c9190610f2d565b604051602081830303815290604052905090565b6000604051630280e1e560e61b815260040160405180910390fd5b60008060029054906101000a90046001600160a01b03166001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156103bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103e39190610f5c565b905090565b60006103f642610384610f95565b8267ffffffffffffffff1610806104235750610416426309660180610f95565b8267ffffffffffffffff16115b1561044157604051638e7c849d60e01b815260040160405180910390fd5b6040516bffffffffffffffffffffffff1933606090811b8216602084015286901b166034820152604881018490526001600160c01b031960c084901b16606882015260700160408051601f19818403018152918152815160209283012060008181526003909352912054909150600160401b90046001600160a01b0316156104dc57604051631bd34e3960e31b815260040160405180910390fd5b6040805160608101825267ffffffffffffffff80851682526001600160a01b0380881660208085018281528587018a8152600089815260038452888120975188549351909616600160401b026001600160e01b03199093169590961694909417178555915160019094019390935591815260029091529081208054859290610565908490610f95565b92505081905550826001600082825461057e9190610f95565b90915550506040805184815267ffffffffffffffff8416602082015233916001600160a01b0387169184917f39520e61968f97cb52bbc0408e3247e22d31bfe93e180b5020561b2f2d0c94d5910160405180910390a46000546105f2906201000090046001600160a01b0316333086610960565b9392505050565b6000818152600360209081526040918290208251606081018452815467ffffffffffffffff8116808352600160401b9091046001600160a01b0316938201939093526001909101549281019290925242101561066857604051636100d92960e11b815260040160405180910390fd5b80604001516001600082825461067e9190610fa8565b90915550506040808201516020808401516001600160a01b0316600090815260029091529182208054919290916106b6908490610fa8565b9250508190555080602001516001600160a01b0316827f7716ba17b163f2fc2bcac016d834f00a9068b04c55517a6b72372ea8d3073ad4836040015160405161070191815260200190565b60405180910390a3600082815260036020908152604080832080546001600160e01b03191681556001018390559083015190830151915461075392620100009091046001600160a01b031691906109d1565b5050565b60005b818110156107955761078383838381811061077757610777610fbb565b905060200201356105f9565b8061078d81610fd1565b91505061075a565b505050565b6060600060029054906101000a90046001600160a01b03166001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa1580156107ef573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526108179190810190610e8b565b60405160200161033c9190610fea565b600054610100900460ff16158080156108475750600054600160ff909116105b806108615750303b158015610861575060005460ff166001145b6108c95760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084015b60405180910390fd5b6000805460ff1916600117905580156108ec576000805461ff0019166101001790555b6000805462010000600160b01b031916620100006001600160a01b038516021790558015610753576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15050565b60005b92915050565b6040516001600160a01b03808516602483015283166044820152606481018290526109cb9085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152610a01565b50505050565b6040516001600160a01b03831660248201526044810182905261079590849063a9059cbb60e01b90606401610994565b6000610a56826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610ad69092919063ffffffff16565b9050805160001480610a77575080806020019051810190610a779190611013565b6107955760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016108c0565b6060610ae58484600085610aed565b949350505050565b606082471015610b4e5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016108c0565b600080866001600160a01b03168587604051610b6a9190611035565b60006040518083038185875af1925050503d8060008114610ba7576040519150601f19603f3d011682016040523d82523d6000602084013e610bac565b606091505b5091509150610bbd87838387610bc8565b979650505050505050565b60608315610c37578251600003610c30576001600160a01b0385163b610c305760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016108c0565b5081610ae5565b610ae58383815115610c4c5781518083602001fd5b8060405162461bcd60e51b81526004016108c09190610c8a565b60005b83811015610c81578181015183820152602001610c69565b50506000910152565b6020815260008251806020840152610ca9816040850160208701610c66565b601f01601f19169190910160400192915050565b6001600160a01b0381168114610cd257600080fd5b50565b60008060408385031215610ce857600080fd5b8235610cf381610cbd565b946020939093013593505050565b600080600060608486031215610d1657600080fd5b8335610d2181610cbd565b92506020840135610d3181610cbd565b929592945050506040919091013590565b600080600060608486031215610d5757600080fd5b8335610d6281610cbd565b925060208401359150604084013567ffffffffffffffff81168114610d8657600080fd5b809150509250925092565b600060208284031215610da357600080fd5b5035919050565b60008060208385031215610dbd57600080fd5b823567ffffffffffffffff80821115610dd557600080fd5b818501915085601f830112610de957600080fd5b813581811115610df857600080fd5b8660208260051b8501011115610e0d57600080fd5b60209290920196919550909350505050565b600060208284031215610e3157600080fd5b81356105f281610cbd565b60008060408385031215610e4f57600080fd5b8235610e5a81610cbd565b91506020830135610e6a81610cbd565b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b600060208284031215610e9d57600080fd5b815167ffffffffffffffff80821115610eb557600080fd5b818401915084601f830112610ec957600080fd5b815181811115610edb57610edb610e75565b604051601f8201601f19908116603f01168101908382118183101715610f0357610f03610e75565b81604052828152876020848701011115610f1c57600080fd5b610bbd836020830160208801610c66565b6602637b1b5b2b2160cd1b815260008251610f4f816007850160208701610c66565b9190910160070192915050565b600060208284031215610f6e57600080fd5b815160ff811681146105f257600080fd5b634e487b7160e01b600052601160045260246000fd5b8082018082111561095a5761095a610f7f565b8181038181111561095a5761095a610f7f565b634e487b7160e01b600052603260045260246000fd5b600060018201610fe357610fe3610f7f565b5060010190565b601b60fa1b815260008251611006816001850160208701610c66565b9190910160010192915050565b60006020828403121561102557600080fd5b815180151581146105f257600080fd5b60008251611047818460208701610c66565b919091019291505056fea2646970667358221220941bb66ca25a588e419a63c6d54d54a306460dda9c7b1aa33f7ca8babdcf930564736f6c63430008120033

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101425760003560e01c80638df82800116100b8578063b503a3c71161007c578063b503a3c71461034b578063b8ddb9101461035e578063cc80e7771461036c578063ccee0b9b1461037f578063dfa3a43214610392578063f2fde38b146103c857600080fd5b80638df82800146102df5780638fa26185146102f257806392360bb114610305578063a2da203714610325578063a6bae3cf1461033857600080fd5b80634074d3f81161010a5780634074d3f8146101fe57806347a5098d1461026057806364b3b84414610273578063715018a614610293578063799320d11461029b5780638da5cb5b146102ce57600080fd5b8063044d587f1461014757806323772d921461016d578063320780c81461018257806338561e0c146101c357806338926b6d146101d6575b600080fd5b61015a61015536600461240b565b6103db565b6040519081526020015b60405180910390f35b61018061017b366004612469565b610709565b005b6101ab610190366004612469565b6005602052600090815260409020546001600160a01b031681565b6040516001600160a01b039091168152602001610164565b6101806101d1366004612469565b610767565b6101e96101e436600461249c565b6108ba565b60408051928352602083019190915201610164565b61023a61020c366004612556565b6007602052600090815260409020805460018201546002909201546001600160a01b03918216929091169083565b604080516001600160a01b03948516815293909216602084015290820152606001610164565b6101e961026e36600461256f565b610a26565b610286610281366004612556565b610ac6565b60405161016491906125d7565b610180610b59565b6102be6102a9366004612469565b60096020526000908152604090205460ff1681565b6040519015158152602001610164565b6006546001600160a01b03166101ab565b6101806102ed366004612556565b610b6d565b610180610300366004612610565b610cca565b61015a610313366004612556565b60046020526000908152604090205481565b61015a61033336600461256f565b610e1d565b61015a61034636600461268f565b610e47565b6101ab610359366004612469565b610e62565b61015a6103463660046126bb565b6101e961037a3660046126d7565b610ec1565b61018061038d366004612556565b610f14565b61015a6103a036600461256f565b60009182526003602090815260408084206001600160a01b0393909316845291905290205490565b6101806103d6366004612469565b61106d565b6000846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561041b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061043f91906126f9565b60ff1660121461046257604051630456c65960e51b815260040160405180910390fd5b6001600160a01b03841660009081526009602052604090205460ff1661049b5760405163ee70b1c360e01b815260040160405180910390fd5b846001600160a01b0316846001600160a01b031663e1758bd86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156104e3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610507919061271c565b6001600160a01b03161461052e57604051631a9f5c0560e11b815260040160405180910390fd5b8260000361054f5760405163fd1ee34960e01b815260040160405180910390fd5b61055f6040870160208801612469565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561059c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105c091906126f9565b60ff16601214610665576105da6040870160208801612469565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610617573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061063b91906126f9565b61064690600a612833565b61065884670de0b6b3a7640000612842565b6106629190612859565b92505b856040516020016106769190612890565b60408051808303601f1901815282825280516020918201206060840183526001600160a01b0389811685528881168386019081528585018981526000848152600790955294909320945185546001600160a01b03199081169183169190911786559251600186018054909416911617909155905160029092019190915590506106ff86836110e3565b5095945050505050565b610711611168565b6001600160a01b0381166000818152600960209081526040808320805460ff19169055519182527f50fb816a31ab5c5d6d46d597369943c0b750211947ceb7eea0a5addace02044091015b60405180910390a250565b61076f611168565b806001600160a01b03166391d14854826001600160a01b0316633c8241a16040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107e0919061292d565b6040516001600160e01b031960e084901b1681526004810191909152306024820152604401602060405180830381865afa158015610822573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108469190612946565b6108635760405163e4e6118f60e01b815260040160405180910390fd5b6001600160a01b038116600081815260096020908152604091829020805460ff1916600190811790915591519182527f50fb816a31ab5c5d6d46d597369943c0b750211947ceb7eea0a5addace020440910161075c565b6000806108c56111c2565b60008481526002602052604090205460ff1660038160038111156108eb576108eb61259f565b03610903576108f98561121b565b9250925050610a15565b60028160038111156109175761091761259f565b146109435760028160405163f4345bc960e01b815260040161093a929190612968565b60405180910390fd5b60008581526001602052604090206005810154600160401b90046001600160a01b0316156109de5760058101548154604051632fc848ed60e01b81526001600160a01b03600160401b909304831692632fc848ed926109ab9291169033908a906004016129d3565b600060405180830381600087803b1580156109c557600080fd5b505af11580156109d9573d6000803e3d6000fd5b505050505b6109e88633610a26565b60008881526003602090815260408083203384529091528120559094509250610a128685856112b2565b50505b610a1f6001600055565b9250929050565b60008281526002602052604081206001810154829190829015610a7957600182015460008781526003602090815260408083206001600160a01b038a168452909152902054610a749161149c565b610a7c565b60005b600087815260016020526040902060040154909150610a9c9082906114b1565b93508160020154600014610abd576002820154610aba9082906114b1565b92505b50509250929050565b604080516080810182526000808252602082018190529181018290526060810191909152600082815260026020526040908190208151608081019092528054829060ff166003811115610b1b57610b1b61259f565b6003811115610b2c57610b2c61259f565b8152600182015460208201526002820154604082015260039091015460ff16151560609091015292915050565b610b61611168565b610b6b60006114c6565b565b610b756111c2565b6000818152600160209081526040808320600290925290912060058201546001600160401b0316421015610bbc57604051630cea94ad60e31b815260040160405180910390fd5b6001815460ff166003811115610bd457610bd461259f565b14610bfd57805460405163f4345bc960e01b815261093a9160019160ff90911690600401612968565b816003015481600101541015610c4a57805460ff1916600317815560405183907fc77ea6414b21b2cf2170f259ee35ec16a7cbf16eeace77cc3ae8c6d52556881a90600090a25050610cbd565b805460ff1916600217815560038201546001820154610c6991906129ff565b60028201819055600182015460408051918252602082019290925284917f321f57f44af402708b8b3bad0bd10012cd568d8696946e26edeb86178bb7c27e910160405180910390a2610cba83611518565b50505b610cc76001600055565b50565b82600003610ceb57604051635069375b60e11b815260040160405180910390fd5b60008481526001602052604081206003810154909103610d2157604051637d600f6d60e11b81526004810186905260240161093a565b60058101546001600160401b0316421180610d5f5750600160008681526002602052604090205460ff166003811115610d5c57610d5c61259f565b14155b15610d7d57604051630bffe79960e01b815260040160405180910390fd5b6005810154600160401b90046001600160a01b031615610e0c5760058101548154604051632fc848ed60e01b81526001600160a01b03600160401b909304831692632fc848ed92610dd992911690339088908890600401612a12565b600060405180830381600087803b158015610df357600080fd5b505af1158015610e07573d6000803e3d6000fd5b505050505b610e1685856115db565b5050505050565b60008281526008602090815260408083206001600160a01b03851684529091529020545b92915050565b600060405163dc05711160e01b815260040160405180910390fd5b6001600160a01b038082166000908152600560205260409020541680610ebc57610e8b82611699565b6001600160a01b03838116600090815260056020526040902080546001600160a01b03191691831691909117905590505b919050565b60008281526007602052604081206002810154829190610ee29085906114b1565b6000868152600860209081526040808320338452909152902054909350610f0a9084906129ff565b9150509250929050565b6000818152600260205260409020600381015460ff1615610f4857604051630c8d9eab60e31b815260040160405180910390fd5b60038101805460ff191660019081179091556000838152602091909152604090206002825460ff166003811115610f8157610f8161259f565b03610fdd5760405183907f0cf39eedb483dd8d759788bf84c9a69e9dc611bc2da361ea04b62245015867f290600090a2600281015460038201546001830154610fd8926001600160a01b0391821692911690611760565b505050565b6003825460ff166003811115610ff557610ff561259f565b036110495760405183907f17da104c9f3b96f1a4d40b8f500c6ad4497b9fc0910a7fa050e5188628fb05a190600090a2600281015460048201548254610fd8926001600160a01b0391821692911690611760565b815460405163f4345bc960e01b815261093a9160029160ff90911690600401612968565b611075611168565b6001600160a01b0381166110da5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161093a565b610cc7816114c6565b6000826040516020016110f69190612890565b6040516020818303038152906040528051906020012060001c90506301e2850082111561113657604051637616640160e01b815260040160405180910390fd5b6111466103596020850185612469565b506000818152600460205260409020829055611161836117c3565b9392505050565b6006546001600160a01b03163314610b6b5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161093a565b6002600054036112145760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015260640161093a565b6002600055565b60008181526008602090815260408083203384529091528120805490829055819061124584611ab3565b604080516000815260208101859052929550909350339186917f80d231c3431de24ab93b46f175dcb0c3e4d22a5d14e0be106fd53ea1b60bcc0f910160405180910390a36000848152600760205260409020546112ac906001600160a01b03163383611760565b50915091565b600083815260046020908152604080832054600790925282209091806112d88786610ec1565b60008981526008602090815260408083203384529091528120559092509050611302878787611b42565b811561131e57825461131e906001600160a01b03163384611760565b6040805182815260208101849052339189917f80d231c3431de24ab93b46f175dcb0c3e4d22a5d14e0be106fd53ea1b60bcc0f910160405180910390a38060000361136c5750505050505050565b600062093a80851061137e5784611383565b62093a805b6000898152600160205260409020600501549091506113ac9082906001600160401b0316612a5e565b4211156113ce5783546113c9906001600160a01b03163384611760565b611492565b600184015484546113ec916001600160a01b03918216911684611760565b60018481015460008a815260209290925260408083206005015490516317e289e960e01b81523360048201526001600160401b0390911660248201526044810184905260648101849052603c608482015260a481019290925260c482018490526001600160a01b0316906317e289e99060e401600060405180830381600087803b15801561147957600080fd5b505af115801561148d573d6000803e3d6000fd5b505050505b5050505050505050565b600061116183670de0b6b3a764000084611bc3565b60006111618383670de0b6b3a7640000611bc3565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600081815260016020908152604080832080546001600160a01b039081168086526005909452828520549251636eb1769f60e11b815230600482015292166024830181905290939092909163dd62ed3e90604401602060405180830381865afa158015611589573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115ad919061292d565b90506115d5828460040154836115c39190612a5e565b85546001600160a01b03169190611be2565b50505050565b600082815260076020526040812060028101549091906115fc9084906114b1565b600085815260086020908152604080832033845290915281208054929350839290919061162a908490612a5e565b90915550508154611646906001600160a01b0316333084611c71565b6116508484611ca9565b6002820154604080518381526020810192909252339186917f17700ceb1658b18206f427c1578048e87504106b14ec69e9b4586d9a95174a32910160405180910390a350505050565b60006116c47f000000000000000000000000f4029759b9d469ecdfb29a7af8fed3a8f9cbaa4c611d61565b60405163189acdbd60e31b81526001600160a01b0384811660048301529192509082169063c4d66de890602401600060405180830381600087803b15801561170b57600080fd5b505af115801561171f573d6000803e3d6000fd5b50506040516001600160a01b038086169350841691507f0310432d7f6807c3b1be0e54000e643522a00a5db4a8ab89f15a30415b5eabcb90600090a3919050565b6040516001600160a01b038316602482015260448101829052610fd890849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152611df6565b6000426117d660c0840160a08501612a71565b6001600160401b0316108061180e57506117f34262ed4e00612a5e565b61180360c0840160a08501612a71565b6001600160401b0316115b1561182c5760405163eb468ebd60e01b815260040160405180910390fd5b6118396020830183612469565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611876573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061189a91906126f9565b60ff166012146118bd57604051630456c65960e51b815260040160405180910390fd5b60026118cf6040840160208501612469565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561190c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061193091906126f9565b61193a9190612a8e565b61194590600a612833565b8260600135108061196157506706f05b59d3b200008260800135105b1561197f57604051633e8bac2560e21b815260040160405180910390fd5b816040516020016119909190612890565b60408051601f198184030181529181528151602092830120600081815260019093529120549091506001600160a01b0316156119df5760405163e794df0960e01b815260040160405180910390fd5b600081815260016020526040902082906119f98282612ad4565b5050604080516080810190915280600181526000602080830182905260408084018390526060909301829052848252600290522081518154829060ff19166001836003811115611a4b57611a4b61259f565b02179055506020828101516001830155604083015160028301556060909201516003909101805460ff1916911515919091179055611aaa9033903090608086013590611a9990870187612469565b6001600160a01b0316929190611c71565b610ebc81611ecb565b60008181526003602090815260408083203380855290835281842080549085905582518581529384018190528493909286917fd9cb1e2714d65a111c0f20f060176ad657496bd47a3de04ec7c3d4ca232112ac910160405180910390a360008481526001602081905260409091200154611b37906001600160a01b03163383611760565b600094909350915050565b81600003611b4f57505050565b6040805183815260208101839052339185917fd9cb1e2714d65a111c0f20f060176ad657496bd47a3de04ec7c3d4ca232112ac910160405180910390a38015611bb95760008381526001602081905260409091200154611bb9906001600160a01b03163383611760565b610fd88383611ff1565b828202811515841585830485141716611bdb57600080fd5b0492915050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b179052611c33848261213b565b6115d5576040516001600160a01b038416602482015260006044820152611c6790859063095ea7b360e01b9060640161178c565b6115d58482611df6565b6040516001600160a01b03808516602483015283166044820152606481018290526115d59085906323b872dd60e01b9060840161178c565b60008281526002602052604081206001018054839290611cca908490612a5e565b9091555050600082815260036020908152604080832033845290915281208054839290611cf8908490612a5e565b909155505060008281526001602081905260409091200154611d25906001600160a01b0316333084611c71565b604051818152339083907fdcd726e11f8b5e160f00290f0fe3a1abb547474e53a8e7a8f49a85e7b1ca3199906020015b60405180910390a35050565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008260601b60e81c176000526e5af43d82803e903d91602b57fd5bf38260781b17602052603760096000f090506001600160a01b038116610ebc5760405162461bcd60e51b8152602060048201526016602482015275115490cc4c4d8dce8818dc99585d194819985a5b195960521b604482015260640161093a565b6000611e4b826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166121e29092919063ffffffff16565b9050805160001480611e6c575080806020019051810190611e6c9190612946565b610fd85760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161093a565b60008181526004602052604081205462093a8011611ef757600082815260046020526040902054611efc565b62093a805b60008381526001602081815260408084206007835281852081546001600160a01b039081168088526005808752858920548c8a52600480895299879020548751938452868a0154851698840198909852600280870154851684890152600387015460608501529986015460808401529401546001600160401b03811660a083015290941c811660c08501528154811660e08501529481015485166101008401529490940154610120820152929091166101408301526101608201526101808101829052909150339083907fae74ea7bd2d650ccd85bd50a9ab8edbab2e1963361fed65904e07cd746006f7c906101a001611d55565b600082815260046020908152604080832054600180845282852080546001600160a01b03908116875260058087529487205496899052919094529190920154919216906120489083906001600160401b0316612a5e565b42111561207757600084815260016020526040902054612072906001600160a01b03163385611760565b6115d5565b6000848152600160205260409020600501546001600160a01b03821690635b1fc7f290339086906120bb906120b69088906001600160401b0316612a5e565b6121f9565b6040516001600160e01b031960e086901b1681526001600160a01b03909316600484015260248301919091526001600160401b031660448201526064016020604051808303816000875af1158015612117573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e16919061292d565b6000806000846001600160a01b0316846040516121589190612ba5565b6000604051808303816000865af19150503d8060008114612195576040519150601f19603f3d011682016040523d82523d6000602084013e61219a565b606091505b50915091508180156121c45750805115806121c45750808060200190518101906121c49190612946565b80156121d957506001600160a01b0385163b15155b95945050505050565b60606121f18484600085612265565b949350505050565b60006001600160401b038211156122615760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203660448201526534206269747360d01b606482015260840161093a565b5090565b6060824710156122c65760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161093a565b600080866001600160a01b031685876040516122e29190612ba5565b60006040518083038185875af1925050503d806000811461231f576040519150601f19603f3d011682016040523d82523d6000602084013e612324565b606091505b509150915061233587838387612340565b979650505050505050565b606083156123af5782516000036123a8576001600160a01b0385163b6123a85760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161093a565b50816121f1565b6121f183838151156123c45781518083602001fd5b8060405162461bcd60e51b815260040161093a9190612bc1565b600060e082840312156123f057600080fd5b50919050565b6001600160a01b0381168114610cc757600080fd5b6000806000806000610160868803121561242457600080fd5b61242e87876123de565b945060e086013561243e816123f6565b935061010086013561244f816123f6565b949793965093946101208101359450610140013592915050565b60006020828403121561247b57600080fd5b8135611161816123f6565b634e487b7160e01b600052604160045260246000fd5b600080604083850312156124af57600080fd5b8235915060208301356001600160401b03808211156124cd57600080fd5b818501915085601f8301126124e157600080fd5b8135818111156124f3576124f3612486565b604051601f8201601f19908116603f0116810190838211818310171561251b5761251b612486565b8160405282815288602084870101111561253457600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b60006020828403121561256857600080fd5b5035919050565b6000806040838503121561258257600080fd5b823591506020830135612594816123f6565b809150509250929050565b634e487b7160e01b600052602160045260246000fd5b600481106125d357634e487b7160e01b600052602160045260246000fd5b9052565b60006080820190506125ea8284516125b5565b602083015160208301526040830151604083015260608301511515606083015292915050565b6000806000806060858703121561262657600080fd5b843593506020850135925060408501356001600160401b038082111561264b57600080fd5b818701915087601f83011261265f57600080fd5b81358181111561266e57600080fd5b88602082850101111561268057600080fd5b95989497505060200194505050565b60008061010083850312156126a357600080fd5b6126ad84846123de565b9460e0939093013593505050565b600060e082840312156126cd57600080fd5b61116183836123de565b600080604083850312156126ea57600080fd5b50508035926020909101359150565b60006020828403121561270b57600080fd5b815160ff8116811461116157600080fd5b60006020828403121561272e57600080fd5b8151611161816123f6565b634e487b7160e01b600052601160045260246000fd5b600181815b8085111561278a57816000190482111561277057612770612739565b8085161561277d57918102915b93841c9390800290612754565b509250929050565b6000826127a157506001610e41565b816127ae57506000610e41565b81600181146127c457600281146127ce576127ea565b6001915050610e41565b60ff8411156127df576127df612739565b50506001821b610e41565b5060208310610133831016604e8410600b841016171561280d575081810a610e41565b612817838361274f565b806000190482111561282b5761282b612739565b029392505050565b600061116160ff841683612792565b8082028115828204841417610e4157610e41612739565b60008261287657634e487b7160e01b600052601260045260246000fd5b500490565b6001600160401b0381168114610cc757600080fd5b60e08101823561289f816123f6565b6001600160a01b0390811683526020840135906128bb826123f6565b90811660208401526040840135906128d2826123f6565b8082166040850152606085013560608501526080850135608085015260a085013591506128fe8261287b565b6001600160401b03821660a085015260c0850135915061291d826123f6565b80821660c0850152505092915050565b60006020828403121561293f57600080fd5b5051919050565b60006020828403121561295857600080fd5b8151801515811461116157600080fd5b6040810161297682856125b5565b61116160208301846125b5565b60005b8381101561299e578181015183820152602001612986565b50506000910152565b600081518084526129bf816020860160208601612983565b601f01601f19169290920160200192915050565b6001600160a01b038481168252831660208201526060604082018190526000906121d9908301846129a7565b81810381811115610e4157610e41612739565b6001600160a01b0385811682528416602082015260606040820181905281018290526000828460808401376000608084840101526080601f19601f850116830101905095945050505050565b80820180821115610e4157610e41612739565b600060208284031215612a8357600080fd5b81356111618161287b565b60ff8281168282160390811115610e4157610e41612739565b80546001600160a01b0319166001600160a01b0392909216919091179055565b60008135610e41816123f6565b8135612adf816123f6565b612ae98183612aa7565b506020820135612af8816123f6565b612b058160018401612aa7565b506040820135612b14816123f6565b612b218160028401612aa7565b5060608201356003820155608082013560048201556005810160a0830135612b488161287b565b6001600160401b0381166001600160401b031983541617825550610fd8612b7160c08501612ac7565b82805468010000000000000000600160e01b03191660409290921b68010000000000000000600160e01b0316919091179055565b60008251612bb7818460208701612983565b9190910192915050565b60208152600061116160208301846129a756fea2646970667358221220a5a1ac180e7b7db8c99018ab323ec3d95f94273de78d23fe760de101558b11a164736f6c63430008120033

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

Txn Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]
[ 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.