Skip to content
Verified contractExactUnlicense

HSKImplementationV1

Address0x557683a5fa469d00516dee63fbf345c450cf647a
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.9

 

Same code

1 more contract

 

Details

Compiler
solc 0.8.9+commit.e5eed63a
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
london
License
Unlicense
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
20,197,285
Creation transaction
0x82cff35a20…92690313ca

contracts/HSK.sol

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "./ERC20Permit.sol";
import "./BurnPermit.sol";

/// @title HashKey Platform Token Contract
contract HSKImplementationV1 is BurnPermit, ERC20Permit {
    receive() external payable {
        revert("Contract is not payable");
    }
}

@openzeppelin/contracts/access/Ownable.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/interfaces/IERC1271.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)

pragma solidity ^0.8.0;

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

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@openzeppelin/contracts/utils/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));
    }
}

@openzeppelin/contracts/utils/cryptography/ECDSA.sol

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

pragma solidity ^0.8.0;

import "../Strings.sol";

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

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

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

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

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

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

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

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

        return (signer, RecoverError.NoError);
    }

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

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

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

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

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

@openzeppelin/contracts/utils/math/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);
        }
    }
}

@openzeppelin/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/math/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);
        }
    }
}

contracts/Access.sol

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/Ownable.sol";

/// @title Implement access control of Hashkey.
abstract contract Access is Ownable {
    mapping(bytes32 => mapping(address => bool)) private _roleMembers;

    event SetupRole(bytes32 role, bool enable, address indexed account);

    modifier accessible(bytes32 role) {
        require(
            owner() == msg.sender || hasRole(role, msg.sender),
            "Access: caller has no access"
        );
        _;
    }

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

    /// @dev
    function setupRole(bytes32 role, bool enable, address account) external onlyOwner {
        require(account != address(0), "Access: account is zero address");
        _roleMembers[role][account] = enable;
        
        emit SetupRole(role, enable, account);
    }
}

contracts/BlackList.sol

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "./Access.sol";

abstract contract BlackList is Access {

    bytes32 public constant BLACKLIST_ROLE = keccak256("Blacklist Role");

    mapping(address => bool) private _blacklist;

    event SetupBlackList(address indexed account, bool blacklisted);

    modifier notInBlackList(address account) {
        require(!inBlackList(account), "Blacklist: in blacklist");
        _;
    }
    
    /// @dev Return if the account is in blacklist.
    function inBlackList(address account) public view returns (bool) {
        return _blacklist[account];
    }
    
    /// @dev Add the account in the blacklist, or remove the account from the blacklist.
    function setBlackList(address account, bool blacklisted) external accessible(BLACKLIST_ROLE) {
        require(account != address(0), "Blacklist: zero address");
        _blacklist[account] = blacklisted;
        emit SetupBlackList(account, blacklisted);
    }
}

contracts/BurnPermit.sol

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ERC20.sol";
import "./library/CheckSig.sol";

