Skip to content
Verified contractExactBUSL-1.1

MilestoneManager

Address0xdfa1f7ae5014984d449c50f90c243ebb087ff6cd
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.18

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.18+commit.87f61d96
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
BUSL-1.1
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
21,237,959
Creation transaction
0x397511126d…da6f91acb4

contracts/MilestoneManager.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { AccessProtected } from "./libraries/AccessProtected.sol";
import { IMilestoneManager } from "./interfaces/IMilestoneManager.sol";

/**
 * @title Milestone Manager
 * @notice The MilestoneManager contract is responsible for managing the milestones
 */
contract MilestoneManager is AccessProtected, IMilestoneManager {
	using SafeERC20 for IERC20;

	/// Address of the token
	address public immutable tokenAddress;
	/// Total Number of tokens reserved for milestones
	uint256 public numTokensReservedForMilestones;
	/// Nonce to generate milestone IDs
	uint256 private milestoneIdNonce;

	/// Milestone struct to store the details of a milestone
	struct Milestone {
		address recipient;
		uint32 deactivationTimestamp;
		uint256 claimedAmount;
		MilestoneStep[] steps;
	}

	/// MilestoneStep struct to store the details of a milestone step
	struct MilestoneStep {
		uint256 allocation;
		bool isApproved;
		uint32 deactivationTimestamp;
		string externalRef;
	}

	/// Holds the milestone IDs for each recipient
	mapping(address => bytes32[]) public recipientMilestones;
	/// Holds the milestone details for each milestone ID
	mapping(bytes32 => Milestone) public milestonesById;
	/// List of all recipients
	address[] public recipients;

	/**
	 * @notice Sets the token address
	 * @dev The token address cannot be the zero address
	 * @param _tokenAddress - The address of the token
	 */
	constructor(address _tokenAddress) {
		if (_tokenAddress == address(0)) {
			revert invalidAddress();
		}
		tokenAddress = _tokenAddress;
	}

	/**
	 * @notice Creates a new milestone
	 * @param recipient - The address of the recipient
	 * @param _allocations - The amount of tokens to allocate for each step
	 * @param _approvals - The approval status of each step
	 * @param _externalRefs - The external reference of each step
	 * @return milestoneId - The ID of the created milestone
	 */
	function createMilestone(
		address recipient,
		uint256[] calldata _allocations,
		bool[] calldata _approvals,
		string[] calldata _externalRefs
	) public onlyAdmin returns (bytes32) {
		if (recipient == address(0)) {
			revert invalidZeroAddress();
		}
		uint256 length = _allocations.length;
		if (_approvals.length != length || _externalRefs.length != length) {
			revert arrayLengthMismatch();
		}

		// Generate the Milestone ID based on the nonce
		bytes32 milestoneId = bytes32(milestoneIdNonce++);
		Milestone storage milestone = milestonesById[milestoneId];
		// Initialize the milestone directly in the mapping
		milestone.recipient = recipient;
		uint256 totalExpectedAmount;

		for (uint256 i; i < _allocations.length; ) {
			milestone.steps.push(
				MilestoneStep({
					allocation: _allocations[i],
					isApproved: _approvals[i],
					externalRef: _externalRefs[i],
					deactivationTimestamp: 0
				})
			);

			totalExpectedAmount += _allocations[i];
			unchecked {
				++i;
			}
		}

		milestonesById[milestoneId] = milestone;
		if (!isRecipient(recipient)) {
			recipients.push(recipient);
		}
		recipientMilestones[recipient].push(milestoneId);
		numTokensReservedForMilestones += totalExpectedAmount;

		emit MilestoneCreated(milestoneId, recipient, totalExpectedAmount);
		IERC20(tokenAddress).safeTransferFrom(
			msg.sender,
			address(this),
			totalExpectedAmount
		);
		return milestoneId;
	}

	/**
	 * @notice Creates a batch of milestones
	 * @param recipient - The address of the recipient
	 * @param _allocations - The amount of tokens to allocate for each step
	 * @param _approvals - The approval status of each step
	 * @param _externalRefs - The external reference of each step
	 * @return milestonesId - The IDs of the created milestones
	 */
	function createMilestoneBatch(
		address[] calldata recipient,
		uint256[][] calldata _allocations,
		bool[][] calldata _approvals,
		string[][] calldata _externalRefs
	) external onlyAdmin returns (bytes32[] memory) {
		uint256 length = recipient.length;
		bytes32[] memory milestonesId = new bytes32[](length);
		if (
			_allocations.length != length ||
			_approvals.length != length ||
			_externalRefs.length != length
		) {
			revert arrayLengthMismatch();
		}
		for (uint256 i; i < length; ) {
			milestonesId[i] = createMilestone(
				recipient[i],
				_allocations[i],
				_approvals[i],
				_externalRefs[i]
			);
			unchecked {
				++i;
			}
		}
		return milestonesId;
	}

	/**
	 * @notice Claim the tokens for a milestone
	 * @param milestoneId - The ID of the milestone
	 */
	function claim(bytes32 milestoneId) external {
		Milestone storage milestone = milestonesById[milestoneId];
		if (milestone.recipient != msg.sender) {
			revert NotMilestoneOwner();
		}

		uint256 claimableAmount = calculateClaimable(milestoneId);
		if (claimableAmount == 0) {
			revert insufficientBalance();
		}

		milestone.claimedAmount += claimableAmount;
		numTokensReservedForMilestones -= claimableAmount;
		emit MilestoneClaimed(milestoneId, msg.sender, claimableAmount);
		IERC20(tokenAddress).safeTransfer(msg.sender, claimableAmount);
	}

	/**
	 * @notice Calculate the claimable amount for a milestone
	 * @param milestoneId - The ID of the milestone
	 * @return claimable - The claimable amount
	 */
	function calculateClaimable(
		bytes32 milestoneId
	) internal view returns (uint256) {
		Milestone memory milestone = milestonesById[milestoneId];
		uint256 totalClaimable;

		for (uint256 i; i < milestone.steps.length; ) {
			if (milestone.steps[i].isApproved) {
				totalClaimable += milestone.steps[i].allocation;
			}
			unchecked {
				++i;
			}
		}

		return totalClaimable - milestone.claimedAmount;
	}

	/**
	 * @notice Approve a milestone step
	 * @param _milestoneId - The ID of the milestone
	 * @param _stepIndex - The index of the step to approve
	 */
	function approveMilestone(
		bytes32 _milestoneId,
		uint256 _stepIndex
	) external onlyAdmin {
		Milestone storage milestone = milestonesById[_milestoneId];
		if (milestone.recipient == address(0)) {
			revert milestoneNotExists();
		}
		if (_stepIndex >= milestone.steps.length) {
			revert invalidStepIndex();
		}
		MilestoneStep storage step = milestone.steps[_stepIndex];
		if (step.isApproved) {
			revert stepAlreadyApproved();
		}

		if (step.deactivationTimestamp != 0) {
			revert MilestoneStepIsRevoked();
		}

		step.isApproved = true;

		emit MilestoneApproved(_milestoneId, _stepIndex);
	}

	/**
	 * @notice Revoke a milestone
	 * @param milestoneId - The ID of the milestone to revoke
	 */
	function revokeMilestone(bytes32 milestoneId) external onlyAdmin {
		Milestone storage milestone = milestonesById[milestoneId];
		if (milestone.recipient == address(0)) {
			revert milestoneNotExists();
		}
		if (milestone.deactivationTimestamp != 0) {
			revert milestoneAlreadyRevoked();
		}
		uint revokedAmount;
		milestone.deactivationTimestamp = uint32(block.timestamp);
		for (uint256 i; i < milestone.steps.length; ) {
			if (
				milestone.steps[i].isApproved == false &&
				milestone.steps[i].deactivationTimestamp == 0
			) {
				revokeMilestoneStep(milestoneId, i);
				revokedAmount += milestone.steps[i].allocation;
			}
			unchecked {
				++i;
			}
		}
		emit MilestoneRevoked(milestoneId, milestone.recipient, revokedAmount);
	}

	/**
	 * @notice Revokes a milestone step
	 * @param milestoneId The ID of the milestone
	 * @param stepIndex The index of the step
	 */
	function revokeMilestoneStep(
		bytes32 milestoneId,
		uint256 stepIndex
	) public onlyAdmin {
		Milestone storage milestone = milestonesById[milestoneId];

		if (stepIndex >= milestone.steps.length) {
			revert invalidStepIndex();
		}

		MilestoneStep storage step = milestone.steps[stepIndex];

		// Check if the step has already been approved
		if (step.isApproved) {
			revert stepAlreadyApproved();
		}

		// Check if the step has already been revoked
		if (step.deactivationTimestamp != 0) {
			revert stepAlreadyRevoked();
		}

		uint256 revokeAmount = step.allocation;

		step.deactivationTimestamp = uint32(block.timestamp);
		// Update the total reserved tokens for milestones
		numTokensReservedForMilestones -= revokeAmount;

		emit MilestoneStepRevoked(
			milestoneId,
			stepIndex,
			milestone.recipient,
			revokeAmount
		);
	}

	/// ADMIN WITHDRAW HELPER FUNCTIONS

	/**
	 * @notice Allow the owner to withdraw any balance not currently tied up in milestones
	 * @param _amountRequested - Amount to withdraw
	 */
	function withdrawAdmin(uint256 _amountRequested) external onlyAdmin {
		uint256 amountRemaining = amountAvailableToWithdrawByAdmin();
		if (amountRemaining < _amountRequested) {
			revert insufficientBalance();
		}

		emit AdminWithdrawn(msg.sender, _amountRequested);
		IERC20(tokenAddress).safeTransfer(msg.sender, _amountRequested);
	}

	/**
	 * @notice Withdraw accidentally sent tokens other than the token managed by this contract
	 * @param _otherTokenAddress - the token which we want to withdraw
	 */
	function withdrawOtherToken(address _otherTokenAddress) external onlyAdmin {
		if (_otherTokenAddress == tokenAddress) {
			// tokenAddress address is already sure to be nonzero due to constructor
			revert invalidToken();
		}
		uint256 balance = IERC20(_otherTokenAddress).balanceOf(address(this));
		IERC20(_otherTokenAddress).safeTransfer(msg.sender, balance);
	}

	/// @notice Amount of tokens available to withdraw by the admin
	function amountAvailableToWithdrawByAdmin() public view returns (uint256) {
		return
			IERC20(tokenAddress).balanceOf(address(this)) -
			numTokensReservedForMilestones;
	}

	/**
	 * @notice Get the milestone by ID
	 * @param milestoneId - The ID of the milestone
	 * @return milestone - The milestone object
	 */
	function getMilestoneById(
		bytes32 milestoneId
	) external view returns (Milestone memory) {
		return milestonesById[milestoneId];
	}

	/**
	 * @notice Get all recipients
	 * @return recipients - The list of recipients
	 */
	function getAllRecipients() external view returns (address[] memory) {
		return recipients;
	}

	/**
	 * @notice Get all the recipients in a range
	 * @param _from - The start index (inclusive)
	 * @param _to - The end index (exclusive)
	 * @return recipientsSliced - The recipients in the range
	 */
	function getAllRecipientsSliced(
		uint256 _from,
		uint256 _to
	) external view returns (address[] memory) {
		address[] memory recipientsSliced = new address[](_to - _from);
		for (uint256 i = _from; i < _to; ) {
			recipientsSliced[i - _from] = recipients[i];
			unchecked {
				++i;
			}
		}
		return recipientsSliced;
	}

	/**
	 * @notice Get the length of all recipients
	 * @return length - The length of all recipients
	 */
	function getAllRecipientsLength() external view returns (uint256) {
		return recipients.length;
	}

	/**
	 * @notice Get the milestones of a recipient
	 * @param _recipient - The recipient address
	 * @return recipientMilestones - The milestones of the recipient
	 */
	function getRecipientMilestones(
		address _recipient
	) external view returns (bytes32[] memory) {
		return recipientMilestones[_recipient];
	}

	/**
	 * @notice Get the length of the milestones of a recipient
	 * @param _recipient - The recipient address
	 * @return length - The length of the milestones of the recipient
	 */
	function getRecipientMilestonesLength(
		address _recipient
	) external view returns (uint256) {
		return recipientMilestones[_recipient].length;
	}

	/**
	 * @notice Get the milestones of a recipient in a range
	 * @param _from - The start index (inclusive)
	 * @param _to - The end index (exclusive)
	 * @param _recipient - The recipient address
	 * @return recipientMilestonesSliced - The milestones of the recipient in the range
	 */
	function getRecipientMilestonesSliced(
		uint256 _from,
		uint256 _to,
		address _recipient
	) external view returns (bytes32[] memory) {
		bytes32[] memory recipientMilestonesSliced = new bytes32[](_to - _from);
		for (uint256 i = _from; i < _to; ) {
			recipientMilestonesSliced[i - _from] = recipientMilestones[
				_recipient
			][i];
			unchecked {
				++i;
			}
		}
		return recipientMilestonesSliced;
	}

	/**
	 * @notice Check if a recipient has milestones
	 * @param recipient - The recipient address
	 * @return isRecipient - True if the recipient has milestones
	 */
	function isRecipient(address recipient) public view returns (bool) {
		return recipientMilestones[recipient].length != 0;
	}
}

