ONVestingSub

Description:

ERC20 token contract with Mintable, Factory capabilities. Standard implementation for fungible tokens on Ethereum.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

// Sources flattened with hardhat v2.26.3 https://hardhat.org

// SPDX-License-Identifier: Apache-2.0 AND MIT

// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v5.4.0

// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}


// File @openzeppelin/contracts/interfaces/IERC20.sol@v5.4.0

// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;


// File contracts/interfaces/ONCommon.sol

// Original license: SPDX_License_Identifier: Apache-2.0
pragma solidity 0.8.26;

error TGENotStarted();
error TGEAlreadyStarted();
error InvalidAddress();

/**
 * @dev Struct to define vesting term
 */
struct VestingTerm {
    address beneficiary;
    uint64 cliff;
    uint64 vestingDuration;
    uint64 milestoneDuration;
    uint256 unlockedAtTGE;
    uint256 total;
}

/**
 * @dev Struct to store vesting schedule
 */
struct VestingSchedule {
    uint64 cliff;
    uint64 vestingDuration;
    uint64 milestoneDuration;
    uint64 milestoneClaimed;
    uint256 milestoneReleaseAmount;
    uint256 unlockedAtTGE;
    uint256 totalClaimed;
}

/**
 * @dev Struct to store vesting schedule
 */
struct VestingDetail {
    address contractAddress;
    address beneficiary;
    uint64 start;
    uint64 end;
    uint64 milestoneDuration;
    uint64 milestoneClaimed;
    uint256 milestoneReleaseAmount;
    uint256 unlockedAtTGE;
    uint256 totalClaimed;
    uint256 balanceClaimable;
    uint256 balanceRemain;
}

/**
 * @title Orochi Network Token Interface
 */
interface ONTokenInterface is IERC20 {
    // Custom public/external functions

    function mint() external returns (bool);

    // Ownership (from Ownable)

    function owner() external view returns (address);

    function transferOwnership(address newOwner) external;

    function renounceOwnership() external;
}

/**
 * @title Orochi Network Vesting Sub Interface
 */
interface ONVestingSubInterface {
    // Init
    function init(
        address onVestingMainAddress,
        VestingTerm calldata vestingTerm
    ) external returns (bool);

    // Beneficiary actions
    function claim() external;

    function emergency() external;

    function transferVestingContract(address beneficiaryNew) external;

    // Views
    function getBeneficiary() external view returns (address);

    function getTimeStart() external view returns (uint64);

    function getTimeEnd() external view returns (uint64);

    function getClaimableBalance() external view returns (uint256);

    function getRemainingBalance() external view returns (uint256);

    function getVestingDetail() external view returns (VestingDetail memory);
}

/**
 * @title Orochi Network Vesting Main Interface
 */
interface ONVestingMainInterface {
    // External functions
    function transfer(address to, uint256 value) external;

    function setTokenAddress(address tokenAddress) external;

    function setImplementation(address onVestingSubImpl) external;

    function setTimeTGE(uint256 timestampTGE) external;

    function mint() external;

    function addVestingTerm(VestingTerm calldata vestingTerm) external;

    // View functions
    function getImplementation() external view returns (address);

    function getTokenAddress() external view returns (address);

    function getTimeTGE() external view returns (uint256);

    function getVestingDetailList(
        uint256 offset,
        uint256 limit
    ) external view returns (VestingDetail[] memory);

    function getVestingContractAddress(
        uint256 index
    ) external view returns (address);

    function getVestingContractTotal() external view returns (uint256);

    function isTGE() external view returns (bool);
}


// File @openzeppelin/contracts/utils/ReentrancyGuard.sol@v5.4.0

// Original license: SPDX_License_Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @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 EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * 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;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    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
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

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

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

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


// File contracts/interfaces/ONVestingSubBaseInterface.sol

// Original license: SPDX_License_Identifier: Apache-2.0
pragma solidity 0.8.26;

/**
 * @title Orochi Network Vesting Main Base Interface
 */
interface ONVestingSubBaseInterface {
    // Errors
    error UnableToInitTwice();
    error InvalidBeneficiary(address beneficiary);
    error UnableToCallEmergency();
    error InvalidVestingSchedule(address beneficiary);
    error NoClaimableToken(address beneficiary, uint256 milestone);
    error InsufficientBalance(
        address beneficiary,
        uint256 balance,
        uint256 remaining
    );
    error UnableToRelease(
        address beneficiary,
        uint256 milestone,
        uint256 amount
    );
    error InvalidVestingTerm(address beneficiary);