abstract contract BurnPermit is ERC20 {
    using CheckSig for address;

    mapping(address => uint256) private _burnNonces;

    bytes32 private constant BURN_TYPEHASH = keccak256("HSK V1 Burn");

    bytes32 private constant BURN_FROM_TYPEHASH = keccak256("HSK V1 Burn From");

    bytes32 public constant BURN_ROLE = keccak256("Burn Role");

    /// @dev Return account's available nonce.
    function burnNonce(address account) public view returns (uint256) {
        return _burnNonces[account];
    }

    /// @dev Hash of the burn request message.
    function burnMessageHash(
        address applicant,
        uint256 amount,
        uint256 nonce,
        uint256 deadline
    ) public view returns (bytes32) {
        return keccak256(
            abi.encode(
                BURN_TYPEHASH,
                block.chainid,
                address(this),
                applicant,
                amount,
                nonce,
                deadline
            )
        );
    }

    /// @dev Hash of the burn from request message.
    function burnFromMessageHash(
        address applicant,
        address from,
        uint256 amount,
        uint256 nonce,
        uint256 deadline
    ) public view returns (bytes32) {
        return keccak256(
            abi.encode(
                BURN_FROM_TYPEHASH,
                block.chainid,
                address(this),
                applicant,
                from,
                amount,
                nonce,
                deadline
            )
        );
    }

    /// @dev Burn {amount} tokens of {applicant} by the owner, ensure {sig} is signed from {applicant}.
    function burn(address applicant, uint256 amount, uint256 deadline, bytes memory sig)
        external
        accessible(BURN_ROLE)
        notInBlackList(applicant)
    {
        // solhint-disable-next-line not-rely-on-time
        require(block.timestamp <= deadline, "BurnPermit: expired deadline");

        bytes32 message = burnMessageHash(applicant, amount, burnNonce(applicant), deadline);
        bytes32 digest = ECDSA.toEthSignedMessageHash(message);
        _burnNonces[applicant]++;

        applicant.checkSignature(digest, sig);

        _burn(applicant, amount);
    }

    /// @dev Burn {amount} tokens of {applicant} from {from} by the owner, ensure {sig} is signed from {applicant}.
    function burnFrom(
        address applicant,
        address from,
        uint256 amount,
        uint256 deadline,
        bytes memory sig
    )
        external
        accessible(BURN_ROLE)
        notInBlackList(applicant)
        notInBlackList(from)
    {
        // solhint-disable-next-line not-rely-on-time
        require(block.timestamp <= deadline, "BurnPermit: expired deadline");

        bytes32 message = burnFromMessageHash(applicant, from, amount, burnNonce(applicant), deadline);
        bytes32 digest = ECDSA.toEthSignedMessageHash(message);
        _burnNonces[applicant]++;

        applicant.checkSignature(digest, sig);

        _burnFrom(applicant, from, amount);
    }
}

contracts/ERC20.sol

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
pragma abicoder v2;

import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./interface/IERC20.sol";
import "./library/Vesting.sol";
import "./library/Mint.sol";
import "./BlackList.sol";