@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/IERC20.sol

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

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";

@openzeppelin/contracts/security/ReentrancyGuard.sol

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

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

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

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

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

@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
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].
     *
     * CAUTION: See Security Considerations above.
     */
    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);
}

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

@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/Create2.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
        require(address(this).balance >= amount, "Create2: insufficient balance");
        require(bytecode.length != 0, "Create2: bytecode length is zero");
        /// @solidity memory-safe-assembly
        assembly {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
        }
        require(addr != address(0), "Create2: Failed on deploy");
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40) // Get free memory pointer

            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |-------------------|---------------------------------------------------------------------------|
            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |
            // | salt              |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF              |            FF                                                             |
            // |-------------------|---------------------------------------------------------------------------|
            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := keccak256(start, 85)
        }
    }
}

contracts/TokenVestingManager.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { AccessProtected } from "./libraries/AccessProtected.sol";
import { TokenVestingLib } from "./libraries/TokenVestingLib.sol";
import { ITokenVestingManager } from "./interfaces/ITokenVestingManager.sol";

/**
 * @title Token Vesting Manager
 * @notice Contract to manage token vesting
 */
contract TokenVestingManager is AccessProtected, ITokenVestingManager {
	using TokenVestingLib for TokenVestingLib.Vesting;
	using SafeERC20 for IERC20;
	/// Address of the token to be vested
	address public immutable tokenAddress;
	/// Total number of tokens reserved for vesting
	uint256 public numTokensReservedForVesting;

	/// Holds the vesting ids for each recipient
	mapping(address => bytes32[]) public recipientVestings;
	/// Holds the vesting information for each vesting id
	mapping(bytes32 => TokenVestingLib.Vesting) public vestingById;
	/// List of all recipients
	address[] public recipients;

	/**
	 * @notice Sets the token address to be vested
	 * @param _tokenAddress - Address of the token to be vested
	 */
	constructor(address _tokenAddress) {
		if (_tokenAddress == address(0)) {
			revert TokenVestingLib.invalidAddress();
		}
		tokenAddress = _tokenAddress;
	}

	/**
	 * dev Reverts if the vesting is not active
	 */
	modifier isVestingActive(bytes32 _vestingId) {
		if (getVestingInfo(_vestingId).deactivationTimestamp != 0) {
			revert vestingNotActive();
		}
		_;
	}

	/**
	 * @notice Create a new vesting
	 * @param _recipient - Address of the recipient
	 * @param _startTimestamp - Start timestamp of the vesting
	 * @param _endTimestamp - End timestamp of the vesting
	 * @param _timelock - Timelock for the vesting
	 * @param _initialUnlock - Initial unlock amount
	 * @param _cliffReleaseTimestamp - Cliff release timestamp
	 * @param _cliffAmount - Cliff amount
	 * @param _releaseIntervalSecs - Release interval in seconds
	 * @param _linearVestAmount - Linear vest amount
	 * @return vestingId - Identifier of the vesting
	 */
	function createVesting(
		address _recipient,
		uint32 _startTimestamp,
		uint32 _endTimestamp,
		uint32 _timelock,
		uint256 _initialUnlock,
		uint32 _cliffReleaseTimestamp,
		uint256 _cliffAmount,
		uint32 _releaseIntervalSecs,
		uint256 _linearVestAmount
	) external onlyAdmin returns (bytes32 vestingId) {
		if (_recipient == address(0)) {
			revert TokenVestingLib.invalidAddress();
		}
		uint256 totalExpectedAmount = _initialUnlock +
			_cliffAmount +
			_linearVestAmount;

		numTokensReservedForVesting += totalExpectedAmount;

		vestingId = _createVesting(
			_recipient,
			_startTimestamp,
			_endTimestamp,
			_timelock,
			_initialUnlock,
			_cliffReleaseTimestamp,
			_cliffAmount,
			_releaseIntervalSecs,
			_linearVestAmount
		);
		IERC20(tokenAddress).safeTransferFrom(
			msg.sender,
			address(this),
			totalExpectedAmount
		);

		return vestingId;
	}

	/**
	 * @notice Create a batch of vestings
	 * @param params - Parameters for creating the vesting batch
	 * @return vestingIds - Identifiers of the vestings
	 */
	function createVestingBatch(
		CreateVestingBatchParams calldata params
	) external onlyAdmin returns (bytes32[] memory) {
		uint256 length = params._recipients.length;
		bytes32[] memory vestingIds = new bytes32[](length);

		uint256 totalExpectedAmount;

		{
			if (
				params._startTimestamps.length != length ||
				params._endTimestamps.length != length ||
				params._timelocks.length != length ||
				params._initialUnlocks.length != length ||
				params._cliffAmounts.length != length ||
				params._cliffReleaseTimestamps.length != length ||
				params._releaseIntervalSecs.length != length ||
				params._linearVestAmounts.length != length
			) {
				revert arrayLengthMismatch();
			}
		}

		for (uint256 i; i < params._recipients.length; ) {
			vestingIds[i] = _createVesting(
				params._recipients[i],
				params._startTimestamps[i],
				params._endTimestamps[i],
				params._timelocks[i],
				params._initialUnlocks[i],
				params._cliffReleaseTimestamps[i],
				params._cliffAmounts[i],
				params._releaseIntervalSecs[i],
				params._linearVestAmounts[i]
			);

			totalExpectedAmount +=
				uint256(params._initialUnlocks[i]) +
				uint256(params._cliffAmounts[i]) +
				params._linearVestAmounts[i];

			unchecked {
				++i;
			}
		}

		numTokensReservedForVesting += totalExpectedAmount;
		IERC20(tokenAddress).safeTransferFrom(
			msg.sender,
			address(this),
			totalExpectedAmount
		);

		return vestingIds;
	}

	/**
	 * @notice Claim vested tokens
	 * @param _vestingId - Identifier of the vesting
	 */
	function claim(bytes32 _vestingId) external {
		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];
		if (msg.sender != vesting.recipient) {
			revert notVestingOwner();
		}
		if (vesting.timelock > uint32(block.timestamp)) {
			revert TokenVestingLib.timelockEnabled();
		}

		uint256 vested = TokenVestingLib.calculateVestedAmount(
			vesting,
			uint32(block.timestamp)
		);
		uint256 claimable = vested - vesting.claimedAmount;
		if (claimable == 0) {
			revert insufficientBalance();
		}
		vesting.claimedAmount += claimable;
		numTokensReservedForVesting -= claimable;
		emit Claimed(msg.sender, claimable, _vestingId);
		IERC20(tokenAddress).safeTransfer(msg.sender, claimable);
	}

	/**
	 * @notice Revoke active Vesting
	 * @param _vestingId - Vesting Identifier
	 */
	function revokeVesting(
		bytes32 _vestingId
	) external onlyAdmin isVestingActive(_vestingId) {
		TokenVestingLib.Vesting storage vesting = vestingById[_vestingId];
		uint256 finalVestAmount = TokenVestingLib.calculateVestedAmount(
			vesting,
			vesting.endTimestamp
		);
		if (vesting.claimedAmount == finalVestAmount) {
			revert allVestedAmountAlreadyClaimed();
		}

		vesting.deactivationTimestamp = uint32(block.timestamp);
		uint256 vestedAmountNow = TokenVestingLib.calculateVestedAmount(
			vesting,
			uint32(block.timestamp)
		);

		uint256 amountRemaining = finalVestAmount - vestedAmountNow;
		numTokensReservedForVesting -= amountRemaining;

		emit VestingRevoked(vesting.recipient, amountRemaining, vesting);
	}

	/// INTERNAL FUNCTIONS

	/**
	 * @dev Internal function to create a new vesting
	 * @param _recipient - Address of the recipient
	 * @param _startTimestamp - Start timestamp of the vesting
	 * @param _endTimestamp - End timestamp of the vesting
	 * @param _timelock - Timelock for the vesting
	 * @param _initialUnlock - Initial unlock amount
	 * @param _cliffReleaseTimestamp - Cliff release timestamp
	 * @param _cliffAmount - Cliff amount
	 * @param _releaseIntervalSecs - Release interval in seconds
	 * @param _linearVestAmount - Linear vest amount
	 * @return vestingId - Identifier of the vesting
	 */
	function _createVesting(
		address _recipient,
		uint32 _startTimestamp,
		uint32 _endTimestamp,
		uint32 _timelock,
		uint256 _initialUnlock,
		uint32 _cliffReleaseTimestamp,
		uint256 _cliffAmount,
		uint32 _releaseIntervalSecs,
		uint256 _linearVestAmount
	) internal returns (bytes32) {
		if (_recipient == address(0)) {
			revert TokenVestingLib.invalidAddress();
		}
		if (_linearVestAmount + _cliffAmount == 0) {
			revert TokenVestingLib.invalidVestedAmount();
		}
		if (_startTimestamp == 0) {
			revert TokenVestingLib.invalidStartTimestamp();
		}
		if (_endTimestamp == 0) {
			revert TokenVestingLib.invalidEndTimestamp();
		}
		if (_startTimestamp > _endTimestamp) {
			revert TokenVestingLib.invalidEndTimestamp();
		}
		if (_releaseIntervalSecs == 0) {
			revert TokenVestingLib.invalidReleaseInterval();
		}
		if (_cliffReleaseTimestamp == 0) {
			if (_cliffAmount != 0) {
				revert TokenVestingLib.invalidCliffAmount();
			}
			if ((_endTimestamp - _startTimestamp) % _releaseIntervalSecs != 0) {
				revert TokenVestingLib.invalidIntervalLength();
			}
		} else {
			if (
				((_startTimestamp > _cliffReleaseTimestamp) ||
					(_cliffReleaseTimestamp >= _endTimestamp))
			) {
				revert TokenVestingLib.invalidCliffRelease();
			}
			if (_cliffAmount == 0) {
				revert TokenVestingLib.invalidCliffAmount();
			}
			if (
				(_endTimestamp - _cliffReleaseTimestamp) %
					_releaseIntervalSecs !=
				0
			) {
				revert TokenVestingLib.invalidIntervalLength();
			}
		}

		TokenVestingLib.Vesting memory vesting = TokenVestingLib.Vesting({
			recipient: _recipient,
			startTimestamp: _startTimestamp,
			endTimestamp: _endTimestamp,
			deactivationTimestamp: 0,
			timelock: _timelock,
			initialUnlock: _initialUnlock,
			cliffReleaseTimestamp: _cliffReleaseTimestamp,
			cliffAmount: _cliffAmount,
			releaseIntervalSecs: _releaseIntervalSecs,
			linearVestAmount: _linearVestAmount,
			claimedAmount: 0
		});

		bytes32 vestingId = TokenVestingLib.generateVestingId(vesting);
		if (getVestingInfo(vestingId).startTimestamp != 0) {
			revert vestingAlreadyExists(vestingId);
		}

		if (!isRecipient(_recipient)) {
			recipients.push(_recipient);
		}

		vestingById[vestingId] = vesting;
		recipientVestings[_recipient].push(vestingId);

		emit VestingCreated(_recipient, vestingId, vesting);

		return vestingId;
	}

	/// ADMIN WITHDRAW HELPER FUNCTIONS

	/**
	 * @notice Allow the owner to withdraw any balance not currently tied up in Vestings
	 * @param _amountRequested - Amount to withdraw
	 */
	function withdrawAdmin(uint256 _amountRequested) external onlyAdmin {
		uint256 amountRemaining = amountAvailableToWithdrawByAdmin();
		if (amountRemaining < _amountRequested) {
			revert insufficientBalance();
		}

		emit AdminWithdrawn(msg.sender, _amountRequested);
		IERC20(tokenAddress).safeTransfer(msg.sender, _amountRequested);
	}

	/**
	 * @notice Withdraw a token which isn't controlled by the vesting contract. Useful when someone accidentally sends tokens to the contract
	 * @param _otherTokenAddress - the token which we want to withdraw
	 */
	function withdrawOtherToken(address _otherTokenAddress) external onlyAdmin {
		if (_otherTokenAddress == tokenAddress) {
			// tokenAddress address is already sure to be nonzero due to constructor
			revert invalidToken();
		}
		uint256 balance = IERC20(_otherTokenAddress).balanceOf(address(this));
		IERC20(_otherTokenAddress).safeTransfer(msg.sender, balance);
	}

	/// @notice Amount of tokens available to withdraw by the admin
	function amountAvailableToWithdrawByAdmin() public view returns (uint256) {
		return
			IERC20(tokenAddress).balanceOf(address(this)) -
			numTokensReservedForVesting;
	}

	/**
	 * @notice Get the vesting information
	 * @param _vestingId - Identifier of the vesting
	 * @return vesting - Vesting information
	 */
	function getVestingInfo(
		bytes32 _vestingId
	) public view returns (TokenVestingLib.Vesting memory) {
		return vestingById[_vestingId];
	}

	/**
	 * @notice Get all recipients
	 * @return recipients - The list of recipients
	 */
	function getAllRecipients() external view returns (address[] memory) {
		return recipients;
	}

	/**
	 * @notice Check if a recipient has vestings
	 * @param recipient - The recipient address
	 * @return isRecipient - True if the recipient has vestings
	 */
	function isRecipient(address recipient) public view returns (bool) {
		return recipientVestings[recipient].length != 0;
	}

	/**
	 * @notice Get the length of all recipients
	 * @return length - The length of all recipients
	 */
	function getAllRecipientsLength() external view returns (uint256) {
		return recipients.length;
	}

	/**
	 * @notice Get all recipients in a range
	 * @param _from - The start index (inclusive)
	 * @param _to - The end index (exclusive)
	 * @return recipientsSliced - The list of recipients in the range
	 */
	function getAllRecipientsSliced(
		uint256 _from,
		uint256 _to
	) external view returns (address[] memory) {
		address[] memory recipientsSliced = new address[](_to - _from);
		for (uint256 i = _from; i < _to; ) {
			recipientsSliced[i - _from] = recipients[i];
			unchecked {
				++i;
			}
		}
		return recipientsSliced;
	}

	/**
	 * @notice Get all vestings for a recipient
	 * @param _recipient - The recipient address
	 * @return recipientVestings - The list of vestings for the recipient
	 */
	function getAllRecipientVestings(
		address _recipient
	) external view returns (bytes32[] memory) {
		return recipientVestings[_recipient];
	}

	/**
	 * @notice Get all vestings for a recipient in a range
	 * @param _from - The start index (inclusive)
	 * @param _to - The end index (exclusive)
	 * @param _recipient - The recipient address
	 * @return recipientVestingsSliced - The list of vestings for the recipient in the range
	 */
	function getAllRecipientVestingsSliced(
		uint256 _from,
		uint256 _to,
		address _recipient
	) external view returns (bytes32[] memory) {
		bytes32[] memory recipientVestingsSliced = new bytes32[](_to - _from);
		for (uint256 i = _from; i < _to; ) {
			recipientVestingsSliced[i - _from] = recipientVestings[_recipient][
				i
			];
			unchecked {
				++i;
			}
		}
		return recipientVestingsSliced;
	}

	/**
	 * @notice Get the length of all vestings for a recipient
	 * @param _recipient - The recipient address
	 * @return length - The length of all vestings for the recipient
	 */
	function getAllRecipientVestingsLength(
		address _recipient
	) external view returns (uint256) {
		return recipientVestings[_recipient].length;
	}
}

