ETH Price: $3,116.45 (+1.87%)
Gas: 3 Gwei

Contract

0x156AdCb9f74DCC07596821DC28d935eC988AbF75
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Token Holdings

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Value
Release202485232024-07-06 16:00:234 days ago1720281623IN
0x156AdCb9...C988AbF75
0 ETH0.00053955.06511353
Release202403842024-07-05 12:44:115 days ago1720183451IN
0x156AdCb9...C988AbF75
0 ETH0.000799548.94208761
Release202399202024-07-05 11:10:595 days ago1720177859IN
0x156AdCb9...C988AbF75
0 ETH0.000959949.01240804
Release202354722024-07-04 20:16:116 days ago1720124171IN
0x156AdCb9...C988AbF75
0 ETH0.000848957.97034899
Release201988102024-06-29 17:23:5911 days ago1719681839IN
0x156AdCb9...C988AbF75
0 ETH0.000339783.80008191
Release201824212024-06-27 10:26:5913 days ago1719484019IN
0x156AdCb9...C988AbF75
0 ETH0.000348933.90243215
Release201824142024-06-27 10:25:3513 days ago1719483935IN
0x156AdCb9...C988AbF75
0 ETH0.000360214.02860768
Release201824072024-06-27 10:24:1113 days ago1719483851IN
0x156AdCb9...C988AbF75
0 ETH0.000311953.48887768
Release201523812024-06-23 5:42:1117 days ago1719121331IN
0x156AdCb9...C988AbF75
0 ETH0.000256872.41162431
Release201044282024-06-16 12:43:1124 days ago1718541791IN
0x156AdCb9...C988AbF75
0 ETH0.000453284.25562286
Release200923872024-06-14 20:18:2326 days ago1718396303IN
0x156AdCb9...C988AbF75
0 ETH0.0013664612.82896049
Release200793102024-06-13 0:25:2328 days ago1718238323IN
0x156AdCb9...C988AbF75
0 ETH0.000980659.20678547
Release200733132024-06-12 4:18:2328 days ago1718165903IN
0x156AdCb9...C988AbF75
0 ETH0.000514455.75364007
Release200732762024-06-12 4:10:5928 days ago1718165459IN
0x156AdCb9...C988AbF75
0 ETH0.000556936.22870918
Release200732652024-06-12 4:08:4728 days ago1718165327IN
0x156AdCb9...C988AbF75
0 ETH0.000517545.78822452
Release200464522024-06-08 10:15:3532 days ago1717841735IN
0x156AdCb9...C988AbF75
0 ETH0.000680226.38626942
Release199968992024-06-01 12:14:2339 days ago1717244063IN
0x156AdCb9...C988AbF75
0 ETH0.000568225.33473928
Release199946032024-06-01 4:32:3539 days ago1717216355IN
0x156AdCb9...C988AbF75
0 ETH0.000566425.31785491
Release199636662024-05-27 20:43:1144 days ago1716842591IN
0x156AdCb9...C988AbF75
0 ETH0.0026455324.83742834
Release199599562024-05-27 8:16:2344 days ago1716797783IN
0x156AdCb9...C988AbF75
0 ETH0.000854479.55637741
Release199599502024-05-27 8:15:1144 days ago1716797711IN
0x156AdCb9...C988AbF75
0 ETH0.000854229.55358877
Release199599432024-05-27 8:13:4744 days ago1716797627IN
0x156AdCb9...C988AbF75
0 ETH0.000766118.56813819
Release199395582024-05-24 11:51:1147 days ago1716551471IN
0x156AdCb9...C988AbF75
0 ETH0.00065396.13911003
Release199294362024-05-23 1:55:2348 days ago1716429323IN
0x156AdCb9...C988AbF75
0 ETH0.000869887.03712804
Release199272522024-05-22 18:36:3549 days ago1716402995IN
0x156AdCb9...C988AbF75
0 ETH0.0018480917.35075187
View all transactions

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To Value
196661302024-04-16 6:02:1185 days ago1713247331  Contract Creation0 ETH
Loading...
Loading

Minimal Proxy Contract for 0x6d721587a0d7566133709355944523114c5fa0f8

Contract Name:
VestingCustomRefundUser

Compiler Version
v0.8.19+commit.7dd6d404

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 25 : VestingCustomRefundUser.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {UnitConverter} from "./libraries/UnitConverter.sol";
import {VestingCustomRefund} from "./VestingCustomRefund.sol";
import {IFactoryImplementation} from "./interfaces/IFactoryImplementation.sol";
import {IVestingCustomRefund} from "./interfaces/IVestingCustomRefund.sol";
import {IVestingCustomRefundProject} from "./interfaces/IVestingCustomRefundProject.sol";
import {IVestingCustomRefundUser} from "./interfaces/IVestingCustomRefundUser.sol";

/**
 * @title VestingCustomRefundUser
 * @author Tim Loh
 * @notice Provides an implementation of custom vesting with refund for user interface
 */