/// @title Implement ERC20 token of HashKey Platform Token.
abstract contract ERC20 is BlackList, IERC20 {
    using SafeCast for uint256;
    using Vesting for Vesting.Cliff;
    using Vesting for Vesting.Linear;

    /// @dev describe the account state of user, user's fund is consist of 3 parts
    struct AccountState {
        Vesting.Cliff[]         cliffVesting;
        Vesting.Linear[]        linearVesting;
        uint256                 available;
    }

    /// @dev describe the current cliff vesting schedule of user
    struct CliffVesting {
        Mint.Bucket             bucket;
        uint64                  expiration;
        uint256                 amount;
    }

    /// @dev describe the current linear vesting schedule of user
    struct LinearVesting {
        Mint.Bucket             bucket;
        uint64                  interval;
        uint64                  expiration;
        uint256                 amount;
    }

    string  private constant NAME            = "HashKey Platform Token";
    string  private constant SYMBOL          = "HSK";
    uint8   private constant DECIMALS        = 18;

    bytes32 public  constant ECO_GROWTH_ROLE = keccak256("Ecosystem Growth Role");
    bytes32 public  constant TEAM_ROLE       = keccak256("Team Role");
    bytes32 public  constant RESERVE_ROLE    = keccak256("Reserve Role");

    // It will cost less than 10,000 GAS to compute and refresh vesting state in
    // each loop step of `_updateAccountState()`.
    // Hereby we restrict a max schdules limit of 2000, which means it will
    // never exceed 20,000,000 GAS, abount 2/3 of a block gas limit (30,000,000).
    uint256 private constant MAX_SCHEDULES   = 2000;

    // set to true to prevent calling `init()` in implementation contract.
    bool    private _initialized             = true;
    uint256 private _ecoGrowthShare          = 650000000  * 10 ** DECIMALS;
    uint256 private _teamShare               = 300000000  * 10 ** DECIMALS;
    uint256 private _reserveShare            = 50000000   * 10 ** DECIMALS;
    uint256 private _totalSupply             = _ecoGrowthShare + _teamShare + _reserveShare;

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

    event MintType1(
        Mint.Bucket indexed bucket,
        address indexed recipient,
        uint256 amount
    );
    event MintType2(
        Mint.Bucket indexed bucket,
        address indexed recipient,
        uint256 expiration,
        uint256 amount
    );
    event MintType3(
        Mint.Bucket indexed bucket,
        address indexed recipient,
        uint256 start,
        uint256 end,
        uint256 interval,
        uint256 amount
    );

    event ShrinkShare(Mint.Bucket indexed bucket, uint256 amount);
    event RecallTeamVesting(address indexed account, uint256 amount);
    event Burn(address indexed applicant, uint256 amount);
    event BurnFrom(address indexed applicant, address indexed from, uint256 amount);

    constructor() {
        // set owner to zero address.
        renounceOwnership();
    }

    /// @dev initialize token parameters.
    /// @notice this function is designed to be called by proxy contract.
    function init(address _owner) external {
        // not initialized in proxy
        require(!_initialized, "ERC20: Already initialized");

        _initialized        = true;
        _ecoGrowthShare     = 650000000  * 10 ** DECIMALS;
        _teamShare          = 300000000  * 10 ** DECIMALS;
        _reserveShare       = 50000000   * 10 ** DECIMALS;
        _totalSupply        = _ecoGrowthShare + _teamShare + _reserveShare;

        _transferOwnership(_owner);
    }

    ///////////////////////////// ERC20 methods /////////////////////////////

    /// @dev see in IERC20
    function name() public pure override returns (string memory) {
        return NAME;
    }

    /// @dev see in IERC20.
    function symbol() public pure override returns (string memory) {
        return SYMBOL;
    }

    /// @dev see in IERC20.
    function decimals() public pure override returns (uint8) {
        return DECIMALS;
    }

    /// @dev see in IERC20.
    function totalSupply() public view override returns (uint256) {
        return _totalSupply;
    }

    /// @dev see in IERC20.
    /// @notice balance is consist of 4 parts: available part and 3 vesting parts.
    function balanceOf(address _owner) public view override returns (uint256) {
        AccountState storage state = accounts[_owner];
        uint256 balance = state.available;

        uint256 length = state.cliffVesting.length;
        for (uint256 i = 0; i < length;) {
            Vesting.Cliff storage vesting = state.cliffVesting[i];
            if (vesting.active) {
                // solhint-disable-next-line not-rely-on-time
                (, uint256 released) = vesting.getCliff(block.timestamp);
                unchecked { balance += released; }
            }
            unchecked { i++; }
        }

        length = state.linearVesting.length;
        for (uint256 i = 0; i < length;) {
            Vesting.Linear storage vesting = state.linearVesting[i];
            if (vesting.active) {
                // solhint-disable-next-line not-rely-on-time
                (, uint256 released) = vesting.getLinear(block.timestamp);
                unchecked { balance += released; }
            }
            unchecked { i++; }
        }

        return balance;
    }

    /// @dev see in IERC20.
    function allowance(address _owner, address spender) public view override returns (uint256) {
        return _allowances[_owner][spender];
    }

    /// @dev see in IERC20.
    function transfer(address to, uint256 amount)
        public
        override
        notInBlackList(msg.sender)
        notInBlackList(to)
        returns (bool)
    {
        _transfer(msg.sender, to, amount);
        return true;
    }

    /// @dev see in IERC20.
    function approve(address spender, uint256 amount)
        public
        override
        notInBlackList(msg.sender)
        notInBlackList(spender)
        returns (bool)
    {
        _approve(msg.sender, spender, amount);
        return true;
    }

    /// @dev see in IERC20.
    /// @notice if _allowance is max of uint256, it means allowance is not limited.
    function transferFrom(address from, address to, uint256 amount)
        public
        override
        notInBlackList(msg.sender)
        notInBlackList(from)
        notInBlackList(to)
        returns (bool)
    {
        uint256 _allowance = allowance(from, msg.sender);
        if (_allowance != type(uint256).max) {
            require(amount <= _allowance, "ERC20: Insufficient allowance");
            _allowances[from][msg.sender] = _allowance - amount;
        }
        _transfer(from, to, amount);
        return true;
    }

    ///////////////////////////// HSK methods ///////////////////////////// 

    /// @dev batch execute transfer tokens.
    function batchTransfer(address[] memory tos, uint256[] memory amounts) external {
        require(tos.length == amounts.length, "ERC20: Unmatched array length");

        for (uint256 i = 0; i < tos.length; i++) {
            transfer(tos[i], amounts[i]);
        }
    }

    /// @dev batch execute transferFrom tokens.
    function batchTransferFrom(
        address from,
        address[] memory tos,
        uint256[] memory amounts
    ) external {
        require(tos.length == amounts.length, "ERC20: Unmatched array length");

        for (uint256 i = 0; i < tos.length; i++) {
            transferFrom(from, tos[i], amounts[i]);
        }
    }

    /// @dev return _ecoGrowthShare.
    function ecoGrowthShare() external view returns (uint256) {
        return _ecoGrowthShare;
    }

    /// @dev return _teamShare.
    function teamShare() external view returns (uint256) {
        return _teamShare;
    }

    /// @dev return _reserveShare.
    function reserveShare() external view returns (uint256) {
        return _reserveShare;
    }

    /// @dev total unlocked token amount of all vesting schedules.
    function vestingAmountOf(address _owner) external view returns (uint256) {
        AccountState storage state = accounts[_owner];
        uint256 amount = 0;

        uint256 length = state.cliffVesting.length;
        for (uint256 i = 0; i < length;) {
            Vesting.Cliff storage vesting = state.cliffVesting[i];
            if (vesting.active) {
                // solhint-disable-next-line not-rely-on-time
                (uint256 locking, ) = vesting.getCliff(block.timestamp);
                unchecked { amount += locking; }
            }
            unchecked { i++; }
        }

        length = state.linearVesting.length;
        for (uint256 i = 0; i < length;) {
            Vesting.Linear storage vesting = state.linearVesting[i];
            if (vesting.active) {
                // solhint-disable-next-line not-rely-on-time
                (uint256 locking, ) = vesting.getLinear(block.timestamp);
                unchecked { amount += locking; }
            }
            unchecked { i++; }
        }

        return amount;
    }

    /// @dev compute all cliff vesting schedules of `_owner`.
    function cliffVestingOf(address _owner) external view returns (CliffVesting[] memory) {
        AccountState storage state = accounts[_owner];
        
        uint256 num = 0;
        uint256 length = state.cliffVesting.length;
        uint256[] memory lockings = new uint256[](length);
        for (uint256 i = 0; i < length;) {
            Vesting.Cliff storage vesting = state.cliffVesting[i];
            if (vesting.active) {
                // solhint-disable-next-line not-rely-on-time
                (uint256 locking, ) = vesting.getCliff(block.timestamp);
                if (locking > 0) {
                    lockings[i] = locking;
                    unchecked { num++; }
                }
            }
            unchecked { i++; }
        }

        CliffVesting[] memory schedules = new CliffVesting[](num);
        num = 0;
        for (uint256 i = 0; i < length;) {
            uint256 locking = lockings[i];
            if (locking > 0) {
                Vesting.Cliff storage vesting = state.cliffVesting[i];
                schedules[num] = CliffVesting({
                    bucket: vesting.bucket,
                    expiration: vesting.expiration,
                    amount: locking
                });
                unchecked { num++; }
            }
            unchecked { i++; }
        }

        return schedules;
    }

    /// @dev compute all linear vesting schedules of `_owner`.
    function linearVestingOf(address _owner) external view returns (LinearVesting[] memory) {
        AccountState storage state = accounts[_owner];
        
        uint256 num = 0;
        uint256 length = state.linearVesting.length;
        uint256[] memory lockings = new uint256[](length);
        for (uint256 i = 0; i < length;) {
            Vesting.Linear storage vesting = state.linearVesting[i];
            if (vesting.active) {
                // solhint-disable-next-line not-rely-on-time
                (uint256 locking, ) = vesting.getLinear(block.timestamp);
                if (locking > 0) {
                    lockings[i] = locking;
                    unchecked { num++; }
                }
            }
            unchecked { i++; }
        }

        LinearVesting[] memory schedules = new LinearVesting[](num);
        num = 0;
        for (uint256 i = 0; i < length;) {
            uint256 locking = lockings[i];
            if (locking > 0) {
                Vesting.Linear storage vesting = state.linearVesting[i];
                schedules[num] = LinearVesting({
                    bucket: vesting.bucket,
                    interval: vesting.interval,
                    expiration: vesting.end,
                    amount: locking
                });
                unchecked { num++; }
            }
            unchecked { i++; }
        }

        return schedules;
    }

    /// @dev mint type 1: directly mint to account, without any vesting schedule.
    function mint1(Mint.Bucket bucket, address recipient, uint256 amount)
        public
        accessible(_selectRole(bucket))
        notInBlackList(recipient)
    {
        require(amount > 0, "ERC20: Amount is zero");
        _decreaseShare(bucket, amount);

        AccountState storage state = accounts[recipient];
        state.available += amount;

        emit MintType1(bucket, recipient, amount);
    }

    /// @dev batch execution of mint type 1.
    function batchMint1(
        Mint.Bucket[] memory buckets,
        address[] memory recipients,
        uint256[] memory amounts
    ) external {
        require(buckets.length == recipients.length, "ERC20: Unmatched array length");
        require(recipients.length == amounts.length, "ERC20: Unmatched array length");

        for (uint256 i = 0; i < recipients.length; i++) {
            mint1(buckets[i], recipients[i], amounts[i]);
        }
    }

    /// @dev mint type 2: mint to account with cliff vesting schedule.
    function mint2(Mint.Bucket bucket, address recipient, uint256 expiration, uint256 amount)
        public
        accessible(_selectRole(bucket))
        notInBlackList(recipient)
    {
        // solhint-disable-next-line not-rely-on-time
        require(expiration > block.timestamp, "ERC20: Expiration less than block time");
        require(amount > 0, "ERC20: Amount is zero");
        _decreaseShare(bucket, amount);

        AccountState storage state = accounts[recipient];
        require(
            state.cliffVesting.length + state.linearVesting.length < MAX_SCHEDULES,
            "ERC20: Too many vesting schedules"
        );
        state.cliffVesting.push(Vesting.Cliff({
            active: true,
            bucket: bucket,
            expiration: expiration.toUint64(),
            amount: amount
        }));

        emit MintType2(bucket, recipient, expiration, amount);
    }

    /// @dev batch execution of mint type 2.
    function batchMint2(
        Mint.Bucket[] memory buckets,
        address[] memory recipients,
        uint256[] memory expirations,
        uint256[] memory amounts
    ) external {
        require(buckets.length == recipients.length, "ERC20: Unmatched array length");
        require(recipients.length == expirations.length, "ERC20: Unmatched array length");
        require(expirations.length == amounts.length, "ERC20: Unmatched array length");

        for (uint256 i = 0; i < recipients.length; i++) {
            mint2(buckets[i], recipients[i], expirations[i], amounts[i]);
        }
    }

    /// @dev Mint type 3: mint to account with linear vesting schedule.
    function mint3(
        Mint.Bucket bucket,
        address recipient,
        uint256 start,
        uint256 end,
        uint256 interval,
        uint256 amount
    )
        public
        accessible(_selectRole(bucket))
        notInBlackList(recipient)
    {
        require(interval > 0, "ERC20: Interval is zero");
        // solhint-disable-next-line not-rely-on-time
        require(start > block.timestamp, "ERC20: Start less than block time");
        require(start < end, "ERC20: Start greater than end");
        require((end - start) % interval == 0, "ERC20: Interval is indivisible");
        require(amount > 0, "ERC20: Amount is zero");
        _decreaseShare(bucket, amount);

        AccountState storage state = accounts[recipient];
        require(
            state.cliffVesting.length + state.linearVesting.length < MAX_SCHEDULES,
            "ERC20: Too many vesting schedules"
        );
        state.linearVesting.push(Vesting.Linear({
            active: true,
            bucket: bucket,
            start: start.toUint64(),
            end: end.toUint64(),
            interval: interval.toUint64(),
            amount: amount
        }));

        emit MintType3(bucket, recipient, start, end, interval, amount);
    }

    /// @dev batch execution of mint type 3.
    function batchMint3(
        Mint.Bucket[] memory buckets,
        address[] memory recipients,
        uint256[] memory starts,
        uint256[] memory ends,
        uint256[] memory intervals,
        uint256[] memory amounts
    ) external {
        require(buckets.length == recipients.length, "ERC20: Unmatched array length");
        require(recipients.length == starts.length, "ERC20: Unmatched array length");
        require(starts.length == ends.length, "ERC20: Unmatched array length");
        require(ends.length == intervals.length, "ERC20: Unmatched array length");
        require(intervals.length == amounts.length, "ERC20: Unmatched array length");

        for (uint256 i = 0; i < recipients.length; i++) {
            mint3(buckets[i], recipients[i], starts[i], ends[i], intervals[i], amounts[i]);
        }
    }

    /// @dev recall vesting amount of a team member.
    function recallTeamVesting(address account) external accessible(TEAM_ROLE) {
        AccountState storage state = accounts[account];
        _updateAccountState(state);

        uint256 recycling = 0;
        uint256 length = state.cliffVesting.length;
        for (uint256 i = 0; i < length;) {
            Vesting.Cliff storage vesting = state.cliffVesting[i];
            if (vesting.active && vesting.bucket == Mint.Bucket.Team) {
                vesting.active = false;
                unchecked { recycling += vesting.amount; }
            }
            unchecked { i++; }
        }

        length = state.linearVesting.length;
        for (uint256 i = 0; i < length;) {
            Vesting.Linear storage vesting = state.linearVesting[i];
            if (vesting.active && vesting.bucket == Mint.Bucket.Team) {
                vesting.active = false;
                unchecked { recycling += vesting.amount; }
            }
            unchecked { i++; }
        }
        // recycle to teamShare
        _teamShare += recycling;

        emit RecallTeamVesting(account, recycling);
    }

    /// @dev reduce share of specified `bucket`, add reduce `_totalSupply`.
    function shrinkShare(Mint.Bucket bucket, uint256 amount) external onlyOwner {
        require(amount > 0, "ERC20: Amount is zero");
        _decreaseShare(bucket, amount);
        _totalSupply -= amount;

        emit ShrinkShare(bucket, amount);
    }

    ///////////////////////////// Internal Methods /////////////////////////////

    function _selectRole(Mint.Bucket bucket) internal pure returns (bytes32) {
        if (bucket == Mint.Bucket.EcoGrowth) {
            return ECO_GROWTH_ROLE;
        } else if (bucket == Mint.Bucket.Team) {
            return TEAM_ROLE;
        } else if (bucket == Mint.Bucket.Reserve) {
            return RESERVE_ROLE;
        } else {
            revert("ERC20: Invalid mint bucket");
        }
    }

    function _decreaseShare(Mint.Bucket bucket, uint256 amount) internal {
        if (bucket == Mint.Bucket.EcoGrowth) {
            require(amount <= _ecoGrowthShare, "ERC20: Insufficient share");
            _ecoGrowthShare -= amount;
        } else if (bucket == Mint.Bucket.Team) {
            require(amount <= _teamShare, "ERC20: Insufficient share");
            _teamShare -= amount;
        } else if (bucket == Mint.Bucket.Reserve) {
            require(amount <= _reserveShare, "ERC20: Insufficient share");
            _reserveShare -= amount;
        } else {
            revert("ERC20: Invalid mint bucket");
        }
    }

    /// @dev compute the releasing amount of vest part and even vest part.
    function _updateAccountState(AccountState storage state) internal {
        uint256 increased = 0;
        uint256 released;
        uint256 length = state.cliffVesting.length;
        for (uint256 i = 0; i < length;) {
            Vesting.Cliff storage vesting = state.cliffVesting[i];
            // solhint-disable-next-line not-rely-on-time
            released = vesting.updateCliff(block.timestamp);
            unchecked {
                increased += released;
                i++;
            }
        }

        length = state.linearVesting.length;
        for (uint256 i = 0; i < length;) {
            Vesting.Linear storage vesting = state.linearVesting[i];
            // solhint-disable-next-line not-rely-on-time
            released = vesting.updateLinear(block.timestamp);
            unchecked {
                increased += released;
                i++;
            }
        }

        state.available += increased;
    }

    /// @dev transfer {amount} from {_from} to {_to}.
    /// @notice update account state firstly.
    function _transfer(address from, address to, uint256 amount) internal {
        require(to != address(0), "ERC20: To address is zero");

        AccountState storage fromState = accounts[from];
        _updateAccountState(fromState);
        require(fromState.available >= amount, "ERC20: Insufficient balance");
        fromState.available -= amount;

        AccountState storage toState = accounts[to];
        toState.available += amount;

        emit Transfer(from, to, amount);
    }

    /// @dev approve {amount} of {spender} from {owner}
    function _approve(address _owner, address spender, uint256 amount) internal {
        require(spender != address(0), "ERC20: Spender address is zero");

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

    /// @dev burn {amount} of {applicant}, and reduce _totalSupply.
    function _burn(address applicant, uint256 amount) internal {
        AccountState storage state = accounts[applicant];
        _updateAccountState(state);

        require(state.available >= amount, "ERC20: Insufficient balance");
        state.available -= amount;
        _totalSupply -= amount;

        emit Burn(applicant, amount);
    }

    /// @dev burn {amount} of {from} allowance for {applicant}, and reduce _totalSupply.
    function _burnFrom(address applicant, address from, uint256 amount) internal {
        uint256 _allowance = allowance(from, applicant);
        require(amount <= _allowance, "ERC20: Insufficient allowance");
        _allowances[from][applicant] = _allowance - amount;
        
        AccountState storage state = accounts[from];
        _updateAccountState(state);

        require(state.available >= amount, "ERC20: Insufficient balance");
        state.available -= amount;
        _totalSupply -= amount;

        emit BurnFrom(applicant, from, amount);
    }
}

contracts/ERC20Permit.sol

// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./interface/IERC20Permit.sol";
import "./ERC20.sol";
import "./library/CheckSig.sol";

/// @title ERC20 with permit, as defined in https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]
/// @notice ERC20 tokens which supports approvement via signature
abstract contract ERC20Permit is IERC20Permit, ERC20 {
    using CheckSig for address;

    bytes32 private constant NAME_HASH = keccak256("HSK");

    bytes32 private constant VERSION_HASH = keccak256("version 1");

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private constant PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    mapping(address => uint256) private _nonces;

    /// @dev return user's current nonce and increase it.
    function increaseNonce(address account) internal returns (uint256) {
        uint256 n = _nonces[account];
        _nonces[account]++;
        return n;
    }

    /// @dev See in IERC20Permit
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() public view override returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, NAME_HASH, VERSION_HASH, block.chainid, address(this)));
    }

    /// @dev See in IERC20Permit.
    function nonces(address account) public view override returns (uint256) {
        return _nonces[account];
    }

    /// @dev See in IERC20Permit.
    function permit(
        address _owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    )
        public
        override
        notInBlackList(_owner)
        notInBlackList(spender)
    {
        // solhint-disable-next-line not-rely-on-time
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, _owner, spender, value, increaseNonce(_owner), deadline));
        bytes32 digest = ECDSA.toTypedDataHash(DOMAIN_SEPARATOR(), structHash);

        _owner.checkSignature(digest, v, r, s);

        _approve(_owner, spender, value);
    }
}