contracts/VestedMilestoneManager.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./libraries/AccessProtected.sol";
import "./libraries/TokenVestingLib.sol";
import { IVestedMilestoneManager } from "./interfaces/IVestedMilestoneManager.sol";

/**
 * @title Vested Milestone Manager
 * @notice Manages milestones that trigger token vesting schedules upon admin approval.
 */
contract VestedMilestoneManager is
	AccessProtected,
	ReentrancyGuard,
	IVestedMilestoneManager
{
	using SafeERC20 for IERC20;
	using TokenVestingLib for TokenVestingLib.Vesting;

	/// Address of the token
	address public immutable tokenAddress;
	/// Total Number of tokens reserved for vesting
	uint256 public numTokensReservedForVesting;
	/// Nonce to generate milestone IDs
	uint256 private milestoneIdNonce;

	/// Milestone struct to store the details of a milestone
	struct Milestone {
		address recipient;
		uint32 deactivationTimestamp;
		uint256 claimedAmount;
		MilestoneStep[] steps;
	}

	/// MilestoneStep struct to store the details of a milestone step
	struct MilestoneStep {
		uint256 allocation;
		bool isApproved;
		uint32 deactivationTimestamp;
		string externalRef;
		TokenVestingLib.Vesting vesting;
	}

	/// Holds the milestone IDs for each recipient
	mapping(address => bytes32[]) public recipientMilestones;
	/// Holds the milestone details for each milestone ID
	mapping(bytes32 => Milestone) public milestonesById;
	/// List of all recipients
	address[] public recipients;

	/**
	 * @notice Sets the token address
	 * @dev The token address cannot be the zero address
	 * @param _tokenAddress - The address of the token
	 */
	constructor(address _tokenAddress) {
		if (_tokenAddress == address(0)) {
			revert TokenVestingLib.invalidAddress();
		}
		tokenAddress = _tokenAddress;
	}

	/**
	 * @notice Creates a new vested milestone
	 * @param _recipient - The address of the recipient
	 * @param _allocations - The amount of tokens to allocate for each step
	 * @param _externalRefs - The external reference of each step
	 * @return milestoneId - The ID of the created milestone
	 */
	function createMilestone(
		address _recipient,
		uint256[] calldata _allocations,
		string[] calldata _externalRefs
	) public onlyAdmin returns (bytes32) {
		if (_recipient == address(0)) {
			revert invalidZeroAddress();
		}
		uint256 length = _allocations.length;
		if (_externalRefs.length != length) {
			revert arrayLengthMismatch();
		}

		// Generate the Milestone ID based on the nonce
		bytes32 milestoneId = bytes32(milestoneIdNonce++);
		Milestone storage milestone = milestonesById[milestoneId];
		TokenVestingLib.Vesting memory emptyVesting;
		// Initialize the milestone directly in the mapping
		milestone.recipient = _recipient;
		uint256 totalExpectedAmount;

		for (uint256 i; i < _allocations.length; ) {
			milestone.steps.push(
				MilestoneStep({
					allocation: _allocations[i],
					isApproved: false,
					deactivationTimestamp: 0,
					externalRef: _externalRefs[i],
					vesting: emptyVesting
				})
			);
			totalExpectedAmount += _allocations[i];
			unchecked {
				++i;
			}
		}

		milestonesById[milestoneId] = milestone;
		if (!isRecipient(_recipient)) {
			recipients.push(_recipient);
		}
		recipientMilestones[_recipient].push(milestoneId);
		numTokensReservedForVesting += totalExpectedAmount;

		emit VestedMilestoneCreated(
			milestoneId,
			_recipient,
			totalExpectedAmount
		);
		IERC20(tokenAddress).safeTransferFrom(
			msg.sender,
			address(this),
			totalExpectedAmount
		);
		return milestoneId;
	}

	/**
	 * @notice Creates a batch of vested milestones
	 * @param recipient - The address of the recipient
	 * @param _allocations - The amount of tokens to allocate for each step
	 * @param _externalRefs - The external reference of each step
	 * @return milestonesId - The ID of the created milestones
	 */
	function createMilestoneBatch(
		address[] calldata recipient,
		uint256[][] calldata _allocations,
		string[][] calldata _externalRefs
	) external onlyAdmin returns (bytes32[] memory) {
		uint256 length = recipient.length;
		bytes32[] memory milestonesId = new bytes32[](length);
		if (_allocations.length != length || _externalRefs.length != length) {
			revert arrayLengthMismatch();
		}
		for (uint256 i; i < length; ) {
			milestonesId[i] = createMilestone(
				recipient[i],
				_allocations[i],
				_externalRefs[i]
			);
			unchecked {
				++i;
			}
		}
		return milestonesId;
	}

	/**
	 * @notice Approves a milestone step and initializes its vesting schedule.
	 * @param _milestoneId - The ID of the milestone
	 * @param _stepIndex - The index of the step
	 * @param _startTimestamp - The start timestamp of the vesting
	 * @param _endTimestamp - The end timestamp of the vesting
	 * @param _timelock - The timelock of the vesting
	 * @param _initialUnlock - The initial unlock of the vesting
	 * @param _cliffReleaseTimestamp - The cliff release timestamp of the vesting
	 * @param _cliffAmount - The cliff amount of the vesting
	 * @param _releaseIntervalSecs - The release interval of the vesting
	 * @param _linearVestAmount - The linear vest amount of the vesting
	 */
	function approveMilestoneStep(
		bytes32 _milestoneId,
		uint256 _stepIndex,
		uint32 _startTimestamp,
		uint32 _endTimestamp,
		uint32 _timelock,
		uint256 _initialUnlock,
		uint32 _cliffReleaseTimestamp,
		uint256 _cliffAmount,
		uint32 _releaseIntervalSecs,
		uint256 _linearVestAmount
	) external onlyAdmin {
		Milestone storage milestone = milestonesById[_milestoneId];
		if (milestone.recipient == address(0)) {
			revert milestoneNotExists();
		}
		if (_stepIndex >= milestone.steps.length) {
			revert invalidStepIndex();
		}

		MilestoneStep storage step = milestone.steps[_stepIndex];
		if (step.isApproved) {
			revert stepAlreadyApproved();
		}

		if (step.deactivationTimestamp != 0) {
			revert MilestoneStepIsRevoked();
		}

		step.vesting = _createVesting(
			milestone.recipient,
			_startTimestamp,
			_endTimestamp,
			_timelock,
			_initialUnlock,
			_cliffReleaseTimestamp,
			_cliffAmount,
			_releaseIntervalSecs,
			_linearVestAmount
		);
		if (
			_cliffAmount + _linearVestAmount + _initialUnlock != step.allocation
		) {
			revert TokenVestingLib.invalidVestedAmount();
		}

		step.isApproved = true;

		emit VestedMilestoneStepApproved(_milestoneId, _stepIndex);
		emit VestingInitialized(_milestoneId, _stepIndex);
	}

	/**
	 * @notice Revokes a milestone
	 * @param _milestoneId The ID of the milestone
	 */
	function revokeMilestone(bytes32 _milestoneId) external onlyAdmin {
		Milestone storage milestone = milestonesById[_milestoneId];
		if (milestone.recipient == address(0)) {
			revert milestoneNotExists();
		}
		if (milestone.deactivationTimestamp != 0) {
			revert milestoneAlreadyRevoked();
		}
		uint256 amountToRevoke;
		for (uint256 i; i < milestone.steps.length; ) {
			if (milestone.steps[i].deactivationTimestamp == 0) {
				amountToRevoke += revokeMilestoneStep(_milestoneId, i);
			}
			unchecked {
				++i;
			}
		}

		milestone.deactivationTimestamp = uint32(block.timestamp);
		emit MilestoneRevoked(
			_milestoneId,
			milestone.recipient,
			amountToRevoke
		);
	}

	/**
	 * @notice Revokes a milestone step
	 * @param _milestoneId The ID of the milestone
	 * @param _stepIndex The index of the step
	 * @return uint256 The amount of tokens revoked
	 */
	function revokeMilestoneStep(
		bytes32 _milestoneId,
		uint256 _stepIndex
	) public onlyAdmin returns (uint256) {
		Milestone storage milestone = milestonesById[_milestoneId];
		if (milestone.steps.length <= _stepIndex) {
			revert invalidStepIndex();
		}
		if (milestone.deactivationTimestamp != 0) {
			revert milestoneAlreadyRevoked();
		}
		MilestoneStep storage step = milestone.steps[_stepIndex];
		if (step.deactivationTimestamp != 0) {
			revert stepAlreadyRevoked();
		}

		if (!step.isApproved) {
			step.deactivationTimestamp = uint32(block.timestamp);
			numTokensReservedForVesting -= step.allocation;
			emit MilestoneStepRevoked(
				_milestoneId,
				_stepIndex,
				milestone.recipient,
				step.allocation
			);
			return step.allocation;
		} else {
			if (
				step.deactivationTimestamp != 0 ||
				step.vesting.deactivationTimestamp != 0
			) {
				revert stepAlreadyRevoked();
			}
			step.deactivationTimestamp = uint32(block.timestamp);
			step.vesting.deactivationTimestamp = uint32(block.timestamp);

			uint claimableAmount = TokenVestingLib.calculateVestedAmount(
				step.vesting,
				uint32(block.timestamp)
			) - step.vesting.claimedAmount;

			uint amountToRevoke = step.allocation -
				(claimableAmount + step.vesting.claimedAmount);
			numTokensReservedForVesting -= amountToRevoke;
			emit MilestoneStepRevoked(
				_milestoneId,
				_stepIndex,
				milestone.recipient,
				amountToRevoke
			);
			return amountToRevoke;
		}
	}

	/**
	 * @notice Claims all available tokens for a specific milestone step.
	 * @param milestoneId - The ID of the milestone
	 * @param stepIndex - The index of the step
	 */
	function claim(bytes32 milestoneId, uint256 stepIndex) external {
		Milestone storage milestone = milestonesById[milestoneId];
		if (msg.sender != milestone.recipient) {
			revert notVestingOwner();
		}

		MilestoneStep storage step = milestone.steps[stepIndex];
		if (!milestone.steps[stepIndex].isApproved) {
			revert stepNotApproved();
		}

		if (
			milestone.steps[stepIndex].vesting.timelock >
			uint32(block.timestamp) &&
			milestone.steps[stepIndex].vesting.timelock != 0
		) {
			revert TokenVestingLib.timelockEnabled();
		}

		if (
			milestone.steps[stepIndex].vesting.startTimestamp >
			uint32(block.timestamp)
		) {
			revert startTimestampNotReached();
		}

		uint claimableAmount = TokenVestingLib.calculateVestedAmount(
			step.vesting,
			uint32(block.timestamp)
		);

		uint256 claimable = claimableAmount - step.vesting.claimedAmount; // claimableAmount is always bigger than claimedAmount
		if (claimable == 0) {
			revert insufficientBalance();
		}
		milestone.claimedAmount += claimable;
		step.vesting.claimedAmount += claimable;
		numTokensReservedForVesting -= claimable;
		emit Claimed(msg.sender, claimable, stepIndex);
		IERC20(tokenAddress).safeTransfer(msg.sender, claimable);
	}

	/**
	 * @dev Internal function to create a vesting schedule for a given recipient
	 * @param _recipient The address of the recipient for whom the vesting is created.
	 * @param _startTimestamp The start time of the vesting period as a UNIX timestamp.
	 * @param _endTimestamp The end time of the vesting period as a UNIX timestamp.
	 * @param _timelock Optional timelock period before which tokens cannot be claimed.
	 * @param _initialUnlock Amount of tokens that are immediately vested when the vesting starts.
	 * @param _cliffReleaseTimestamp The timestamp at which the cliff amount is released.
	 * @param _cliffAmount The amount of tokens released at the cliff.
	 * @param _releaseIntervalSecs The interval, in seconds, at which the linear vesting releases occur after the cliff.
	 * @param _linearVestAmount The total amount of tokens to be released linearly after the cliff has passed.
	 * @return vesting A struct representing the vesting schedule.
	 */
	function _createVesting(
		address _recipient,
		uint32 _startTimestamp,
		uint32 _endTimestamp,
		uint32 _timelock,
		uint256 _initialUnlock,
		uint32 _cliffReleaseTimestamp,
		uint256 _cliffAmount,
		uint32 _releaseIntervalSecs,
		uint256 _linearVestAmount
	) internal pure returns (TokenVestingLib.Vesting memory) {
		if (_linearVestAmount + _cliffAmount == 0) {
			revert TokenVestingLib.invalidVestedAmount();
		}
		if (_startTimestamp == 0) {
			revert TokenVestingLib.invalidStartTimestamp();
		}
		if (_startTimestamp > _endTimestamp) {
			revert TokenVestingLib.invalidEndTimestamp();
		}
		if (_releaseIntervalSecs == 0) {
			revert TokenVestingLib.invalidReleaseInterval();
		}
		if (_cliffReleaseTimestamp != 0 && _cliffAmount == 0) {
			revert TokenVestingLib.invalidVestedAmount();
		}
		if (_cliffReleaseTimestamp == 0 && _cliffAmount != 0) {
			revert TokenVestingLib.invalidVestedAmount();
		}
		if (_cliffReleaseTimestamp != 0) {
			if (
				(_endTimestamp - _cliffReleaseTimestamp) %
					_releaseIntervalSecs !=
				0
			) {
				revert TokenVestingLib.invalidIntervalLength();
			}
		} else {
			if ((_endTimestamp - _startTimestamp) % _releaseIntervalSecs != 0) {
				revert TokenVestingLib.invalidIntervalLength();
			}
		}

		if (
			((_startTimestamp > _cliffReleaseTimestamp) ||
				(_cliffReleaseTimestamp >= _endTimestamp)) && _cliffAmount != 0
		) {
			revert invalidCliffReleaseTimestamp();
		}

		if ((_startTimestamp > _timelock && _timelock != 0)) {
			revert invalidUnlockTimestamp();
		}

		TokenVestingLib.Vesting memory vesting = TokenVestingLib.Vesting({
			recipient: _recipient,
			startTimestamp: _startTimestamp,
			endTimestamp: _endTimestamp,
			deactivationTimestamp: 0,
			timelock: _timelock,
			initialUnlock: _initialUnlock,
			cliffReleaseTimestamp: _cliffReleaseTimestamp,
			cliffAmount: _cliffAmount,
			releaseIntervalSecs: _releaseIntervalSecs,
			linearVestAmount: _linearVestAmount,
			claimedAmount: 0
		});
		return vesting;
	}

	/// ADMIN WITHDRAW HELPER FUNCTIONS

	/**
	 * @notice Allow the owner to withdraw any balance not currently tied up in Vestings
	 * @param _amountRequested - Amount to withdraw
	 */
	function withdrawAdmin(uint256 _amountRequested) external onlyAdmin {
		uint256 amountRemaining = amountAvailableToWithdrawByAdmin();
		if (amountRemaining < _amountRequested) {
			revert insufficientBalance();
		}

		emit AdminWithdrawn(msg.sender, _amountRequested);
		IERC20(tokenAddress).safeTransfer(msg.sender, _amountRequested);
	}

	/**
	 * @notice Withdraw a token which isn't controlled by the vesting contract. Useful when someone accidentally sends tokens to the contract
	 * @param _otherTokenAddress - the token which we want to withdraw
	 */
	function withdrawOtherToken(address _otherTokenAddress) external onlyAdmin {
		if (_otherTokenAddress == tokenAddress) {
			// tokenAddress address is already sure to be nonzero due to constructor
			revert invalidToken();
		}
		uint256 balance = IERC20(_otherTokenAddress).balanceOf(address(this));
		IERC20(_otherTokenAddress).safeTransfer(msg.sender, balance);
	}

	/// @notice Amount of tokens available to withdraw by the admin∂
	function amountAvailableToWithdrawByAdmin() public view returns (uint256) {
		return
			IERC20(tokenAddress).balanceOf(address(this)) -
			numTokensReservedForVesting;
	}

	/**
	 * @notice Check if a recipient has milestones
	 * @param recipient - The recipient address
	 * @return isRecipient - True if the recipient has milestones
	 */
	function isRecipient(address recipient) public view returns (bool) {
		return recipientMilestones[recipient].length != 0;
	}

	/**
	 * @notice Get all recipients
	 * @return recipients - The list of recipients
	 */
	function getAllRecipients() external view returns (address[] memory) {
		return recipients;
	}

	/**
	 * @notice Get all recipients in a range
	 * @param _from - The start index (inclusive)
	 * @param _to - The end index (exclusive)
	 * @return recipientsSliced - The list of recipients in the range
	 */
	function getAllRecipientsSliced(
		uint256 _from,
		uint256 _to
	) external view returns (address[] memory) {
		address[] memory recipientsSliced = new address[](_to - _from);
		for (uint256 i = _from; i < _to; ) {
			recipientsSliced[i - _from] = recipients[i];
			unchecked {
				++i;
			}
		}
		return recipientsSliced;
	}

	/**
	 * @notice Get the length of all recipients
	 * @return length - The length of all recipients
	 */
	function getAllRecipientsLength() external view returns (uint256) {
		return recipients.length;
	}

	/**
	 * @notice Get the milestone by ID
	 * @param milestoneId - The ID of the milestone
	 * @return milestone - The milestone object
	 */
	function getMilestoneById(
		bytes32 milestoneId
	) external view returns (Milestone memory) {
		return milestonesById[milestoneId];
	}

	/**
	 * @notice Get the milestone step by index
	 * @param milestoneId - The ID of the milestone
	 * @param stepIndex - The index of the step
	 * @return milestoneStep - The milestone step object
	 */
	function getMilestoneStep(
		bytes32 milestoneId,
		uint256 stepIndex
	) external view returns (MilestoneStep memory) {
		return milestonesById[milestoneId].steps[stepIndex];
	}

	/**
	 * @notice Get all milestone steps
	 * @param milestoneId - The ID of the milestone
	 * @return steps - The milestone steps
	 */
	function getAllMilestoneSteps(
		bytes32 milestoneId
	) external view returns (MilestoneStep[] memory) {
		return milestonesById[milestoneId].steps;
	}

	/**
	 * @notice Get the length of all milestone steps
	 * @param milestoneId - The ID of the milestone
	 * @return length - The length of all milestone steps
	 */
	function getAllMilestoneStepsLength(
		bytes32 milestoneId
	) external view returns (uint256) {
		return milestonesById[milestoneId].steps.length;
	}

	/**
	 * @notice Get all milestone steps in a range
	 * @param milestoneId - The ID of the milestone
	 * @param _from - The start index (inclusive)
	 * @param _to - The end index (exclusive)
	 * @return stepsSliced - The milestone steps in the range
	 */
	function getAllMilestoneStepsSliced(
		bytes32 milestoneId,
		uint256 _from,
		uint256 _to
	) external view returns (MilestoneStep[] memory) {
		MilestoneStep[] memory stepsSliced = new MilestoneStep[](_to - _from);
		for (uint256 i = _from; i < _to; ) {
			stepsSliced[i - _from] = milestonesById[milestoneId].steps[i];
			unchecked {
				++i;
			}
		}
		return stepsSliced;
	}

	/**
	 * @notice Get the milestones of a recipient
	 * @param _recipient - The recipient address
	 * @return recipientMilestones - The milestones of the recipient
	 */
	function getRecipientMilestones(
		address _recipient
	) external view returns (bytes32[] memory) {
		return recipientMilestones[_recipient];
	}

	/**
	 * @notice Get the length of the milestones of a recipient
	 * @param _recipient - The recipient address
	 * @return length - The length of the milestones of the recipient
	 */
	function getRecipientMilestonesLength(
		address _recipient
	) external view returns (uint256) {
		return recipientMilestones[_recipient].length;
	}

	/**
	 * @notice Get the milestones of a recipient in a range
	 * @param _recipient - The recipient address
	 * @param _from - The start index (inclusive)
	 * @param _to - The end index (exclusive)
	 * @return milestonesSliced - The milestones of the recipient in the range
	 */
	function getRecipientMilestonesSliced(
		address _recipient,
		uint256 _from,
		uint256 _to
	) external view returns (bytes32[] memory) {
		bytes32[] memory milestonesSliced = new bytes32[](_to - _from);
		for (uint256 i = _from; i < _to; ) {
			milestonesSliced[i - _from] = recipientMilestones[_recipient][i];
			unchecked {
				++i;
			}
		}
		return milestonesSliced;
	}
}