contract VestingCustomRefundUser is VestingCustomRefund, IVestingCustomRefundUser {
    using SafeERC20 for IERC20;
    using UnitConverter for uint256;

    struct PaymentReceivedInfo {
        address paymentVestingAddress; // Address of custom vesting contract containing payment tokens received
        uint256 rate; // How many weis one token costs in payment token
    }

    uint256 public constant TOKEN_RATE_SCALE = 10 ** TOKEN_MAX_DECIMALS;

    PaymentReceivedInfo private _paymentReceivedInfo;

    /**
     * @param tokenAddress_ The address of vesting token
     * @param tokenDecimals_ The number of decimals for vesting token
     * @param allowAccumulate_ `true` if multiple grant amounts is allowed to accumulate for the same user,
     *                         `false` if a user can only have one grant
     * @param backofficeAdminAddress The address that will be assigned the backoffice role admin role and backoffice
     *                               contract admin role
     * @param tenantAdminAddress The address that will be assigned the tenant role admin role, tenant governance role
     *                           and tenant contract admin role
     */
    function initialize(
        address tokenAddress_,
        uint256 tokenDecimals_,
        bool allowAccumulate_,
        address backofficeAdminAddress,
        address tenantAdminAddress
    ) public virtual override initializer {
        __VestingCustomRefundUser_init(
            tokenAddress_,
            tokenDecimals_,
            allowAccumulate_,
            backofficeAdminAddress,
            tenantAdminAddress
        );
    }

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function __VestingCustomRefundUser_init(
        // solhint-disable-previous-line func-name-mixedcase
        address tokenAddress_,
        uint256 tokenDecimals_,
        bool allowAccumulate_,
        address backofficeAdminAddress,
        address tenantAdminAddress
    ) internal onlyInitializing {
        __VestingCustomRefund_init_unchained(
            tokenAddress_,
            tokenDecimals_,
            allowAccumulate_,
            backofficeAdminAddress,
            tenantAdminAddress
        );
        __VestingCustomRefundUser_init_unchained();
    }

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function __VestingCustomRefundUser_init_unchained() internal onlyInitializing {
        // solhint-disable-previous-line func-name-mixedcase, no-empty-blocks
    }

    /**
     * @inheritdoc IVestingCustomRefundUser
     */
    function cancelRefundWindow() external virtual override onlyRole(BACKOFFICE_CONTRACT_ADMIN_ROLE) {
        // solhint-disable-previous-line ordering

        _cancelRefundWindow();

        if (_paymentReceivedInfo.paymentVestingAddress != address(0)) {
            require(
                IVestingCustomRefundProject(_paymentReceivedInfo.paymentVestingAddress).cancelRefundWindow(),
                "VCRU: cancel payment refund"
            );
        }
    }

    /**
     * @inheritdoc IVestingCustomRefundUser
     */
    function extendRefundWindow(
        uint256 newDurationSeconds
    ) external virtual override onlyRole(BACKOFFICE_CONTRACT_ADMIN_ROLE) {
        _extendRefundWindow(newDurationSeconds);

        if (_paymentReceivedInfo.paymentVestingAddress != address(0)) {
            require(
                IVestingCustomRefundProject(_paymentReceivedInfo.paymentVestingAddress).extendRefundWindow(
                    newDurationSeconds
                ),
                "VCRU: extend payment refund"
            );
        }
    }

    /**
     * @inheritdoc IVestingCustomRefundUser
     */
    function refund() external virtual override whenNotPaused {
        require(!hasRefundedFor(msg.sender), "VCRU: refunded");
        require(!hasReleasedFor(msg.sender), "VCRU: claimed");

        uint256 refundableTokenAmount = _refundableAmountFor(msg.sender);
        require(refundableTokenAmount > 0, "VCRU: zero token refundable");

        uint256 refundableTokenDecimalsAmount = refundableTokenAmount.scaleWeiToDecimals(tokenDecimals);
        uint256 refundableTokenWeiAmount = refundableTokenDecimalsAmount.scaleDecimalsToWei(tokenDecimals);
        require(refundableTokenWeiAmount > 0, "VCRU: zero token refund");

        uint256 refundablePaymentAmount = _paymentReceivedInfo.rate > 0
            ? (refundableTokenWeiAmount * _paymentReceivedInfo.rate) / TOKEN_RATE_SCALE
            : 0;
        require(
            _paymentReceivedInfo.paymentVestingAddress == address(0) || refundablePaymentAmount > 0,
            "VCRU: zero payment refund"
        );

        _refund(msg.sender, refundableTokenWeiAmount);

        emit TokensRefunded(msg.sender, refundableTokenWeiAmount, refundablePaymentAmount);

        if (_paymentReceivedInfo.paymentVestingAddress != address(0)) {
            require(
                IVestingCustomRefundProject(_paymentReceivedInfo.paymentVestingAddress).refund(
                    msg.sender,
                    refundablePaymentAmount
                ),
                "VCRU: refund payment"
            );
        }
    }

    /**
     * @inheritdoc IVestingCustomRefund
     * @dev Cannot claim if have previously refunded
     */
    function release() external virtual override(VestingCustomRefund, IVestingCustomRefund) whenNotPaused {
        require(!hasRefundedFor(msg.sender), "VCRU: refunded");

        uint256 releasableAmount = releasableAmountFor(msg.sender);

        _release(msg.sender, releasableAmount);
    }

    /**
     * @inheritdoc IVestingCustomRefundUser
     */
    function removePaymentReceivedInfo() external virtual override onlyRole(BACKOFFICE_CONTRACT_ADMIN_ROLE) {
        require(!hasRefundWindowStarted(block.timestamp), "VCRU: refund started");

        address paymentVestingAddress = _paymentReceivedInfo.paymentVestingAddress;
        uint256 rate = _paymentReceivedInfo.rate;

        _paymentReceivedInfo.paymentVestingAddress = address(0);
        _paymentReceivedInfo.rate = 0;

        emit PaymentReceivedInfoRemoved(msg.sender, paymentVestingAddress, rate);
    }

    /**
     * @inheritdoc IVestingCustomRefund
     * @dev Cannot revoke if have previously refunded
     */
    function revokeVestingGrant(
        address account
    ) external virtual override(VestingCustomRefund, IVestingCustomRefund) onlyRole(TENANT_CONTRACT_ADMIN_ROLE) {
        require(!hasRefundedFor(account), "VCRU: refunded");

        _revokeVestingGrant(account);
    }

    /**
     * @inheritdoc IVestingCustomRefundUser
     */
    function setPaymentReceivedInfo(
        address paymentVestingAddress,
        uint256 rate
    ) external virtual override onlyRole(BACKOFFICE_CONTRACT_ADMIN_ROLE) {
        require(paymentVestingAddress != address(0), "VCRU: payment vesting");
        require(rate > 0, "VCRU: rate");
        require(!hasRefundWindowStarted(block.timestamp), "VCRU: refund started");

        _paymentReceivedInfo.paymentVestingAddress = paymentVestingAddress;
        _paymentReceivedInfo.rate = rate;

        emit PaymentReceivedInfoSet(msg.sender, paymentVestingAddress, rate);

        bool supportsVestingCustomRefundProjectInterface = IVestingCustomRefundProject(paymentVestingAddress)
            .supportsInterface(type(IVestingCustomRefundProject).interfaceId);
        require(supportsVestingCustomRefundProjectInterface, "VCRU: interface");

        if (isRefundWindowDefined()) {
            (uint256 startTimestamp, uint256 durationSeconds, ) = getRefundWindow();

            require(
                IVestingCustomRefundProject(paymentVestingAddress).setRefundWindow(startTimestamp, durationSeconds),
                "VCRU: project set refund"
            );
        } else {
            // https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return
            // slither-disable-next-line unused-return
            (uint256 startTimestamp, , ) = IVestingCustomRefundProject(paymentVestingAddress).getRefundWindow();

            if (startTimestamp > 0) {
                require(
                    IVestingCustomRefundProject(paymentVestingAddress).cancelRefundWindow(),
                    "VCRU: project cancel refund"
                );
            }
        }
    }

    /**
     * @inheritdoc IVestingCustomRefundUser
     */
    function setRefundWindow(
        uint256 startTimestamp,
        uint256 durationSeconds
    ) external virtual override onlyRole(BACKOFFICE_CONTRACT_ADMIN_ROLE) {
        require(startTimestamp > block.timestamp, "VCRU: start timestamp");
        require(isVestingScheduleDefined(), "VCRU: undefined schedule");
        require(hasVestingScheduleStarted(startTimestamp), "VCRU: before schedule start");

        _setRefundWindow(startTimestamp, durationSeconds);

        if (_paymentReceivedInfo.paymentVestingAddress != address(0)) {
            require(
                IVestingCustomRefundProject(_paymentReceivedInfo.paymentVestingAddress).setRefundWindow(
                    startTimestamp,
                    durationSeconds
                ),
                "VCRU: set payment refund"
            );
        }
    }

    /**
     * @inheritdoc IFactoryImplementation
     */
    function factoryImplementationType()
        external
        view
        virtual
        override(VestingCustomRefund, IFactoryImplementation)
        returns (uint256 implementationType)
    {
        implementationType = 0x59eb2902326a23c3fb6e66c499c661a6165df892fc643c67c712570ad48e50d3;
    }

    /**
     * @inheritdoc IVestingCustomRefundUser
     */
    function getPaymentReceivedInfo()
        external
        view
        virtual
        override
        returns (address paymentVestingAddress, uint256 rate)
    {
        paymentVestingAddress = _paymentReceivedInfo.paymentVestingAddress;
        rate = _paymentReceivedInfo.rate;
    }

    /**
     * @inheritdoc IVestingCustomRefundUser
     */
    function refundableAmountFor(address account) external view virtual override returns (uint256 refundableAmount) {
        refundableAmount = _refundableAmountFor(account);
    }
}