    // Events
    event TransferVestingContract(address indexed from, address indexed to);
    event EmergencyWithdraw(address indexed to, uint256 value);
    event TokenClaimed(
        address indexed beneficiary,
        uint256 indexed milestone,
        uint256 indexed amount
    );
    event UnlockAtTGE(address indexed beneficiary, uint256 indexed amount);
}


// File contracts/ONVestingSubBase.sol

// Original license: SPDX_License_Identifier: Apache-2.0
pragma solidity 0.8.26;


/**
 * @title Orochi Network Vesting Sub Base
 */
contract ONVestingSubBase is ONVestingSubBaseInterface {
    // Beneficiary of the vesting contract
    address private beneficiary;

    // Main vesting contract address
    ONVestingMainInterface private onVestingMain;

    // Schedule of vesting
    VestingSchedule private schedule;

    uint64 immutable MAX_CLIFF = 365 days; // 12 months

    uint64 immutable MAX_MILESTONE_DURATION = 90 days; // 3 months

    uint64 immutable MAX_VESTING_DURATION = 365 days * 3; // 36 months

    /**
     * @dev Modifier to make sure that the TGE is started
     */
    modifier onlyPostTGE() {
        if (!onVestingMain.isTGE()) {
            revert TGENotStarted();
        }
        _;
    }

    /**
     * @dev Modifier to make sure that this contract wasn't initialized
     */
    modifier onlyOnce() {
        if (beneficiary != address(0)) {
            revert UnableToInitTwice();
        }
        _;
    }

    /**
     * @dev Modifier to make sure that the caller is the beneficiary of the vesting contract
     */
    modifier onlyBeneficiary() {
        if (msg.sender != beneficiary) {
            revert InvalidBeneficiary(msg.sender);
        }
        _;
    }

    /*******************************************************
     * Internal
     ********************************************************/

    /**
     * Init method
     * @param onVestingMainAddress The address of the main vesting contract
     * @param vestingTerm Vesting term
     */
    function _init(
        address onVestingMainAddress,
        VestingTerm calldata vestingTerm
    ) internal returns (bool) {
        if (
            onVestingMainAddress == address(0) ||
            vestingTerm.beneficiary == address(0)
        ) {
            revert InvalidAddress();
        }
        onVestingMain = ONVestingMainInterface(onVestingMainAddress);
        beneficiary = vestingTerm.beneficiary;
        emit TransferVestingContract(address(0), vestingTerm.beneficiary);
        _addVestingTerm(vestingTerm);
        return true;
    }

    /**
     * If token is vested but stuck in the smart contract
     * this method allow to withdraw all of them
     */
    function _emergency() internal {
        if (block.timestamp >= _timeEnd() + schedule.milestoneDuration) {
            VestingSchedule memory vestingSchedule = schedule;
            uint256 remaining = _getRemainingBalance();
            if (_getToken().transfer(beneficiary, remaining)) {
                vestingSchedule.totalClaimed += remaining;
                // Prevent division by zero
                if (
                    vestingSchedule.vestingDuration >=
                    vestingSchedule.milestoneDuration &&
                    vestingSchedule.milestoneDuration > 0
                ) {
                    vestingSchedule.milestoneClaimed =
                        vestingSchedule.vestingDuration /
                        vestingSchedule.milestoneDuration;
                }
                schedule = vestingSchedule;
                emit EmergencyWithdraw(beneficiary, remaining);
                return;
            }
        }
        revert UnableToCallEmergency();
    }

    /**
     * Transfer vesting contract to new owner
     * @param beneficiaryNew New vesting contract owner
     */
    function _transferVestingContract(address beneficiaryNew) internal {
        if (beneficiaryNew == address(0) || beneficiaryNew == beneficiary) {
            revert InvalidBeneficiary(beneficiaryNew);
        }
        emit TransferVestingContract(beneficiary, beneficiaryNew);
        beneficiary = beneficiaryNew;
    }

    /**
     * Claim tokens for a benefi account
     */
    function _claim(address account) internal {
        VestingSchedule memory vestingSchedule = schedule;

        // If there is no token then vesting schedule is invalid
        if (_getRemainingBalance() == 0) {
            revert InvalidVestingSchedule(account);
        }

        (uint64 milestone, uint256 amount) = _balance();

        // Check if there is any claimable token left
        if (amount == 0) {
            revert NoClaimableToken(account, milestone);
        }

        if (amount > _getRemainingBalance()) {
            revert InsufficientBalance(account, amount, _getRemainingBalance());
        }

        // Update the vesting schedule
        vestingSchedule.milestoneClaimed = milestone;
        vestingSchedule.totalClaimed += amount;
        schedule = vestingSchedule;

        if (!_getToken().transfer(account, amount)) {
            revert UnableToRelease(account, milestone, amount);
        }

        emit TokenClaimed(account, milestone, amount);
    }

    /**
     * Add a vesting term to the contract
     * @dev Only callable by the owner before TGE
     * @param term VestingTerm struct
     */
    function _addVestingTerm(VestingTerm calldata term) internal {
        if (term.total == term.unlockedAtTGE) {
            schedule = VestingSchedule({
                cliff: 0,
                vestingDuration: 0,
                milestoneDuration: 0,
                milestoneClaimed: 0,
                milestoneReleaseAmount: 0,
                unlockedAtTGE: term.unlockedAtTGE,
                totalClaimed: 0
            });
            // If the total amount is equal to the unlockedAtTGE then we can skip the vesting schedule
            emit UnlockAtTGE(term.beneficiary, term.unlockedAtTGE);
            return;
        }

        // Filter invalid terms
        // All token must not be unlocked immediatly
        // Mile stone duration <= 3 months
        // Cliff <= 12 months
        // Mile stone duration <= Vesting duration <= 36 months
        if (
            term.total > term.unlockedAtTGE &&
            term.milestoneDuration > 0 &&
            term.milestoneDuration <= MAX_MILESTONE_DURATION &&
            term.cliff <= MAX_CLIFF &&
            term.cliff <= term.vestingDuration &&
            term.vestingDuration >= term.milestoneDuration &&
            term.vestingDuration <= MAX_VESTING_DURATION
        ) {
            uint256 remaining = term.total - term.unlockedAtTGE;
            uint256 milestoneTotal = term.vestingDuration /
                term.milestoneDuration;
            uint256 milestoneReleaseAmount = remaining / milestoneTotal;

            // Calculate the amount to unlock at TGE
            if (term.unlockedAtTGE > 0) {
                emit UnlockAtTGE(term.beneficiary, term.unlockedAtTGE);
            }

            schedule = VestingSchedule({
                cliff: term.cliff,
                vestingDuration: term.vestingDuration,
                milestoneDuration: term.milestoneDuration,
                milestoneClaimed: 0,
                milestoneReleaseAmount: milestoneReleaseAmount,
                unlockedAtTGE: term.unlockedAtTGE,
                totalClaimed: 0
            });
            return;
        }
        revert InvalidVestingTerm(term.beneficiary);
    }

    /*******************************************************
     * Internal View
     ********************************************************/

    /**
     * Get beneficiary address
     */
    function _getBeneficiary() internal view returns (address) {
        return beneficiary;
    }

    /**
     * Claimable token balance of the given account
     */
    function _getClaimableBalance() internal view returns (uint256) {
        (, uint256 amount) = _balance();
        return amount;
    }

    /**
     * Get vesting schedule of the given account
     */
    function _getVestingDetail() internal view returns (VestingDetail memory) {
        VestingSchedule memory vestingSchedule = schedule;
        VestingDetail memory vestingDetail = VestingDetail({
            contractAddress: address(this),
            beneficiary: beneficiary,
            start: _timeStart(),
            end: _timeEnd(),
            milestoneDuration: vestingSchedule.milestoneDuration,
            milestoneClaimed: vestingSchedule.milestoneClaimed,
            milestoneReleaseAmount: vestingSchedule.milestoneReleaseAmount,
            unlockedAtTGE: vestingSchedule.unlockedAtTGE,
            totalClaimed: vestingSchedule.totalClaimed,
            balanceClaimable: _getClaimableBalance(),
            balanceRemain: _getRemainingBalance()
        });

        return vestingDetail;
    }

    /*******************************************************
     * Internal View
     ********************************************************/

    /**
     * Get ON token instance
     */
    function _getToken() internal view returns (ONTokenInterface) {
        return ONTokenInterface(onVestingMain.getTokenAddress());
    }

    /**
     * Start of vesting time
     */
    function _timeStart() internal view returns (uint64) {
        return uint64(onVestingMain.getTimeTGE() + schedule.cliff);
    }

    /**
     * End of vesting time
     */
    function _timeEnd() internal view returns (uint64) {
        return _timeStart() + schedule.vestingDuration;
    }

    /**
     * Vesting balance
     */
    function _getRemainingBalance() internal view returns (uint256) {
        return _getToken().balanceOf(address(this));
    }

    /**
     * Calculate balance of the given account and milestone
     * @return milestone Claimable milestone
     * @return amount Claimable amount
     */
    function _balance()
        internal
        view
        returns (uint64 milestone, uint256 amount)
    {
        VestingSchedule memory vestingSchedule = schedule;

        // Check for the normal vesting schedule where
        // the contract is a not vested immediately
        if (
            vestingSchedule.vestingDuration > 0 &&
            vestingSchedule.milestoneDuration > 0 &&
            vestingSchedule.vestingDuration >= vestingSchedule.milestoneDuration
        ) {
            // Calculate total milestones
            uint64 milestoneTotal = vestingSchedule.vestingDuration /
                vestingSchedule.milestoneDuration;
            uint64 currentTime = uint64(block.timestamp);

            // If this contract is fully vested,
            // We gonna return all remain token
            if (currentTime >= _timeEnd()) {
                return (milestoneTotal, _getRemainingBalance());
            }

            milestone = currentTime > _timeStart()
                ? ((currentTime - _timeStart()) /
                    vestingSchedule.milestoneDuration)
                : 0;
            // Milestone can't be greater than total milestones
            milestone = milestone >= milestoneTotal
                ? milestoneTotal
                : milestone;

            uint256 claimableAmount = milestone *
                vestingSchedule.milestoneReleaseAmount +
                vestingSchedule.unlockedAtTGE;
            if (claimableAmount > vestingSchedule.totalClaimed) {
                return (
                    milestone,
                    claimableAmount - vestingSchedule.totalClaimed
                );
            }
        } else if (
            vestingSchedule.unlockedAtTGE > 0 &&
            vestingSchedule.totalClaimed == 0
        ) {
            return (0, vestingSchedule.unlockedAtTGE);
        }
        return (0, 0);
    }
}