contracts/factories/MilestoneManagerFactory.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

import { Create2 } from "@openzeppelin/contracts/utils/Create2.sol";
import { IMilestoneManagerFactory } from "../interfaces/IMilestoneManagerFactory.sol";
import { MilestoneManager } from "../MilestoneManager.sol";

/// @title MilestoneManager Factory
/// @notice Allows anyone to reliably deploy a new `MilestoneManager` contract.
contract MilestoneManagerFactory is IMilestoneManagerFactory {
	/// @notice Creates a new MilestoneManager instance
	/// @param tokenAddress The address of the ERC20 token to be used in the MilestoneManager
	/// @return address The address of the newly created MilestoneManager contract
	function newMilestoneManager(
		address tokenAddress
	) external override returns (MilestoneManager) {
		MilestoneManager milestoneManager = new MilestoneManager(tokenAddress);

		emit MilestoneManagerCreated(milestoneManager);
		milestoneManager.setAdmin(msg.sender, true);
		milestoneManager.setAdmin(address(this), false);
		return milestoneManager;
	}
}

contracts/factories/TokenVestingManagerFactory.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

import { Create2 } from "@openzeppelin/contracts/utils/Create2.sol";
import { ITokenVestingManagerFactory } from "../interfaces/ITokenVestingManagerFactory.sol";
import { TokenVestingManager } from "../TokenVestingManager.sol";