contracts/interface/IERC20.sol

//SPDX-License-Identifier: Unlicense
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 name of the token.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
    /**
     * @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 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 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 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);
}

contracts/interface/IERC20Permit.sol

// SPDX-License-Identifier: Unlicense
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);
}

contracts/library/CheckSig.sol

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/interfaces/IERC1271.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

library CheckSig {
    /// @dev Check {from} has signed a hashed message {digest} with signature {v, r, s}.
    function checkSignature(address from, bytes32 digest, uint8 v, bytes32 r, bytes32 s) internal view {
        if (from.code.length > 0) {
            // from is a contract
            (bool success, bytes memory result) = from.staticcall(
                abi.encodeWithSelector(IERC1271.isValidSignature.selector, digest, abi.encodePacked(r, s, v))
            );
            require(
                success && result.length == 32 && abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector),
                "ERC1271: Unauthorized"
            );
        } else {
            require(ECDSA.recover(digest, v, r, s) == from, "CheckSig: Unauthorized");
        }
    }

    /// @dev Check {from} has signed a hashed message {digest} with signature {sig}.
    function checkSignature(address from, bytes32 digest, bytes memory sig) internal view {
        if (from.code.length > 0) {
            // from is a contract
            (bool success, bytes memory result) = from.staticcall(
                abi.encodeWithSelector(IERC1271.isValidSignature.selector, digest, sig)
            );
            require(
                success && result.length == 32 && abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector),
                "ERC1271: Unauthorized"
            );
        } else {
            require(ECDSA.recover(digest, sig) == from, "CheckSig: Unauthorized");
        }
    }
}

contracts/library/Mint.sol

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

library Mint {
    
    enum Bucket {
        // 0
        EcoGrowth,
        // 1
        Team,
        // 2
        Reserve
    }
}

contracts/library/Vesting.sol

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "./Mint.sol";

library Vesting {

    /// Cliff Vesting defines `amount` tokens will be fully unlocked after `expiration`.
    struct Cliff {
        bool            active;
        Mint.Bucket     bucket;
        uint64          expiration;
        uint256         amount;
    }

    /// Linear Vesting defines `amount` tokens will start unlocking linearly from `start` to `end`.
    /// Tokens will unlock every `interval` seconds.
    struct Linear {
        bool            active;
        Mint.Bucket     bucket;
        uint64          start;
        uint64          end;
        uint64          interval;
        uint256         amount;
    }

    /// @dev compute current (locking, released) amount of a Cliff Vesting.
    function getCliff(Cliff storage vesting, uint256 timestamp) internal view returns (uint256, uint256) {
        require(vesting.active, "Cliff Vesting is not active");

        if (timestamp >= vesting.expiration) {
            return (0, vesting.amount);
        } else {
            return (vesting.amount, 0);
        }
    }

    /// @dev compute current (locking, released) amount of a Linear Vesting.
    function getLinear(Linear storage vesting, uint256 timestamp) internal view returns (uint256, uint256) {
        require(vesting.active, "Linear Vesting is not active");

        if (timestamp <= vesting.start) {
            return (vesting.amount, 0);
        } else if (timestamp > vesting.start && timestamp < vesting.end) {
            // the following computation will never overflow
            unchecked {
                // interval is always greater than 0 less than 1 year
                uint256 iTimes = (timestamp - vesting.start) / vesting.interval;
                uint256 nTimes = (vesting.end - vesting.start) / vesting.interval;
                // nTimes interval is always greater
                uint256 released = vesting.amount * iTimes / nTimes;
                return (vesting.amount - released, released);
            }
        } else {
            return (0, vesting.amount);
        }
    }

    /// @dev update a Cliff Vesting, return the released amount.
    function updateCliff(Cliff storage vesting, uint256 timestamp) internal returns (uint256) {
        if (!vesting.active || timestamp < vesting.expiration) {
            return 0;
        }

        vesting.active = false;
        return vesting.amount;
    }

    /// @dev update a Linear Vesting, return the released amount.
    function updateLinear(Linear storage vesting, uint256 timestamp) internal returns (uint256) {
        if (!vesting.active || timestamp < vesting.start + vesting.interval) {
            return 0;
        }

        if (timestamp < vesting.end) {
            // the following computation will never overflow
            unchecked {
                uint256 iTimes = (timestamp - vesting.start) / vesting.interval;
                uint256 nTimes = (vesting.end - vesting.start) / vesting.interval;
                uint256 released = vesting.amount * iTimes / nTimes;
                vesting.start = uint64(iTimes * vesting.interval + vesting.start);
                vesting.amount = vesting.amount - released;
                return released;
            }
        } else {
            vesting.active = false;
            return vesting.amount;
        }
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "london",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.