// File contracts/ONVestingSub.sol

// Original license: SPDX_License_Identifier: Apache-2.0
pragma solidity 0.8.26;



/**
 * @title Orochi Network Vesting Sub
 */
contract ONVestingSub is ONVestingSubBase, ReentrancyGuard {
    /*******************************************************
     * External Only Once
     ********************************************************/

    /**
     * Init method
     * @param onVestingMainAddress The address of the main vesting contract
     * @param vestingTerm Vesting term
     */
    function init(
        address onVestingMainAddress,
        VestingTerm calldata vestingTerm
    ) external onlyOnce nonReentrant returns (bool) {
        return _init(onVestingMainAddress, vestingTerm);
    }

    /*******************************************************
     * External Only Beneficiary, after TGE
     ********************************************************/

    /**
     * Claim tokens for the sender
     * @dev Only callable after TGE
     */
    function claim() external nonReentrant onlyPostTGE onlyBeneficiary {
        _claim(_getBeneficiary());
    }

    /**
     * If token is vested but stuck in the smart contract
     * this method allow to withdraw all of them
     * @dev Only callable after fully vested
     */
    function emergency() external nonReentrant onlyPostTGE onlyBeneficiary {
        _emergency();
    }

    /*******************************************************
     * External Only Beneficiary
     ********************************************************/

    /**
     * Transfer vesting contract to new owner
     * @param beneficiaryNew New vesting contract owner
     */
    function transferVestingContract(
        address beneficiaryNew
    ) external nonReentrant onlyBeneficiary {
        _transferVestingContract(beneficiaryNew);
    }

    /*******************************************************
     * External View
     ********************************************************/

    /**
     * Get beneficiary address
     */
    function getBeneficiary() external view returns (address) {
        return _getBeneficiary();
    }

    /**
     * Get start of vesting time
     */
    function getTimeStart() external view returns (uint64) {
        return _timeStart();
    }

    /**
     * Get end of vesting time
     */
    function getTimeEnd() external view returns (uint64) {
        return _timeEnd();
    }

    /**
     * Claimable token balance of the given account
     */
    function getClaimableBalance() external view returns (uint256) {
        return _getClaimableBalance();
    }

    /**
     * Vesting balance
     */
    function getRemainingBalance() external view returns (uint256) {
        return _getRemainingBalance();
    }

    /**
     * Get vesting schedule of the given account
     */
    function getVestingDetail() external view returns (VestingDetail memory) {
        return _getVestingDetail();
    }
}

Tags:
ERC20, Token, Mintable, Factory|addr:0xf16b8d1cea6a7596920c5f121c6f360add0baa27|verified:true|block:23595506|tx:0x0e9d4448da60eca7c68c69da859fbb7b95c5c478b744463814ec893b4c82a282|first_check:1760693040

Submitted on: 2025-10-17 11:24:00

Comments

Log in to comment.

No comments yet.