/// @title TokenVestingManager Factory
/// @notice Allows anyone to reliably deploy a new `TokenVestingManager` contract using deterministic addresses.
contract TokenVestingManagerFactory is ITokenVestingManagerFactory {
	/// @notice Creates a new TokenVestingManager instance
	/// @param tokenAddress The address of the ERC20 token to be used in the TokenVestingManager
	/// @return The address of the newly created TokenVestingManager contract
	function newTokenVestingManager(
		address tokenAddress
	) external override returns (TokenVestingManager) {
		TokenVestingManager tokenVestingManager = new TokenVestingManager(
			tokenAddress
		);

		emit TokenVestingManagerCreated(tokenVestingManager);
		tokenVestingManager.setAdmin(msg.sender, true);
		tokenVestingManager.setAdmin(address(this), false);
		return tokenVestingManager;
	}
}

contracts/factories/VestedMilestoneManagerFactory.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

import { Create2 } from "@openzeppelin/contracts/utils/Create2.sol";
import { IVestedMilestoneManagerFactory } from "../interfaces/IVestedMilestoneManagerFactory.sol";
import { VestedMilestoneManager } from "../VestedMilestoneManager.sol";

/// @title VestedMilestoneManager Factory
/// @notice Allows anyone to reliably deploy a new `VestedMilestoneManager` contract.
contract VestedMilestoneManagerFactory is IVestedMilestoneManagerFactory {
	function newVestedMilestoneManager(
		address tokenAddress
	) external override returns (VestedMilestoneManager) {
		VestedMilestoneManager vestedMilestoneManager = new VestedMilestoneManager(
				tokenAddress
			);

		emit VestedMilestoneManagerCreated(vestedMilestoneManager);
		vestedMilestoneManager.setAdmin(msg.sender, true);
		vestedMilestoneManager.setAdmin(address(this), false);
		return vestedMilestoneManager;
	}
}