File 2 of 25 : 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 3 of 25 : 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 4 of 25 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/Address.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) || (!Address.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 5 of 25 : 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 6 of 25 : 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 7 of 25 : 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 8 of 25 : 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 9 of 25 : 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 10 of 25 : 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 11 of 25 : 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 12 of 25 : 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 13 of 25 : 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 14 of 25 : 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 15 of 25 : 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 16 of 25 : AdminPrivileges.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {IAdminPrivileges} from "./interfaces/IAdminPrivileges.sol";

/**
 * @title AdminPrivileges
 * @author Tim Loh
 * @notice Provides admin privileges role definitions that are inherited by other contracts
 */
contract AdminPrivileges is AccessControl, IAdminPrivileges {
    bytes32 public constant BACKOFFICE_ROLE_ADMIN_ROLE = keccak256("BACKOFFICE_ROLE_ADMIN_ROLE");
    bytes32 public constant BACKOFFICE_GOVERNANCE_ROLE = keccak256("BACKOFFICE_GOVERNANCE_ROLE");
    bytes32 public constant BACKOFFICE_CONTRACT_ADMIN_ROLE = keccak256("BACKOFFICE_CONTRACT_ADMIN_ROLE");

    bytes32 public constant TENANT_ROLE_ADMIN_ROLE = keccak256("TENANT_ROLE_ADMIN_ROLE");
    bytes32 public constant TENANT_GOVERNANCE_ROLE = keccak256("TENANT_GOVERNANCE_ROLE");
    bytes32 public constant TENANT_CONTRACT_ADMIN_ROLE = keccak256("TENANT_CONTRACT_ADMIN_ROLE");
}

File 17 of 25 : AdminWallet.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

import {IAdminWallet} from "./interfaces/IAdminWallet.sol";

/**
 * @title AdminWallet
 * @author Tim Loh
 * @notice Provides an implementation of the admin wallet interface that is inherited by other contracts
 */
contract AdminWallet is IAdminWallet {
    address private _adminWallet;

    /**
     * @inheritdoc IAdminWallet
     */
    function adminWallet() public view virtual override returns (address) {
        return _adminWallet;
    }

    /**
     * @dev Change admin wallet that will receive the funds to a new wallet address
     * @param newWallet The new admin wallet address
     */
    function _setAdminWallet(address newWallet) internal virtual {
        require(newWallet != address(0), "AdminWallet: new wallet");

        address oldWallet = _adminWallet;
        _adminWallet = newWallet;

        emit AdminWalletChanged(oldWallet, newWallet, msg.sender);
    }
}

File 18 of 25 : IAdminPrivileges.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

/**
 * @title AdminPrivileges Interface
 * @author Tim Loh
 * @notice Interface for admin privileges role definitions that are inherited by other contracts
 */
interface IAdminPrivileges {
    // solhint-disable func-name-mixedcase

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function BACKOFFICE_ROLE_ADMIN_ROLE() external view returns (bytes32);

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function BACKOFFICE_GOVERNANCE_ROLE() external view returns (bytes32);

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function BACKOFFICE_CONTRACT_ADMIN_ROLE() external view returns (bytes32);

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function TENANT_ROLE_ADMIN_ROLE() external view returns (bytes32);

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function TENANT_GOVERNANCE_ROLE() external view returns (bytes32);

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function TENANT_CONTRACT_ADMIN_ROLE() external view returns (bytes32);

    // solhint-enable func-name-mixedcase
}

File 19 of 25 : IAdminWallet.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

/**
 * @title AdminWallet Interface
 * @author Tim Loh
 * @notice Interface for admin wallet that will receive the funds
 */
interface IAdminWallet {
    /**
     * @notice Emitted when admin wallet has been changed from `oldWallet` to `newWallet`
     * @param oldWallet The wallet before the wallet was changed
     * @param newWallet The wallet after the wallet was changed
     * @param sender The address that changes the admin wallet
     */
    event AdminWalletChanged(address indexed oldWallet, address indexed newWallet, address indexed sender);

    /**
     * @notice Returns the admin wallet address that will receive the funds
     * @return Admin wallet address
     */
    function adminWallet() external view returns (address);
}

File 20 of 25 : IFactoryImplementation.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

/**
 * @title IFactoryImplementation
 * @author Tim Loh
 * @notice Provides factory implementation type that is inherited by reference implementation contracts for matching
 *         with corresponding factory contracts
 */
interface IFactoryImplementation {
    function factoryImplementationType() external view returns (uint256);
}

File 21 of 25 : IVestingCustomRefund.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {IAdminPrivileges} from "./IAdminPrivileges.sol";
import {IAdminWallet} from "./IAdminWallet.sol";
import {IFactoryImplementation} from "./IFactoryImplementation.sol";

/**
 * @title IVestingCustomRefund
 * @author Tim Loh
 * @notice Interface for custom vesting with refund
 */
interface IVestingCustomRefund is IAccessControl, IAdminPrivileges, IAdminWallet, IFactoryImplementation {
    /**
     * @notice Emitted when refund window has been cancelled
     * @param sender The address that cancelled the refund
     * @param refundStartTimestamp Timestamp when cancelled refund window will start
     * @param refundDurationSeconds Duration of cancelled refund window in seconds
     * @param refundEndTimestamp Timestamp when cancelled refund window will end
     */
    event RefundWindowCancelled(
        address indexed sender,
        uint256 refundStartTimestamp,
        uint256 refundDurationSeconds,
        uint256 refundEndTimestamp
    );

    /**
     * @notice Emitted when refund window has been extended
     * @param sender The address that extended the refund window
     * @param newDurationSeconds Refund window duration in seconds after extension
     * @param newEndTimestamp Timestamp when refund window will end after extension
     * @param oldDurationSeconds Refund window duration in seconds before extension
     * @param oldEndTimestamp Timestamp when refund window will end before extension
     */
    event RefundWindowExtended(
        address indexed sender,
        uint256 newDurationSeconds,
        uint256 newEndTimestamp,
        uint256 oldDurationSeconds,
        uint256 oldEndTimestamp
    );

    /**
     * @notice Emitted when refund window has been set
     * @param sender The address that set the refund window
     * @param startTimestamp Timestamp when refund window will start
     * @param durationSeconds Refund window duration in seconds
     * @param endTimestamp Timestamp when refund window will end
     */
    event RefundWindowSet(
        address indexed sender,
        uint256 startTimestamp,
        uint256 durationSeconds,
        uint256 endTimestamp
    );

    /**
     * @notice Emitted when vesting schedule has been set
     * @param sender The address that set the vesting schedule
     * @param startTimestamps Array specifying the start timestamps of each period
     * @param percentReleases Array specifying the percentage of grant amount to be released for each period
     * @param durationsDays Array specifying the duration in days of each period
     */
    event ScheduleSet(
        address indexed sender,
        uint256[] startTimestamps,
        uint256[] percentReleases,
        uint256[] durationsDays
    );

    /**
     * @notice Emitted when vested tokens have been released to `account`
     * @param account The address that received the released tokens
     * @param amount The amount of tokens in wei transferred to `account`
     */
    event TokensReleased(address indexed account, uint256 amount);

    /**
     * @notice Emitted when unused tokens have been transferred to the admin wallet
     * @param sender The address that initiated the transfer of unused tokens
     * @param unusedAmount The amount of tokens in wei transferred to the admin wallet
     * @param balanceInWei The amount of tokens in wei held by the custom vesting contract before transfer
     * @param totalReleasedAmount The total amount of tokens in wei that has been released so far
     * @param totalRevokedAmount The total amount of tokens in wei that has been revoked so far
     * @param totalRefundAmount The total amount of tokens in wei that has been refunded so far
     * @param totalGrantAmount The total vesting grant token amount in wei that has been added so far
     */
    event UnusedTokensTransferred(
        address indexed sender,
        uint256 unusedAmount,
        uint256 balanceInWei,
        uint256 totalReleasedAmount,
        uint256 totalRevokedAmount,
        uint256 totalRefundAmount,
        uint256 totalGrantAmount
    );

    /**
     * @notice Emitted when vesting grant has been added
     * @param account The address that has the vesting grant added
     * @param grantAmount The grant token amount in wei
     * @param isRevocable `true` if vesting grant is revocable
     *                    `false` if vesting grant is not revocable
     */
    event VestingGrantAdded(address indexed account, uint256 grantAmount, bool isRevocable);

    /**
     * @notice Emitted when vesting grant has been revoked
     * @param account The address that has the vesting grant revoked
     * @param remainderAmount The amount of tokens in wei that has been revoked for `account`
     * @param grantAmount The grant token amount in wei
     * @param refundedAmount The amount of tokens in wei that has been refunded to `account`
     * @param releasedAmount The amount of tokens in wei that has been released to `account`
     */
    event VestingGrantRevoked(
        address indexed account,
        uint256 remainderAmount,
        uint256 grantAmount,
        uint256 refundedAmount,
        uint256 releasedAmount
    );

    /**
     * @notice Add vesting grant for `account`
     * @dev Must be called by tenant contract admin role
     * @dev grant can only be added before schedule start
     * @dev grant cannot be added if previous grant has been revoked
     * @dev isRevocable will be ignored if grant already added but amount allowed to accumulate
     * @param account The address that will have the vesting grant added
     * @param grantAmount The token amount in wei to be granted
     * @param isRevocable `true` if vesting grant is revocable
     *                    `false` if vesting grant is not revocable
     */
    function addVestingGrant(address account, uint256 grantAmount, bool isRevocable) external;

    /**
     * @notice Batch add vesting grants for specified `accounts`
     * @dev Must be called by tenant contract admin role
     * @param accounts Array specifying the addresses that will have the vesting grants added
     * @param grantAmounts Array specifying the amount of tokens in wei to be granted for each account
     * @param isRevocables Array soecuftubg whether each grant is revocable
     */
    function addVestingGrantsBatch(
        address[] memory accounts,
        uint256[] memory grantAmounts,
        bool[] memory isRevocables
    ) external;

    /**
     * @notice Pause user functions
     * @dev Must be called by tenant contract admin role
     */
    function pauseContract() external;

    /**
     * @notice Release vested tokens to sender
     * @dev Can only release if vesting schedule is defined
     * @dev Can only release when vesting schedule has started
     * @dev Cannot release if grant has been revoked
     */
    function release() external;

    /**
     * @notice Revoke vesting grant for `account`
     * @dev Must be called by tenant contract admin role
     * @dev Only revocable grants can be revoked
     * @param account The address that will have the vesting grant revoked
     */
    function revokeVestingGrant(address account) external;

    /**
     * @notice Batch revoke vesting grants for specified `accounts`
     * @dev Must be called by tenant contract admin role
     * @dev Only revocable grants can be revoked
     * @param accounts Array specifying the addresses that will have the vesting grants revoked
     */
    function revokeVestingGrantsBatch(address[] memory accounts) external;

    /**
     * @notice Change admin wallet that will receive funds to a new wallet address
     * @dev Must be called by tenant governance role
     * @param newWallet The new admin wallet
     */
    function setAdminWallet(address newWallet) external;

    /**
     * @notice Set vesting schedule
     * @dev Must be called by tenant contract admin role
     * @param startTimestamps Array specifying the start timestamps of each period
     * @param percentReleases Array specifying the percentage of grant amount to be released for each period
     * @param durationsDays Array specifying the duration in days of each period
     */
    function setVestingSchedule(
        uint256[] calldata startTimestamps,
        uint256[] calldata percentReleases,
        uint256[] calldata durationsDays
    ) external;

    /**
     * @notice Transfer unused tokens to the admin wallet
     * @dev Must be called by tenant contract admin role
     */
    function transferUnusedTokens() external;

    /**
     * @notice Unpause user functions
     * @dev Must be called by tenant contract admin role
     */
    function unpauseContract() external;

    /**
     * @notice Get whether multiple grant amounts is allowed to accumulate for the same user
     * @return Returns `true` if multiple grant amounts is allowed to accumulate for the same user,
     *                 `false` if a user can only have one grant
     */
    function allowAccumulate() external view returns (bool);

    /**
     * @notice Get maximum number of grants allowed per batch
     * @return Returns maximum number of grants allowed per batch
     */
    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function BATCH_MAX_NUM() external view returns (uint256); // solhint-disable-line func-name-mixedcase

    /**
     * @notice Get maximum number of schedule entries allowed
     * @return Returns maximum number of schedule entries allowed
     */
    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function SCHEDULE_MAX_ENTRIES() external view returns (uint256); // solhint-disable-line func-name-mixedcase

    /**
     * @notice Get effective grant amount for `account`
     * @param account The address to check
     * @return grantAmountWei The effective grant amount in wei for `account`
     */
    function effectiveGrantAmountFor(address account) external view returns (uint256 grantAmountWei);

    /**
     * @notice Get refund window
     * @return startTimestamp The start timestamp of refund window
     * @return durationSeconds The duration of refund window in seconds
     * @return endTimestamp The end timestamp of refund window
     */
    function getRefundWindow()
        external
        view
        returns (uint256 startTimestamp, uint256 durationSeconds, uint256 endTimestamp);

    /**
     * @notice Get vesting schedule
     * @param startTimestamps Array specifying the start timestamps of each period
     * @param percentReleases Array specifying the percentage of grant amount to be released for each period
     * @param durationsDays Array specifying the duration in days of each period
     * @param endTimestamps Array specifying the end timestamps of each period
     */
    function getVestingSchedule()
        external
        view
        returns (
            uint256[] memory startTimestamps,
            uint256[] memory percentReleases,
            uint256[] memory durationsDays,
            uint256[] memory endTimestamps
        );

    /**
     * @notice Check whether `account` has been refunded
     * @param account The address to check
     * @return hasRefunded `true` if `account` has been refunded
     */
    function hasRefundedFor(address account) external view returns (bool hasRefunded);

    /**
     * @notice Check whether `account` has claimed before
     * @param account The address to check
     * @return hasReleased `true` if `account` has claimed before
     */
    function hasReleasedFor(address account) external view returns (bool hasReleased);

    /**
     * @notice Check whether refund window already started at `atTimestamp`
     * @param atTimestamp The timestamp to check
     * @return hasStarted `true` if refund window already started at `atTimestamp`
     */
    function hasRefundWindowStarted(uint256 atTimestamp) external view returns (bool hasStarted);

    /**
     * @notice Check whether vesting schedule already started at `atTimestamp`
     * @param atTimestamp The timestamp to check
     * @return hasStarted `true` if vesting schedule already started at `atTimestamp`
     */
    function hasVestingScheduleStarted(uint256 atTimestamp) external view returns (bool hasStarted);

    /**
     * @notice Check whether refund window has been defined
     * @return isDefined `true` if refund window has been defined
     */
    function isRefundWindowDefined() external view returns (bool isDefined);

    /**
     * @notice Check whether refund window is open now
     * @return isOpen `true` if refund window is open now
     */
    function isRefundWindowOpenNow() external view returns (bool isOpen);

    /**
     * @notice Check whether vesting schedule has been defined
     * @return isDefined `true` if vesting schedule has been defined
     */
    function isVestingScheduleDefined() external view returns (bool isDefined);

    /**
     * @notice Get current number of schedule entries
     * @return Returns current number of schedule entries
     */
    function numVestingScheduleEntries() external view returns (uint256);

    /**
     * @notice Get refunded token amount for `account`
     * @param account The address to check
     * @return refundedAmount The token amount in wei that has been refunded to `account`
     */
    function refundedAmountFor(address account) external view returns (uint256 refundedAmount);

    /**
     * @notice Get releasable token amount for `account`
     * @param account The address to check
     * @return releasableAmount The token amount in wei that is releasable for `account`
     */
    function releasableAmountFor(address account) external view returns (uint256 releasableAmount);

    /**
     * @notice Get released token amount for `account`
     * @param account The address to check
     * @return releasedAmount The token amount in wei that has been released to `account`
     */
    function releasedAmountFor(address account) external view returns (uint256 releasedAmount);

    /**
     * @notice Check whether vesting grant for `account` has been revoked
     * @param account The address to check
     * @return isRevoked `true` if vesting grant for `account` has been revoked
     */
    function revoked(address account) external view returns (bool isRevoked);

    /**
     * @notice Get address of vesting token
     * @return Returns the address of vesting token
     */
    function tokenAddress() external view returns (address);

    /**
     * @notice Get the number of decimals for vesting token
     * @return Returns the number of decimals for vesting token
     */
    function tokenDecimals() external view returns (uint256);

    /**
     * @notice Get the total token amount of vesting grants
     * @return Returns the total token amount in wei of vesting grants
     */
    function totalGrantAmount() external view returns (uint256);

    /**
     * @notice Get the total token amount that has been refunded
     * @return Returns the total token amount in wei that has been refunded
     */
    function totalRefundAmount() external view returns (uint256);

    /**
     * @notice Get the total token amount that has been released
     * @return Returns the total token amount in wei that has been released
     */
    function totalReleasedAmount() external view returns (uint256);

    /**
     * @notice Get the total token amount that has been revoked
     * @return Returns the total token amount in wei that has been revoked
     */
    function totalRevokedAmount() external view returns (uint256);

    /**
     * @notice Get unvested token amount for `account`
     * @param account The address to check
     * @return unvestedAmount The token amount in wei that has not vested yet for `account`
     */
    function unvestedAmountFor(address account) external view returns (uint256 unvestedAmount);

    /**
     * @notice Get vested token amount for `account`
     * @param account The address to check
     * @return vestedAmount The token amount in wei that has vested for `account`
     */
    function vestedAmountFor(address account) external view returns (uint256 vestedAmount);

    /**
     * @notice Get vesting grant for`account`
     * @param account The address to check
     * @return grantAmount The vesting grant token amount in wei for `account`
     * @return isRevocable `true` if vesting grant for `account` can be revoked
     * @return isRevoked `true` if vesting grant for `account` has been revoked
     * @return isActive `true` if vesting grant for `account` is active
     */
    function vestingGrantFor(
        address account
    ) external view returns (uint256 grantAmount, bool isRevocable, bool isRevoked, bool isActive);
}

File 22 of 25 : IVestingCustomRefundProject.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

import {IVestingCustomRefund} from "./IVestingCustomRefund.sol";

/**
 * @title IVestingCustomRefundProject
 * @author Tim Loh
 * @notice Interface for custom vesting with refund for project
 */
interface IVestingCustomRefundProject is IVestingCustomRefund {
    /**
     * @notice Emitted when tokens have been refunded to `account`
     * @param account The address that received the refund
     * @param refundAmount The amount to be refunded to `account`
     */
    event TokensRefunded(address indexed account, uint256 refundAmount);

    /**
     * @notice Cancel refund window
     * @dev Must be called by contract usage role
     * @dev Can only cancel when refund window has not started yet
     */
    function cancelRefundWindow() external returns (bool isCancelled);

    /**
     * @notice Extend refund window
     * @dev Must be called by contract usage role
     * @dev Can only extend when refund window is open
     * @param newDurationSeconds New refund window duration in seconds
     */
    function extendRefundWindow(uint256 newDurationSeconds) external returns (bool isExtended);

    /**
     * @notice Refund specified amount of tokens to `account`
     * @dev Can only refund if vesting schedule is defined
     * @dev Can only refund when refund window is open
     * @dev Cannot refund if grant has been revoked
     * @param account The address to receive the refunded amount of tokens
     * @param amount The token amount in wei to be refunded to `account`
     */
    function refund(address account, uint256 amount) external returns (bool isRefunded);

    /**
     * @notice Set refund window
     * @dev Must be called by contract usage role
     * @dev Can only have one refund
     * @param startTimestamp Timestamp when refund window will start
     * @param durationSeconds Refund window duration in seconds
     */
    function setRefundWindow(uint256 startTimestamp, uint256 durationSeconds) external returns (bool isSet);

    /**
     * @notice Get contract usage role definition
     * @return Returns contract usage role definition
     */
    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function CONTRACT_USAGE_ROLE() external view returns (bytes32); // solhint-disable-line func-name-mixedcase

    /**
     * @notice Get interface ID for IVestingCustomRefundProject interface
     * @return Returns interface ID for IVestingCustomRefundProject interface
     */
    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function INTERFACE_ID() external view returns (bytes4); // solhint-disable-line func-name-mixedcase

    /**
     * @notice Get token amount that is refundable for `account`
     * @param account The address to check
     * @return refundableAmount The token amount in wei that is refundedable for `account`
     */
    function refundableAmountFor(address account) external view returns (uint256 refundableAmount);

    /**
     * @notice Checks whether this contract implements the interface defined by `interfaceId`
     * @dev ERC165
     * @return `true` if this contract implements the interface defined by `interfaceId`
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 23 of 25 : IVestingCustomRefundUser.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

import {IVestingCustomRefund} from "./IVestingCustomRefund.sol";

/**
 * @title IVestingCustomRefundUser
 * @author Tim Loh
 * @notice Interface for custom vesting with refund for user
 */
interface IVestingCustomRefundUser is IVestingCustomRefund {
    /**
     * @notice Emitted when payment received info has been removed
     * @param sender The address that removed the payment received info
     * @param paymentVestingAddress Address of payment token vesting contract
     * @param rate Number of weis one token costs in payment token
     */
    event PaymentReceivedInfoRemoved(address indexed sender, address paymentVestingAddress, uint256 rate);

    /**
     * @notice Emitted when payment received info has been set
     * @param sender The address that set the payment received info
     * @param paymentVestingAddress Address of payment token vesting contract
     * @param rate Number of weis one token costs in payment token
     */
    event PaymentReceivedInfoSet(address indexed sender, address paymentVestingAddress, uint256 rate);

    /**
     * @notice Emitted when tokens have been refunded for `account`
     * @param account The address that received the refund
     * @param refundTokenAmount The token amount in wei to be refunded for `account`
     * @param refundPaymentAmount The payment amount in wei to be transferred to `account`
     */
    event TokensRefunded(address indexed account, uint256 refundTokenAmount, uint256 refundPaymentAmount);

    /**
     * @notice Cancel refund window
     * @dev Must be called by backoffice contract admin role
     * @dev Can only cancel when refund window has not started yet
     * @dev Will cancel refund window on corresponding payment token vesting contract
     */
    function cancelRefundWindow() external;

    /**
     * @notice Extend refund window
     * @dev Must be called by backoffice contract admin role
     * @dev Can only extend when refund window is open
     * @dev Will extend refund window on corresponding payment token vesting contract
     * @dev Refund window must end before start of corresponding payment token vesting schedule
     * @param newDurationSeconds New refund window duration in seconds
     */
    function extendRefundWindow(uint256 newDurationSeconds) external;

    /**
     * @notice Refund refundable amount of tokens to sender
     * @dev Can only refund if vesting schedule is defined
     * @dev Can only refund when refund window is open
     * @dev Cannot refund if have previously refunded
     * @dev Cannot refund if have previously claimed
     * @dev Cannot refund if grant has been revoked
     * @dev Will refund payment token to sender from corresponding payment token vesting contract
     */
    function refund() external;

    /**
     * @notice Remove payment received info
     * @dev Must be called by backoffice contract admin role
     * @dev Cannot remove if refund window already started
     * @dev Will cancel refund window on corresponding payment token vesting contract if refund window is set in this
     *      contract
     */
    function removePaymentReceivedInfo() external;

    /**
     * @notice Set payment received info
     * @dev Must be called by backoffice contract admin role
     * @dev Cannot set if refund window already started
     * @dev Will set refund window on payment token vesting contract to be same as this vesting contract
     * @param paymentVestingAddress The address of custom vesting contract containing payment tokens received
     * @param rate How many weis one token costs in payment token
     */
    function setPaymentReceivedInfo(address paymentVestingAddress, uint256 rate) external;

    /**
     * @notice Set refund window
     * @dev Must be called by backoffice contract admin role
     * @dev Requires vesting schedule to be set
     * @dev Can only have one refund
     * @dev Will set refund window on corresponding payment token vesting contract
     * @dev Refund window must start at or after project token vesting schedule start
     * @dev Refund window must end before start of corresponding payment token vesting schedule
     * @param startTimestamp Timestamp when refund window will start
     * @param durationSeconds Refund window duration in seconds
     */
    function setRefundWindow(uint256 startTimestamp, uint256 durationSeconds) external;

    /**
     * @notice Get payment received info
     * @return paymentVestingAddress The address of custom vesting contract containing payment tokens received
     * @return rate How many weis one token costs in payment token
     */
    function getPaymentReceivedInfo() external view returns (address paymentVestingAddress, uint256 rate);

    /**
     * @notice Get token amount that is refundable for `account`
     * @param account The address to check
     * @return refundableAmount The token amount in wei that is refundedable for `account`
     */
    function refundableAmountFor(address account) external view returns (uint256 refundableAmount);
}

File 24 of 25 : UnitConverter.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

/**
 * @title UnitConverter
 * @author Tim Loh
 * @notice Converts given amount between Wei and number of decimal places
 */
library UnitConverter {
    uint256 public constant TOKEN_MAX_DECIMALS = 18;

    /**
     * @notice Scale down given amount in Wei to given number of decimal places
     * @param weiAmount Amount in Wei
     * @param decimals Number of decimal places
     * @return decimalsAmount Amount in Wei scaled down to given number of decimal places
     */
    // https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code
    // slither-disable-next-line dead-code
    function scaleWeiToDecimals(uint256 weiAmount, uint256 decimals) internal pure returns (uint256 decimalsAmount) {
        require(decimals <= TOKEN_MAX_DECIMALS, "UnitConverter: decimals");

        if (decimals < TOKEN_MAX_DECIMALS && weiAmount > 0) {
            uint256 decimalsDiff = TOKEN_MAX_DECIMALS - decimals;
            decimalsAmount = weiAmount / 10 ** decimalsDiff;
        } else {
            decimalsAmount = weiAmount;
        }
    }

    /**
     * @notice Scale up given amount in given number of decimal places to Wei
     * @param decimalsAmount Amount in number of decimal places
     * @param decimals Number of decimal places
     * @return weiAmount Amount in given number of decimal places scaled up to Wei
     */
    // https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code
    // slither-disable-next-line dead-code
    function scaleDecimalsToWei(uint256 decimalsAmount, uint256 decimals) internal pure returns (uint256 weiAmount) {
        require(decimals <= TOKEN_MAX_DECIMALS, "UnitConverter: decimals");

        if (decimals < TOKEN_MAX_DECIMALS && decimalsAmount > 0) {
            uint256 decimalsDiff = TOKEN_MAX_DECIMALS - decimals;
            weiAmount = decimalsAmount * 10 ** decimalsDiff;
        } else {
            weiAmount = decimalsAmount;
        }
    }
}

File 25 of 25 : VestingCustomRefund.sol
// SPDX-License-Identifier: Apache-2.0
// Copyright 2023 Enjinstarter
pragma solidity 0.8.19;

import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {UnitConverter} from "./libraries/UnitConverter.sol";
import {AdminPrivileges} from "./AdminPrivileges.sol";
import {AdminWallet} from "./AdminWallet.sol";
import {IFactoryImplementation} from "./interfaces/IFactoryImplementation.sol";
import {IVestingCustomRefund} from "./interfaces/IVestingCustomRefund.sol";

/**
 * @title VestingCustomRefund
 * @author Tim Loh
 * @notice Provides an implementation of custom vesting with refund interface
 */
contract VestingCustomRefund is Initializable, Pausable, AdminPrivileges, AdminWallet, IVestingCustomRefund {
    using SafeERC20 for IERC20;
    using UnitConverter for uint256;

    struct CustomVestingScheduleEntry {
        uint256 percentRelease; // Percentage of grant amount to be released for period
        uint256 startTimestamp; // Start timestamp of period
        uint256 durationDays; // Duration in days for period
        uint256 endTimestamp; // End timestamp of period
    }

    struct RefundWindow {
        uint256 startTimestamp; // Start timestamp of refund window
        uint256 durationSeconds; // Duration of refund window in seconds
        uint256 endTimestamp; // End timestamp of refund window
    }

    struct VestingGrant {
        uint256 grantAmount; // Total number of tokens granted in wei
        // `true` if vesting grant can be revoked (e.g. gift), // `false` if cannot be revoked (e.g. purchased)
        bool isRevocable;
        bool isRevoked; // `true` if vesting grant has been revoked
        bool isActive; // `true` if vesting grant is active
    }

    uint256 public constant BATCH_MAX_NUM = 100;
    uint256 public constant SCHEDULE_MAX_ENTRIES = 100;

    uint256 public constant PERCENT_100_WEI = 100 ether;
    uint256 public constant SECONDS_IN_DAY = 86400;
    uint256 public constant TOKEN_MAX_DECIMALS = 18;

    bool public allowAccumulate;
    uint256 public numVestingScheduleEntries;
    address public tokenAddress;
    uint256 public tokenDecimals;
    uint256 public totalGrantAmount;
    uint256 public totalRefundAmount;
    uint256 public totalReleasedAmount;
    uint256 public totalRevokedAmount;

    RefundWindow private _refundWindow;

    mapping(address => uint256) private _refunded;
    mapping(address => uint256) private _released;
    mapping(address => VestingGrant) private _vestingGrants;
    mapping(uint256 => CustomVestingScheduleEntry) private _vestingSchedule;

    constructor() {
        _disableInitializers();
    }

    /**
     * @param tokenAddress_ The address of vesting token
     * @param tokenDecimals_ The number of decimals for vesting token
     * @param allowAccumulate_ `true` if multiple grant amounts is allowed to accumulate for the same user,
     *                         `false` if a user can only have one grant
     * @param backofficeAdminAddress The address that will be assigned the backoffice role admin role and backoffice
     *                               contract admin role
     * @param tenantAdminAddress The address that will be assigned the tenant role admin role, tenant governance role
     *                           and tenant contract admin role
     */
    function initialize(
        address tokenAddress_,
        uint256 tokenDecimals_,
        bool allowAccumulate_,
        address backofficeAdminAddress,
        address tenantAdminAddress
    ) public virtual initializer {
        __VestingCustomRefund_init(
            tokenAddress_,
            tokenDecimals_,
            allowAccumulate_,
            backofficeAdminAddress,
            tenantAdminAddress
        );
    }

    // https://github.com/crytic/slither/wiki/Detector-Documentation#dead-code
    // slither-disable-start dead-code

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function __VestingCustomRefund_init(
        // solhint-disable-previous-line func-name-mixedcase
        address tokenAddress_,
        uint256 tokenDecimals_,
        bool allowAccumulate_,
        address backofficeAdminAddress,
        address tenantAdminAddress
    ) internal onlyInitializing {
        __VestingCustomRefund_init_unchained(
            tokenAddress_,
            tokenDecimals_,
            allowAccumulate_,
            backofficeAdminAddress,
            tenantAdminAddress
        );
    }

    // slither-disable-end dead-code

    // https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
    // slither-disable-next-line naming-convention
    function __VestingCustomRefund_init_unchained(
        // solhint-disable-previous-line func-name-mixedcase
        address tokenAddress_,
        uint256 tokenDecimals_,
        bool allowAccumulate_,
        address backofficeAdminAddress,
        address tenantAdminAddress
    ) internal onlyInitializing {
        require(tokenAddress_ != address(0), "VCR: token address");
        require(tokenDecimals_ <= TOKEN_MAX_DECIMALS, "VCR: token decimals");
        require(backofficeAdminAddress != address(0), "VCR: backoffice admin");
        require(tenantAdminAddress != address(0), "VCR: tenant admin");

        _setRoleAdmin(BACKOFFICE_ROLE_ADMIN_ROLE, BACKOFFICE_ROLE_ADMIN_ROLE);
        _setRoleAdmin(BACKOFFICE_CONTRACT_ADMIN_ROLE, BACKOFFICE_ROLE_ADMIN_ROLE);
        _setRoleAdmin(TENANT_ROLE_ADMIN_ROLE, TENANT_ROLE_ADMIN_ROLE);
        _setRoleAdmin(TENANT_GOVERNANCE_ROLE, TENANT_ROLE_ADMIN_ROLE);
        _setRoleAdmin(TENANT_CONTRACT_ADMIN_ROLE, TENANT_ROLE_ADMIN_ROLE);

        _grantRole(BACKOFFICE_ROLE_ADMIN_ROLE, backofficeAdminAddress);
        _grantRole(BACKOFFICE_CONTRACT_ADMIN_ROLE, backofficeAdminAddress);

        _grantRole(TENANT_ROLE_ADMIN_ROLE, tenantAdminAddress);
        _grantRole(TENANT_GOVERNANCE_ROLE, tenantAdminAddress);
        _grantRole(TENANT_CONTRACT_ADMIN_ROLE, tenantAdminAddress);

        _setAdminWallet(tenantAdminAddress);

        tokenAddress = tokenAddress_;
        tokenDecimals = tokenDecimals_;

        allowAccumulate = allowAccumulate_;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function addVestingGrant(
        // solhint-disable-previous-line ordering
        address account,
        uint256 grantAmount,
        bool isRevocable
    ) external virtual override onlyRole(TENANT_CONTRACT_ADMIN_ROLE) {
        _addVestingGrant(account, grantAmount, isRevocable);
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function addVestingGrantsBatch(
        address[] memory accounts,
        uint256[] memory grantAmounts,
        bool[] memory isRevocables
    ) external virtual override onlyRole(TENANT_CONTRACT_ADMIN_ROLE) {
        require(accounts.length > 0, "VCR: empty");
        require(accounts.length <= BATCH_MAX_NUM, "VCR: exceed max");
        require(grantAmounts.length == accounts.length, "VCR: grant amounts length");
        require(isRevocables.length == accounts.length, "VCR: is revocables length");

        for (uint256 i = 0; i < accounts.length; i++) {
            _addVestingGrant(accounts[i], grantAmounts[i], isRevocables[i]);
        }
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function pauseContract() external virtual override onlyRole(TENANT_CONTRACT_ADMIN_ROLE) {
        _pause();
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function release() external virtual override whenNotPaused {
        uint256 releasableAmount = releasableAmountFor(msg.sender);

        _release(msg.sender, releasableAmount);
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function revokeVestingGrant(address account) external virtual override onlyRole(TENANT_CONTRACT_ADMIN_ROLE) {
        _revokeVestingGrant(account);
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function revokeVestingGrantsBatch(
        address[] memory accounts
    ) external virtual override onlyRole(TENANT_CONTRACT_ADMIN_ROLE) {
        require(accounts.length > 0, "VCR: empty");
        require(accounts.length <= BATCH_MAX_NUM, "VCR: exceed max");

        for (uint256 i = 0; i < accounts.length; i++) {
            _revokeVestingGrant(accounts[i]);
        }
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function setAdminWallet(address newWallet) external virtual override onlyRole(TENANT_GOVERNANCE_ROLE) {
        _setAdminWallet(newWallet);
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function setVestingSchedule(
        uint256[] calldata startTimestamps,
        uint256[] calldata percentReleases,
        uint256[] calldata durationsDays
    ) external virtual override onlyRole(TENANT_CONTRACT_ADMIN_ROLE) {
        require(startTimestamps.length > 0, "VCR: empty");
        require(startTimestamps.length <= SCHEDULE_MAX_ENTRIES, "VCR: exceed max");
        require(percentReleases.length == startTimestamps.length, "VCR: percent length different");
        require(durationsDays.length == startTimestamps.length, "VCR: duration length different");
        require(!hasVestingScheduleStarted(block.timestamp), "VCR: already started");

        uint256 minTimestamp = block.timestamp;
        uint256 totalPercentRelease = 0;

        for (uint256 i = 0; i < startTimestamps.length; i++) {
            require(percentReleases[i] > 0, "VCR: zero percent");
            require(startTimestamps[i] >= minTimestamp, "VCR: invalid start timestamp");

            totalPercentRelease = totalPercentRelease + percentReleases[i];
            require(totalPercentRelease <= PERCENT_100_WEI, "VCR: exceed 100%");

            if (durationsDays[i] > 0) {
                minTimestamp = startTimestamps[i] + durationsDays[i] * SECONDS_IN_DAY;
            } else {
                minTimestamp = startTimestamps[i];
            }

            _vestingSchedule[i] = CustomVestingScheduleEntry({
                percentRelease: percentReleases[i],
                startTimestamp: startTimestamps[i],
                durationDays: durationsDays[i],
                endTimestamp: minTimestamp
            });
        }

        require(totalPercentRelease == PERCENT_100_WEI, "VCR: not 100%");

        numVestingScheduleEntries = startTimestamps.length;

        emit ScheduleSet(msg.sender, startTimestamps, percentReleases, durationsDays);
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function transferUnusedTokens() external virtual override onlyRole(TENANT_CONTRACT_ADMIN_ROLE) {
        uint256 balanceInDecimals = IERC20(tokenAddress).balanceOf(address(this));
        uint256 balanceInWei = balanceInDecimals.scaleDecimalsToWei(tokenDecimals);

        uint256 unusedAmount = balanceInWei +
            totalReleasedAmount +
            totalRevokedAmount +
            totalRefundAmount -
            totalGrantAmount;
        require(unusedAmount > 0, "VCR: nothing to transfer");

        uint256 transferAmount = unusedAmount.scaleWeiToDecimals(tokenDecimals);

        emit UnusedTokensTransferred(
            msg.sender,
            unusedAmount,
            balanceInWei,
            totalReleasedAmount,
            totalRevokedAmount,
            totalRefundAmount,
            totalGrantAmount
        );

        IERC20(tokenAddress).safeTransfer(adminWallet(), transferAmount);
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function unpauseContract() external virtual override onlyRole(TENANT_CONTRACT_ADMIN_ROLE) {
        _unpause();
    }

    /**
     * @inheritdoc IFactoryImplementation
     */
    function factoryImplementationType() external view virtual override returns (uint256 implementationType) {
        implementationType = 0x447e1a635045d08b78677dfba2a78564b566f402520e983a9ae65e8115b13d5b;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function getVestingSchedule()
        external
        view
        virtual
        override
        returns (
            uint256[] memory startTimestamps,
            uint256[] memory percentReleases,
            uint256[] memory durationsDays,
            uint256[] memory endTimestamps
        )
    {
        startTimestamps = new uint256[](numVestingScheduleEntries);
        percentReleases = new uint256[](numVestingScheduleEntries);
        durationsDays = new uint256[](numVestingScheduleEntries);
        endTimestamps = new uint256[](numVestingScheduleEntries);

        if (numVestingScheduleEntries > 0) {
            for (uint256 i = 0; i < numVestingScheduleEntries; i++) {
                startTimestamps[i] = _vestingSchedule[i].startTimestamp;
                percentReleases[i] = _vestingSchedule[i].percentRelease;
                durationsDays[i] = _vestingSchedule[i].durationDays;
                endTimestamps[i] = _vestingSchedule[i].endTimestamp;
            }
        }
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function unvestedAmountFor(address account) external view virtual override returns (uint256 unvestedAmount) {
        require(account != address(0), "VCR: zero account");

        if (revoked(account)) {
            unvestedAmount = 0;
            return unvestedAmount;
        }

        uint256 grantAmountWei = effectiveGrantAmountFor(account);
        uint256 vestedAmountWei = vestedAmountFor(account);

        unvestedAmount = grantAmountWei - vestedAmountWei;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function effectiveGrantAmountFor(address account) public view virtual override returns (uint256 grantAmountWei) {
        require(account != address(0), "VCR: zero account");

        VestingGrant memory vestingGrant = _vestingGrants[account];
        require(vestingGrant.isActive, "VCR: inactive");

        uint256 refundedAmount = refundedAmountFor(account);

        grantAmountWei = vestingGrant.grantAmount - refundedAmount;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function getRefundWindow()
        public
        view
        virtual
        override
        returns (uint256 startTimestamp, uint256 durationSeconds, uint256 endTimestamp)
    {
        startTimestamp = _refundWindow.startTimestamp;
        durationSeconds = _refundWindow.durationSeconds;
        endTimestamp = _refundWindow.endTimestamp;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function hasRefundedFor(address account) public view virtual override returns (bool hasRefunded) {
        require(account != address(0), "VCR: zero account");
        require(_vestingGrants[account].isActive, "VCR: inactive");

        hasRefunded = refundedAmountFor(account) > 0;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function hasReleasedFor(address account) public view virtual override returns (bool hasReleased) {
        require(account != address(0), "VCR: zero account");
        require(_vestingGrants[account].isActive, "VCR: inactive");

        hasReleased = releasedAmountFor(account) > 0;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function hasRefundWindowStarted(uint256 atTimestamp) public view virtual override returns (bool hasStarted) {
        require(atTimestamp > 0, "VCR: timestamp");

        hasStarted = _refundWindow.startTimestamp > 0 && atTimestamp >= _refundWindow.startTimestamp;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function hasVestingScheduleStarted(uint256 atTimestamp) public view virtual override returns (bool hasStarted) {
        require(atTimestamp > 0, "VCR: timestamp");

        hasStarted = numVestingScheduleEntries > 0 && atTimestamp >= _vestingSchedule[0].startTimestamp;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function isRefundWindowDefined() public view virtual override returns (bool isDefined) {
        isDefined = _refundWindow.startTimestamp > 0;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function isRefundWindowOpenNow() public view virtual override returns (bool isOpen) {
        isOpen =
            _refundWindow.startTimestamp > 0 &&
            _refundWindow.endTimestamp > 0 &&
            block.timestamp >= _refundWindow.startTimestamp &&
            block.timestamp < _refundWindow.endTimestamp;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function isVestingScheduleDefined() public view virtual override returns (bool isDefined) {
        isDefined = numVestingScheduleEntries > 0;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function refundedAmountFor(address account) public view virtual override returns (uint256 refundedAmount) {
        require(account != address(0), "VCR: zero account");

        refundedAmount = _refunded[account];
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function releasableAmountFor(address account) public view virtual override returns (uint256 releasableAmount) {
        require(account != address(0), "VCR: zero account");
        require(hasVestingScheduleStarted(block.timestamp), "VCR: not started");
        require(!revoked(account), "VCR: revoked");

        releasableAmount = vestedAmountFor(account) - releasedAmountFor(account);
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function releasedAmountFor(address account) public view virtual override returns (uint256 releasedAmount) {
        require(account != address(0), "VCR: zero account");

        releasedAmount = _released[account];
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function revoked(address account) public view virtual override returns (bool isRevoked) {
        require(account != address(0), "VCR: zero account");

        VestingGrant memory vestingGrant = _vestingGrants[account];
        require(vestingGrant.isActive, "VCR: inactive");

        isRevoked = vestingGrant.isRevoked;
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function vestedAmountFor(address account) public view virtual override returns (uint256 vestedAmount) {
        require(account != address(0), "VCR: zero account");

        if (numVestingScheduleEntries == 0 || _vestingSchedule[0].startTimestamp == 0) {
            return 0;
        }

        if (block.timestamp < _vestingSchedule[0].startTimestamp) {
            return 0;
        }

        if (revoked(account)) {
            return releasedAmountFor(account);
        }

        uint256 grantAmountWei = effectiveGrantAmountFor(account);

        if (block.timestamp >= _vestingSchedule[numVestingScheduleEntries - 1].endTimestamp) {
            return grantAmountWei;
        }

        uint256 totalPercentRelease = _getTotalPercentRelease(block.timestamp);

        // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply
        // slither-disable-next-line divide-before-multiply
        uint256 totalReleaseAmount = (grantAmountWei * totalPercentRelease) / PERCENT_100_WEI;
        vestedAmount = totalReleaseAmount.scaleWeiToDecimals(tokenDecimals).scaleDecimalsToWei(tokenDecimals);
    }

    /**
     * @inheritdoc IVestingCustomRefund
     */
    function vestingGrantFor(
        address account
    ) public view virtual override returns (uint256 grantAmount, bool isRevocable, bool isRevoked, bool isActive) {
        require(account != address(0), "VCR: zero account");

        VestingGrant memory vestingGrant = _vestingGrants[account];
        grantAmount = vestingGrant.grantAmount;
        isRevocable = vestingGrant.isRevocable;
        isRevoked = vestingGrant.isRevoked;
        isActive = vestingGrant.isActive;
    }

    /**
     * @notice Add vesting grant for `account`
     * @dev grant can only be added before schedule start
     * @dev grant cannot be added if previous grant has been revoked
     * @dev isRevocable will be ignored if grant already added but amount allowed to accumulate
     * @param account The address that will have the vesting grant added
     * @param grantAmount The grant token amount in wei
     * @param isRevocable `true` if vesting grant is revocable
     *                    `false` if vesting grant is not revocable
     */
    function _addVestingGrant(address account, uint256 grantAmount, bool isRevocable) internal virtual {
        require(account != address(0), "VCR: zero account");
        require(grantAmount > 0, "VCR: zero grant amount");
        require(!hasVestingScheduleStarted(block.timestamp), "VCR: already started");

        VestingGrant memory vestingGrant = _vestingGrants[account];
        require(allowAccumulate || !vestingGrant.isActive, "VCR: already added");
        require(!vestingGrant.isActive || !revoked(account), "VCR: already revoked");

        uint256 truncatedGrantAmount = grantAmount.scaleWeiToDecimals(tokenDecimals).scaleDecimalsToWei(tokenDecimals);
        require(truncatedGrantAmount > 0, "VCR: zero decimals grant amount");

        // https://github.com/crytic/slither/wiki/Detector-Documentation#costly-operations-inside-a-loop
        // slither-disable-next-line costly-loop
        totalGrantAmount += truncatedGrantAmount;
        // https://github.com/crytic/slither/wiki/Detector-Documentation/#calls-inside-a-loop
        // slither-disable-next-line calls-loop
        uint256 balanceInDecimals = IERC20(tokenAddress).balanceOf(address(this));
        require(balanceInDecimals > 0, "VCR: zero balance");
        uint256 balanceInWei = balanceInDecimals.scaleDecimalsToWei(tokenDecimals);

        uint256 remainderAmount = balanceInWei +
            totalReleasedAmount +
            totalRevokedAmount +
            totalRefundAmount;
        require(remainderAmount >= totalGrantAmount, "VCR: total grant > remainder");

        if (vestingGrant.isActive) {
            _vestingGrants[account].grantAmount = vestingGrant.grantAmount + truncatedGrantAmount;
            // _vestingGrants[account].isRevocable = isRevocable;
        } else {
            _vestingGrants[account] = VestingGrant({
                grantAmount: truncatedGrantAmount,
                isRevocable: isRevocable,
                isRevoked: false,
                isActive: true
            });
        }

        emit VestingGrantAdded(account, truncatedGrantAmount, isRevocable);
    }

    /**
     * @notice Cancel refund window
     * @dev Can only cancel when refund window has not started yet
     */
    function _cancelRefundWindow() internal virtual {
        require(isRefundWindowDefined(), "VCR: no refund");
        require(!hasRefundWindowStarted(block.timestamp), "VCR: refund started");

        uint256 oldStartTimestamp = _refundWindow.startTimestamp;
        uint256 oldDurationSeconds = _refundWindow.durationSeconds;
        uint256 oldEndTimestamp = _refundWindow.endTimestamp;

        _refundWindow.startTimestamp = 0;
        _refundWindow.durationSeconds = 0;
        _refundWindow.endTimestamp = 0;

        emit RefundWindowCancelled(msg.sender, oldStartTimestamp, oldDurationSeconds, oldEndTimestamp);
    }

    /**
     * @notice Extend refund window
     * @dev Can only extend when refund window is open
     * @param newDurationSeconds New refund window duration in seconds
     */
    function _extendRefundWindow(uint256 newDurationSeconds) internal virtual {
        require(newDurationSeconds > 0, "VCR: new duration");
        require(isRefundWindowOpenNow(), "VCR: not open");

        uint256 oldEndTimestamp = _refundWindow.endTimestamp;
        uint256 newEndTimestamp = _refundWindow.startTimestamp + newDurationSeconds;
        require(newEndTimestamp > oldEndTimestamp, "VCR: too short");

        uint256 oldDurationSeconds = _refundWindow.durationSeconds;

        _refundWindow.durationSeconds = newDurationSeconds;
        _refundWindow.endTimestamp = newEndTimestamp;

        emit RefundWindowExtended(msg.sender, newDurationSeconds, newEndTimestamp, oldDurationSeconds, oldEndTimestamp);
    }

    /**
     * @notice Refund specified amount of tokens to `account`
     * @dev Can only refund when refund window is open
     * @dev Cannot refund if have previously refunded
     * @dev Cannot refund if have previously claimed
     * @param account The address to receive the refunded amount of tokens
     * @param amount The token amount in wei to be refunded to `account`
     */
    function _refund(address account, uint256 amount) internal virtual {
        require(account != address(0), "VCR: zero account");
        require(amount > 0, "VCR: zero amount");
        require(isRefundWindowOpenNow(), "VCR: not open");

        _refunded[account] += amount;
        totalRefundAmount += amount;
    }

    /**
     * @notice Release specified amount of tokens to `account`
     * @param account The address to receive the specified amount of tokens
     * @param amount The token amount in wei to be transferred to `account`
     */
    function _release(address account, uint256 amount) internal virtual {
        require(account != address(0), "VCR: zero account");
        require(amount > 0, "VCR: zero amount");

        uint256 transferDecimalsAmount = amount.scaleWeiToDecimals(tokenDecimals);
        uint256 transferWeiAmount = transferDecimalsAmount.scaleDecimalsToWei(tokenDecimals);

        _released[account] += transferWeiAmount;
        totalReleasedAmount += transferWeiAmount;

        emit TokensReleased(account, transferWeiAmount);

        IERC20(tokenAddress).safeTransfer(account, transferDecimalsAmount);
    }

    /**
     * @notice Revoke vesting grant for `account`
     * @dev Only revocable grants can be revoked
     * @param account The address that will have the vesting grant revoked
     */
    function _revokeVestingGrant(address account) internal virtual {
        require(account != address(0), "VCR: zero account");

        VestingGrant memory vestingGrant = _vestingGrants[account];
        require(vestingGrant.isActive, "VCR: inactive");
        require(vestingGrant.isRevocable, "VCR: not revocable");
        require(!revoked(account), "VCR: already revoked");

        uint256 refundedAmount = refundedAmountFor(account);
        uint256 releasedAmount = releasedAmountFor(account);
        uint256 remainderAmount = vestingGrant.grantAmount - refundedAmount - releasedAmount;
        // https://github.com/crytic/slither/wiki/Detector-Documentation#costly-operations-inside-a-loop
        // slither-disable-next-line costly-loop
        totalRevokedAmount += remainderAmount;
        _vestingGrants[account].isRevoked = true;

        emit VestingGrantRevoked(account, remainderAmount, vestingGrant.grantAmount, refundedAmount, releasedAmount);
    }

    /**
     * @notice Set refund window
     * @dev Can only have one refund
     * @param startTimestamp Timestamp when refund window will start
     * @param durationSeconds Refund window duration in seconds
     */
    function _setRefundWindow(uint256 startTimestamp, uint256 durationSeconds) internal virtual {
        require(startTimestamp > 0, "VCR: start timestamp");
        require(durationSeconds > 0, "VCR: duration");
        require(!hasRefundWindowStarted(block.timestamp), "VCR: refund started");

        uint256 endTimestamp = startTimestamp + durationSeconds;

        _refundWindow.startTimestamp = startTimestamp;
        _refundWindow.durationSeconds = durationSeconds;
        _refundWindow.endTimestamp = endTimestamp;

        emit RefundWindowSet(msg.sender, startTimestamp, durationSeconds, endTimestamp);
    }

    /**
     * @notice Get total percentage to be released at specified timestamp
     * @param atTimestamp Specified timestamp
     * @return totalPercentRelease The total percentage to be released at specified timestamp
     */
    function _getTotalPercentRelease(uint256 atTimestamp) internal view virtual returns (uint256 totalPercentRelease) {
        totalPercentRelease = 0;

        for (uint256 i = 0; i < numVestingScheduleEntries; i++) {
            if (atTimestamp < _vestingSchedule[i].startTimestamp) {
                break;
            }

            if (atTimestamp >= _vestingSchedule[i].endTimestamp) {
                totalPercentRelease += _vestingSchedule[i].percentRelease;
            } else {
                uint256 durationSeconds = _vestingSchedule[i].durationDays * SECONDS_IN_DAY;
                uint256 percentRelease = (atTimestamp - _vestingSchedule[i].startTimestamp) *
                    _vestingSchedule[i].percentRelease;

                // https://github.com/crytic/slither/wiki/Detector-Documentation#divide-before-multiply
                // slither-disable-next-line divide-before-multiply
                totalPercentRelease = (totalPercentRelease * durationSeconds + percentRelease) / durationSeconds;
                break;
            }
        }
    }

    /**
     * @notice Get token amount that is refundable for `account`
     * @param account The address to check
     * @return refundableAmount The token amount in wei that is refundedable for `account`
     */
    function _refundableAmountFor(address account) internal view virtual returns (uint256 refundableAmount) {
        require(account != address(0), "VCR: zero account");
        require(isVestingScheduleDefined(), "VCR: undefined schedule");
        require(!revoked(account), "VCR: revoked");

        VestingGrant memory vestingGrant = _vestingGrants[account];
        // require(vestingGrant.isActive, "VCR: inactive"); // already checked in revoked()

        refundableAmount = hasRefundedFor(account) || releasedAmountFor(account) > 0 ? 0 : vestingGrant.grantAmount;
    }
}

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

Contract ABI

[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldWallet","type":"address"},{"indexed":true,"internalType":"address","name":"newWallet","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"AdminWalletChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"paymentVestingAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"rate","type":"uint256"}],"name":"PaymentReceivedInfoRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"paymentVestingAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"rate","type":"uint256"}],"name":"PaymentReceivedInfoSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"refundStartTimestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"refundDurationSeconds","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"refundEndTimestamp","type":"uint256"}],"name":"RefundWindowCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"newDurationSeconds","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newEndTimestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"oldDurationSeconds","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"oldEndTimestamp","type":"uint256"}],"name":"RefundWindowExtended","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"durationSeconds","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"endTimestamp","type":"uint256"}],"name":"RefundWindowSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"startTimestamps","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"percentReleases","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"durationsDays","type":"uint256[]"}],"name":"ScheduleSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"refundTokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"refundPaymentAmount","type":"uint256"}],"name":"TokensRefunded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TokensReleased","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"unusedAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"balanceInWei","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalReleasedAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalRevokedAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalRefundAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"totalGrantAmount","type":"uint256"}],"name":"UnusedTokensTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"grantAmount","type":"uint256"},{"indexed":false,"internalType":"bool","name":"isRevocable","type":"bool"}],"name":"VestingGrantAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"remainderAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"grantAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"refundedAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"releasedAmount","type":"uint256"}],"name":"VestingGrantRevoked","type":"event"},{"inputs":[],"name":"BACKOFFICE_CONTRACT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BACKOFFICE_GOVERNANCE_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BACKOFFICE_ROLE_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BATCH_MAX_NUM","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERCENT_100_WEI","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SCHEDULE_MAX_ENTRIES","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SECONDS_IN_DAY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TENANT_CONTRACT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TENANT_GOVERNANCE_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TENANT_ROLE_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TOKEN_MAX_DECIMALS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TOKEN_RATE_SCALE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"grantAmount","type":"uint256"},{"internalType":"bool","name":"isRevocable","type":"bool"}],"name":"addVestingGrant","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"accounts","type":"address[]"},{"internalType":"uint256[]","name":"grantAmounts","type":"uint256[]"},{"internalType":"bool[]","name":"isRevocables","type":"bool[]"}],"name":"addVestingGrantsBatch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"adminWallet","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"allowAccumulate","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"cancelRefundWindow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"effectiveGrantAmountFor","outputs":[{"internalType":"uint256","name":"grantAmountWei","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"newDurationSeconds","type":"uint256"}],"name":"extendRefundWindow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"factoryImplementationType","outputs":[{"internalType":"uint256","name":"implementationType","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPaymentReceivedInfo","outputs":[{"internalType":"address","name":"paymentVestingAddress","type":"address"},{"internalType":"uint256","name":"rate","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRefundWindow","outputs":[{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"durationSeconds","type":"uint256"},{"internalType":"uint256","name":"endTimestamp","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getVestingSchedule","outputs":[{"internalType":"uint256[]","name":"startTimestamps","type":"uint256[]"},{"internalType":"uint256[]","name":"percentReleases","type":"uint256[]"},{"internalType":"uint256[]","name":"durationsDays","type":"uint256[]"},{"internalType":"uint256[]","name":"endTimestamps","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"atTimestamp","type":"uint256"}],"name":"hasRefundWindowStarted","outputs":[{"internalType":"bool","name":"hasStarted","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"hasRefundedFor","outputs":[{"internalType":"bool","name":"hasRefunded","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"hasReleasedFor","outputs":[{"internalType":"bool","name":"hasReleased","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"atTimestamp","type":"uint256"}],"name":"hasVestingScheduleStarted","outputs":[{"internalType":"bool","name":"hasStarted","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress_","type":"address"},{"internalType":"uint256","name":"tokenDecimals_","type":"uint256"},{"internalType":"bool","name":"allowAccumulate_","type":"bool"},{"internalType":"address","name":"backofficeAdminAddress","type":"address"},{"internalType":"address","name":"tenantAdminAddress","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isRefundWindowDefined","outputs":[{"internalType":"bool","name":"isDefined","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isRefundWindowOpenNow","outputs":[{"internalType":"bool","name":"isOpen","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isVestingScheduleDefined","outputs":[{"internalType":"bool","name":"isDefined","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"numVestingScheduleEntries","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pauseContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"refund","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"refundableAmountFor","outputs":[{"internalType":"uint256","name":"refundableAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"refundedAmountFor","outputs":[{"internalType":"uint256","name":"refundedAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"releasableAmountFor","outputs":[{"internalType":"uint256","name":"releasableAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"release","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"releasedAmountFor","outputs":[{"internalType":"uint256","name":"releasedAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"removePaymentReceivedInfo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"revokeVestingGrant","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"accounts","type":"address[]"}],"name":"revokeVestingGrantsBatch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"revoked","outputs":[{"internalType":"bool","name":"isRevoked","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newWallet","type":"address"}],"name":"setAdminWallet","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"paymentVestingAddress","type":"address"},{"internalType":"uint256","name":"rate","type":"uint256"}],"name":"setPaymentReceivedInfo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"durationSeconds","type":"uint256"}],"name":"setRefundWindow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"startTimestamps","type":"uint256[]"},{"internalType":"uint256[]","name":"percentReleases","type":"uint256[]"},{"internalType":"uint256[]","name":"durationsDays","type":"uint256[]"}],"name":"setVestingSchedule","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokenAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tokenDecimals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalGrantAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalRefundAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalReleasedAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalRevokedAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"transferUnusedTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpauseContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"unvestedAmountFor","outputs":[{"internalType":"uint256","name":"unvestedAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"vestedAmountFor","outputs":[{"internalType":"uint256","name":"vestedAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"vestingGrantFor","outputs":[{"internalType":"uint256","name":"grantAmount","type":"uint256"},{"internalType":"bool","name":"isRevocable","type":"bool"},{"internalType":"bool","name":"isRevoked","type":"bool"},{"internalType":"bool","name":"isActive","type":"bool"}],"stateMutability":"view","type":"function"}]

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ 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.