contracts/interfaces/IMilestoneManager.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

import "../MilestoneManager.sol";

/// @title Interface for the MilestoneManager
/// @notice Provides external functionalities of the MilestoneManager contract for managing project milestones with token allocations
interface IMilestoneManager {
	/// @notice Emitted when a new milestone is successfully created
	/// @param milestoneId Unique identifier of the milestone
	/// @param recipient Address of the milestone's recipient
	event MilestoneCreated(
		bytes32 indexed milestoneId,
		address indexed recipient,
		uint256 allocation
	);

	/// @notice Emitted when a milestone is revoked
	/// @param milestoneId Unique identifier of the milestone that was revoked
	event MilestoneApproved(bytes32 indexed milestoneId, uint256 step);

	/// @notice Emitted when tokens are claimed from a milestone
	/// @param milestoneId Unique identifier of the milestone from which tokens are claimed
	/// @param amount Amount of tokens claimed
	event MilestoneClaimed(
		bytes32 indexed milestoneId,
		address indexed recipient,
		uint256 amount
	);

	event MilestoneRevoked(
		bytes32 indexed milestoneId,
		address indexed recipient,
		uint256 amount
	);

	event MilestoneStepRevoked(
		bytes32 indexed milestoneId,
		uint256 indexed stepIndex,
		address indexed recipient,
		uint256 amount
	);

	/// @notice Emitted when an admin withdraws tokens not tied up in vesting
	/// @param recipient Address of the recipient (admin) making the withdrawal
	/// @param amountRequested Amount of tokens withdrawn by the admin
	event AdminWithdrawn(address indexed recipient, uint256 amountRequested);

	error MilestoneAlreadyExists(bytes32 milestoneId);
	error MilestoneNotActive();
	error InsufficientManagerBalance();
	error NotMilestoneOwner();
	error InvalidParameters();
	error invalidAddress();
	error invalidZeroAddress();
	error arrayLengthMismatch();
	error insufficientBalance();
	error milestoneNotExists();
	error invalidStepIndex();
	error stepAlreadyApproved();
	error invalidToken();
	error milestoneAlreadyRevoked();
	error stepAlreadyRevoked();
	error RevokedMilestone();
	error MilestoneStepIsRevoked();

	/// @notice Create a milestone for a recipient with specific allocations
	/// @param recipient The recipient's address
	/// @param allocations Array of token amounts allocated for each milestone step
	/// @param approvals Array of approval statuses corresponding to each milestone step
	/// @param externalRefs Array of external references or identifiers for each milestone step
	function createMilestone(
		address recipient,
		uint256[] memory allocations,
		bool[] memory approvals,
		string[] memory externalRefs
	) external returns (bytes32);

	/// @notice Allows a recipient to claim their allocated tokens from an active milestone
	/// @param milestoneId The unique identifier of the milestone to claim from
	function claim(bytes32 milestoneId) external;

	/// @notice Approves a milestone, preventing further token claims
	/// @param milestoneId The unique identifier of the milestone to be revoked
	function approveMilestone(bytes32 milestoneId, uint256 step) external;

	function getMilestoneById(
		bytes32 milestoneId
	) external view returns (MilestoneManager.Milestone memory);

	/// @notice Retrieves a list of all recipients who have one or more milestones
	/// @return An array of addresses of recipients
	function getAllRecipients() external view returns (address[] memory);

	/// @notice Retrieves all milestone identifiers associated with a specific recipient
	/// @param recipient Address of the recipient
	/// @return An array of milestone identifiers
	function getRecipientMilestones(
		address recipient
	) external view returns (bytes32[] memory);

	/// @notice Checks if a given address is a recipient of any milestone schedule
	/// @param recipient The address to check against the list of milestone schedule recipients.
	function isRecipient(address recipient) external view returns (bool);
}

contracts/interfaces/IMilestoneManagerFactory.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { MilestoneManager } from "../MilestoneManager.sol";

/// @title The MilestoneManager Factory Interface
/// @notice The Factory facilitates the creation of MilestoneManager instances.
interface IMilestoneManagerFactory {
	/// @notice Emitted when a new MilestoneManager is created
	/// @param milestone The address of the newly created MilestoneManager
	event MilestoneManagerCreated(MilestoneManager milestone);

	/// @notice Creates a new MilestoneManager instance
	/// @param tokenAddress The ERC20 token address to be managed by the MilestoneManager
	/// @return The address of the newly created MilestoneManager
	function newMilestoneManager(
		address tokenAddress
	) external returns (MilestoneManager);
}

contracts/interfaces/ITokenVestingManager.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

import "../libraries/TokenVestingLib.sol";

/// @title Interface for the TokenVestingManager contract
/// @notice Provides the external functions of the TokenVestingManager contract for managing token vesting schedules
interface ITokenVestingManager {
	struct CreateVestingBatchParams {
		address[] _recipients;
		uint32[] _startTimestamps;
		uint32[] _endTimestamps;
		uint32[] _timelocks;
		uint256[] _initialUnlocks;
		uint32[] _cliffReleaseTimestamps;
		uint256[] _cliffAmounts;
		uint32[] _releaseIntervalSecs;
		uint256[] _linearVestAmounts;
	}

	/// @notice Emitted when a new vesting is created
	/// @param recipient Address of the vesting recipient
	/// @param vesting Details of the created vesting
	event VestingCreated(
		address indexed recipient,
		bytes32 vestingId,
		TokenVestingLib.Vesting vesting
	);

	/// @notice Emitted when a claim is made by a vesting recipient
	/// @param recipient Address of the recipient making the claim
	/// @param withdrawalAmount Amount of tokens withdrawn in the claim
	/// @param vestingId Unique identifier of the recipient's vesting arrangement
	event Claimed(
		address indexed recipient,
		uint256 withdrawalAmount,
		bytes32 vestingId
	);

	/// @notice Emitted when a vesting is revoked
	/// @param recipient Address of the recipient whose vesting was revoked
	/// @param numTokensWithheld Amount of tokens withheld during the revocation
	/// @param vesting Details of the revoked vesting
	event VestingRevoked(
		address indexed recipient,
		uint256 numTokensWithheld,
		TokenVestingLib.Vesting vesting
	);

	/// @notice Emitted when an admin withdraws tokens not tied up in vesting
	/// @param recipient Address of the recipient (admin) making the withdrawal
	/// @param amountRequested Amount of tokens withdrawn by the admin
	event AdminWithdrawn(address indexed recipient, uint256 amountRequested);

	error vestingAlreadyExists(bytes32 vestingId);
	error vestingNotActive();
	error insuficientManagerBalance();
	error notVestingOwner();
	error invalidZeroAddress();
	error insufficientBalance();
	error arrayLengthMismatch();
	error allVestedAmountAlreadyClaimed();
	error invalidToken();

	/// @notice Create a vesting schedule for a recipient
	/// @param _recipient Address of the recipient for whom vesting is being created
	/// @param _startTimestamp Start time of the vesting period as a timestamp
	/// @param _endTimestamp End time of the vesting period as a timestamp
	/// @param _timelock Period during which the tokens are locked and cannot be claimed
	/// @param _initialUnlock Amount of tokens that are initially unlocked and claimable at the start time
	/// @param _cliffReleaseTimestamp Timestamp after which the cliff amount can be released
	/// @param _cliffAmount Amount of tokens that are released at once after the cliff period is reached
	/// @param _releaseIntervalSecs Interval in seconds between subsequent releases
	/// @param _linearVestAmount Total amount of tokens that will be vested linearly after the cliff
	function createVesting(
		address _recipient,
		uint32 _startTimestamp,
		uint32 _endTimestamp,
		uint32 _timelock,
		uint256 _initialUnlock,
		uint32 _cliffReleaseTimestamp,
		uint256 _cliffAmount,
		uint32 _releaseIntervalSecs,
		uint256 _linearVestAmount
	) external returns (bytes32 vestingId);

	/// @notice Create vesting schedules in batch for multiple recipients
	// @param _recipients Array of addresses for whom the vesting is being created
	// @param _startTimestamps Array of start timestamps for each vesting
	// @param _endTimestamps Array of end timestamps for each vesting
	// @param _timelocks Array of timelocks for each vesting
	// @param _initialUnlocks Array of amounts that are initially unlocked for each vesting
	// @param _cliffReleaseTimestamps Array of timestamps after which the cliff amounts can be released for each vesting
	// @param _cliffAmounts Array of cliff amounts for each vesting
	// @param _releaseIntervalSecs Array of intervals in seconds between subsequent releases for each vesting
	// @param _linearVestAmounts Array of total amounts of tokens that will be vested linearly after the cliff for each vesting
	function createVestingBatch(
		CreateVestingBatchParams memory params
	) external returns (bytes32[] memory);

	/// @notice Allows a recipient to claim their vested tokens
	/// @param vestingId Unique identifier of the recipient's vesting arrangement
	function claim(bytes32 vestingId) external;

	/// @notice Revokes a vesting arrangement before it has been fully claimed
	/// @param vestingId Unique identifier of the vesting to be revoked
	function revokeVesting(bytes32 vestingId) external;

	/// @notice Allows the admin to withdraw ERC20 tokens not locked in vesting
	/// @param amountRequested Amount of tokens the admin wishes to withdraw
	function withdrawAdmin(uint256 amountRequested) external;

	/// @notice Withdraws ERC20 tokens accidentally sent to the contract's address
	/// @param otherTokenAddress Address of the token to be withdrawn
	function withdrawOtherToken(address otherTokenAddress) external;

	/// @notice Returns the amount of tokens that are available for the admin to withdraw
	/// @return The amount of tokens available to withdraw
	function amountAvailableToWithdrawByAdmin() external view returns (uint256);

	/// @notice Retrieves information about a specific vesting arrangement
	/// @param _vestingId Unique identifier of the vesting
	/// @return Details of the specified vesting
	function getVestingInfo(
		bytes32 _vestingId
	) external view returns (TokenVestingLib.Vesting memory);

	/// @notice Fetches a list of all recipient addresses who have at least one vesting schedule set up in the system
	/// @return An array of addresses, each representing a recipient with an active or historical vesting schedule.
	function getAllRecipients() external view returns (address[] memory);

	/// @notice Checks if a given address is a recipient of any vesting schedule
	/// @param recipient The address to check against the list of vesting schedule recipients.
	function isRecipient(address recipient) external view returns (bool);
}

contracts/interfaces/ITokenVestingManagerFactory.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;
import { TokenVestingManager } from "../TokenVestingManager.sol";

/// @title Interface for the TokenVestingManagerFactory
/// @notice Provides the functionality to deploy TokenVestingManager contracts deterministically using Create2.
interface ITokenVestingManagerFactory {
	/// @notice Emitted when a new TokenVestingManager is created
	/// @param tokenVestingManager The address of the newly created TokenVestingManager
	event TokenVestingManagerCreated(TokenVestingManager tokenVestingManager);

	/// @notice Deploys a new TokenVestingManager contract
	/// @param tokenAddress The ERC20 token address that will be vested by the newly created TokenVestingManager contract.
	/// @return The address of the newly created TokenVestingManager contract
	function newTokenVestingManager(
		address tokenAddress
	) external returns (TokenVestingManager);
}

contracts/interfaces/IVestedMilestoneManager.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

/// @title Interface for the Vested Milestone Manager
/// @notice Manages milestones that trigger token vesting schedules upon admin approval.
interface IVestedMilestoneManager {
	/// @notice Emitted when a new vested milestone is created
	/// @param vestedMilestoneId Unique identifier for the vested milestone
	/// @param recipient Address of the recipient associated with the milestone
	event VestedMilestoneCreated(
		bytes32 indexed vestedMilestoneId,
		address indexed recipient,
		uint256 allocation
	);

	/// @notice Emitted when a milestone step is approved
	/// @param vestedMilestoneId Unique identifier for the vested milestone
	/// @param stepIndex Index of the step within the milestone that was approved
	event VestedMilestoneStepApproved(
		bytes32 indexed vestedMilestoneId,
		uint256 stepIndex
	);

	/// @notice Emitted when vesting for a milestone step is initialized
	/// @param milestoneId Unique identifier of the milestone
	/// @param stepIndex Index of the step within the milestone
	event VestingInitialized(bytes32 indexed milestoneId, uint256 stepIndex);

	/// @notice Emitted when tokens are claimed from a milestone step
	/// @param recipient Address of the recipient claiming the tokens
	/// @param amount Amount of tokens claimed
	/// @param stepIndex Index of the step from which tokens were claimed
	event Claimed(address indexed recipient, uint256 amount, uint256 stepIndex);

	/// @notice Emitted when an admin withdraws tokens not tied up in vesting
	/// @param recipient Address of the recipient (admin) making the withdrawal
	/// @param amountRequested Amount of tokens withdrawn by the admin
	event AdminWithdrawn(address indexed recipient, uint256 amountRequested);

	event MilestoneStepRevoked(
		bytes32 indexed milestoneId,
		uint256 indexed stepIndex,
		address indexed recipient,
		uint256 amount
	);

	event MilestoneRevoked(
		bytes32 indexed milestoneId,
		address indexed recipient,
		uint256 amount
	);

	error insufficientBalance();
	error arrayLengthMismatch();
	error MilestoneAlreadyExists(bytes32 milestoneId);
	error milestoneNotExists();
	error invalidStepIndex();
	error notVestingOwner();
	error invalidZeroAddress();
	error stepNotApproved();
	error stepAlreadyApproved();
	error invalidCliffReleaseTimestamp();
	error invalidUnlockTimestamp();
	error startTimestampNotReached();
	error invalidToken();
	error MilestoneStepIsRevoked();
	error MilestoneIsRevoked();
	error milestoneAlreadyRevoked();
	error stepAlreadyRevoked();
	error vestingAlreadyEnded();

	/// @notice Creates a new milestone with multiple steps
	/// @param _recipient Address of the milestone recipient
	/// @param _allocations Array of token amounts allocated to each milestone step
	/// @param _externalRefs Array of external references or identifiers for each milestone step
	function createMilestone(
		address _recipient,
		uint256[] memory _allocations,
		string[] memory _externalRefs
	) external returns (bytes32);

	/// @notice Approves a milestone step and optionally initializes its vesting schedule if not already set
	/// @param _milestoneId Unique identifier of the milestone
	/// @param _stepIndex Index of the step within the milestone to be approved
	/// @param _startTimestamp Vesting start time as a Unix timestamp
	/// @param _endTimestamp Vesting end time as a Unix timestamp
	/// @param _timelock Duration in seconds during which tokens cannot be claimed
	/// @param _initialUnlock Amount of tokens immediately claimable after the start time
	/// @param _cliffReleaseTimestamp Timestamp after which the cliff amount can be claimed
	/// @param _cliffAmount Amount of tokens available to claim after the cliff is reached
	/// @param _releaseIntervalSecs Interval in seconds between subsequent releases
	/// @param _linearVestAmount Total amount of tokens to be vested after the cliff period
	function approveMilestoneStep(
		bytes32 _milestoneId,
		uint256 _stepIndex,
		uint32 _startTimestamp,
		uint32 _endTimestamp,
		uint32 _timelock,
		uint256 _initialUnlock,
		uint32 _cliffReleaseTimestamp,
		uint256 _cliffAmount,
		uint32 _releaseIntervalSecs,
		uint256 _linearVestAmount
	) external;

	/// @notice Claims all available tokens for a specified milestone step
	/// @param milestoneId Unique identifier of the milestone
	/// @param stepIndex Index of the step within the milestone from which tokens are claimed
	function claim(bytes32 milestoneId, uint256 stepIndex) external;

	/// @notice Checks if an address is a recipient of any milestones
	/// @param recipient Address to check for milestone recipient status
	/// @return bool Returns true if the address has one or more associated milestones, otherwise false
	function isRecipient(address recipient) external view returns (bool);
}

contracts/interfaces/IVestedMilestoneManagerFactory.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

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

/// @title The VestedMilestoneManager Factory Interface
/// @notice The Factory facilitates the creation of VestedMilestoneManager instances.
interface IVestedMilestoneManagerFactory {
	/// @notice Emitted when a new VestedMilestoneManager is created
	/// @param vestedMilestone The address of the newly created VestedMilestoneManager
	event VestedMilestoneManagerCreated(VestedMilestoneManager vestedMilestone);

	/// @notice Creates a new VestedMilestoneManager instance
	/// @param tokenAddress The ERC20 token address to be managed by the VestedMilestoneManager
	/// @return The address of the newly created VestedMilestoneManager
	function newVestedMilestoneManager(
		address tokenAddress
	) external returns (VestedMilestoneManager);
}

contracts/libraries/AccessProtected.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

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

/** 
@title Access Limiter to multiple owner-specified accounts.
@dev Exposes the onlyAdmin modifier, which will revert (ADMIN_ACCESS_REQUIRED) if the caller is not the owner nor the admin.
@notice An address with the role admin can grant that role to or revoke that role from any address via the function setAdmin().
*/
abstract contract AccessProtected is Context {
	mapping(address => bool) private _admins; // user address => admin? mapping
	uint256 public adminCount;

	event AdminAccessSet(address indexed _admin, bool _enabled);

	constructor() {
		_admins[_msgSender()] = true;
		adminCount = 1;
		emit AdminAccessSet(_msgSender(), true);
	}

	/**
	 * Throws if called by any account that isn't an admin or an owner.
	 */
	modifier onlyAdmin() {
		require(_admins[_msgSender()], "ADMIN_ACCESS_REQUIRED");
		_;
	}

	function isAdmin(address _addressToCheck) external view returns (bool) {
		return _admins[_addressToCheck];
	}

	/**
	 * @notice Set/unset Admin Access for a given address.
	 *
	 * @param admin - Address of the new admin (or the one to be removed)
	 * @param isEnabled - Enable/Disable Admin Access
	 */
	function setAdmin(address admin, bool isEnabled) public onlyAdmin {
		require(admin != address(0), "INVALID_ADDRESS");
		require(
			_admins[admin] != isEnabled,
			"FLAG_ALREADY_PRESENT_FOR_ADDRESS"
		);

		if (isEnabled) {
			adminCount++;
		} else {
			require(adminCount > 1, "AT_LEAST_ONE_ADMIN_REQUIRED");
			adminCount--;
		}

		_admins[admin] = isEnabled;
		emit AdminAccessSet(admin, isEnabled);
	}
}

contracts/libraries/TokenVestingLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.18;

library TokenVestingLib {
	error invalidAddress();
	error invalidVestedAmount();
	error invalidStartTimestamp();
	error invalidEndTimestamp();
	error invalidReleaseInterval();
	error invalidIntervalLength();
	error invalidCliffRelease();
	error invalidCliffAmount();
	error timelockEnabled();

	/**
    @notice A structure representing a Vesting - supporting linear and cliff vesting.
	@param releaseIntervalSecs used for calculating the vested amount
	@param linearVestAmount vesting allocation, excluding cliff
	@param claimedAmount claimed so far, excluding cliff
    */

	struct Vesting {
		address recipient; // 160 bits 160/256 slot space - 1st slot
		uint32 startTimestamp; // 32 bits 192/256 slot space - 1st slot
		uint32 endTimestamp; // 32 bits  224/256 slot space - 1st slot
		uint32 deactivationTimestamp; // 32 bits 256/256 slot space - 1st slot
		uint32 timelock; // 32 bits 32/256 slot space - 2nd slot
		uint32 releaseIntervalSecs; // 32 bits 256/256 slot space - 2nd slot
		uint32 cliffReleaseTimestamp; // 32 bits 96/256 slot space - 2nd slot
		uint256 initialUnlock; // 256 bits 64/256 slot space - 3nd slot
		uint256 cliffAmount; // 256 bits 224/256 slot space - 4nd slots
		uint256 linearVestAmount; // 256 bits 256/256 slot space - 5rd slot // We could consider using uint128 here since we used 128 for cliffAmount
		uint256 claimedAmount; // 256 bits 256/256 slot space - 6th slot // We could consider using uint128 here since we used 128 for cliffAmount
	}

	/**
    @notice Calculate the vested amount for a given Vesting, at a given timestamp.
    @param _vesting The vesting in question
    @param _referenceTimestamp Timestamp for which we're calculating
     */
	function calculateVestedAmount(
		Vesting memory _vesting,
		uint32 _referenceTimestamp
	) internal pure returns (uint256) {
		// Does the Vesting exist?
		if (_vesting.deactivationTimestamp != 0) {
			if (_referenceTimestamp > _vesting.deactivationTimestamp) {
				_referenceTimestamp = _vesting.deactivationTimestamp;
			}
		}

		uint256 vestingAmount;

		// Has the Vesting ended?
		if (_referenceTimestamp > _vesting.endTimestamp) {
			_referenceTimestamp = _vesting.endTimestamp;
		}

		// Has the cliff passed?
		if (_referenceTimestamp >= _vesting.cliffReleaseTimestamp) {
			vestingAmount += _vesting.cliffAmount;
		}

		//Does it has an initial unlock?
		if (_vesting.initialUnlock > 0) {
			vestingAmount += _vesting.initialUnlock;
		}

		// Has the vesting started? If so, calculate the vested amount linearly
		uint256 startTimestamp;
		if (_vesting.cliffReleaseTimestamp != 0) {
			startTimestamp = _vesting.cliffReleaseTimestamp;
		} else {
			startTimestamp = _vesting.startTimestamp;
		}
		if (_referenceTimestamp > startTimestamp) {
			uint256 currentVestingDurationSecs = _referenceTimestamp -
				startTimestamp;

			// Round to releaseIntervalSecs
			uint256 truncatedCurrentVestingDurationSecs = (currentVestingDurationSecs /
					_vesting.releaseIntervalSecs) *
					_vesting.releaseIntervalSecs;

			uint256 finalVestingDurationSecs = _vesting.endTimestamp -
				startTimestamp;

			// Calculate vested amount
			uint256 linearVestAmount = (_vesting.linearVestAmount *
				truncatedCurrentVestingDurationSecs) / finalVestingDurationSecs;

			vestingAmount += linearVestAmount;
		}
		return vestingAmount;
	}

	function generateVestingId(
		Vesting memory _vesting
	) internal pure returns (bytes32) {
		return keccak256(abi.encode(_vesting));
	}
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.