// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.23; import {Clone} from…
- User
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.23;
import {Clone} from '@solady/utils/Clone.sol'; import {Math} from '@openzeppelin/contracts/utils/math/Math.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import {IVestingEscrowFactory} from 'src/interfaces/IVestingEscrowFactory.sol'; import {IVestingEscrow} from 'src/interfaces/IVestingEscrow.sol'; import {IVotingAdaptor} from 'src/interfaces/IVotingAdaptor.sol';
contract VestingEscrow is IVestingEscrow, Clone { using SafeERC20 for IERC20; using Address for address; using Address for address payable;
/// @notice The factory that created this VestingEscrow instance. function factory() public pure returns (IVestingEscrowFactory) { return IVestingEscrowFactory(_getArgAddress(0)); } /// @notice The token. function token() public pure returns (IERC20) { return IERC20(_getArgAddress(20)); } /// @notice The token recipient. function recipient() public pure returns (address) { return _getArgAddress(40); } /// @notice The vesting start timestamp. function startTime() public pure returns (uint40) { return _getArgUint40(60); } /// @notice The vesting end timestamp. function endTime() public pure returns (uint40) { return _getArgUint40(65); } /// @notice The vesting cliff length. function cliffLength() public pure returns (uint40) { return _getArgUint40(70); } /// @notice The total amount of tokens locked. function totalLocked() public pure returns (uint256) { return _getArgUint256(75); } /// @notice The total amount of tokens that have been claimed. uint256 public totalClaimed; /// @notice The vesting end time or the time at which vesting was revoked. uint40 public disabledAt; /// @notice Whether vesting is fully revokable. bool public isFullyRevokable; /// @notice Whether vesting has been fully revoked. bool public isFullyRevoked; /// @notice Throws if called by any account other than the owner. modifier onlyOwner() { _checkOwner(); _; } /// @notice Throws if called by any account other than the owner or manager. modifier onlyOwnerOrManager() { _checkOwnerOrManager(); _; } /// @notice Throws if called by any account other than the recipient. modifier onlyRecipient() { _checkRecipient(); _; } /// @notice Throws if the voting adaptor is not set. modifier whenVotingAdaptorIsSet() { _checkVotingAdaptorIsSet(); _; } /// @notice Initializes the contract. /// @param _isFullyRevokable Whether the tokens are fully revokable. /// @param _initialDelegateParams The optional initial delegate information (skipped if empty bytes). function initialize(bool _isFullyRevokable, bytes calldata _initialDelegateParams) external { address _factory = address(factory()); uint256 _totalLocked = totalLocked(); uint40 _endTime = endTime(); IERC20 _token = token(); if (msg.sender != _factory) revert NOT_FACTORY(msg.sender); if (_token.balanceOf(address(this)) < _totalLocked) revert INSUFFICIENT_BALANCE(); disabledAt = _endTime; // Set to maximum time isFullyRevokable = _isFullyRevokable; if (_initialDelegateParams.length != 0) _delegate(_initialDelegateParams); emit VestingEscrowInitialized( _factory, recipient(), address(_token), _totalLocked, startTime(), _endTime, cliffLength(), _isFullyRevokable ); } /// @notice Get the number of unclaimed, vested tokens for recipient. function unclaimed() public view returns (uint256) { if (isFullyRevoked) return 0; uint256 claimTime = Math.min(block.timestamp, disabledAt); return _totalVestedAt(claimTime) - totalClaimed; } /// @notice Get the number of locked tokens for recipient. function locked() public view returns (uint256) { if (block.timestamp >= disabledAt) return 0; return totalLocked() - _totalVestedAt(block.timestamp); } /// @notice Claim tokens which have vested. /// @param beneficiary Address to transfer claimed tokens to. /// @param amount Amount of tokens to claim. function claim(address beneficiary, uint256 amount) external onlyRecipient returns (uint256) { uint256 claimable = Math.min(unclaimed(), amount); totalClaimed += claimable; token().safeTransfer(beneficiary, claimable); emit Claim(beneficiary, claimable); return claimable; } /// @notice Delegate voting power of all available tokens. /// @param params The ABI-encoded delegate params. function delegate(bytes calldata params) external onlyRecipient returns (bytes memory) { return _delegate(params); } /// @notice Participate in a governance vote using all available tokens on the contract's balance. /// @param params The ABI-encoded data for call. Can be obtained from VotingAdaptor.encodeVoteCalldata. function vote(bytes calldata params) external onlyRecipient whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.vote, (params))); } // forgefmt: disable-next-item /// @notice Participate in a governance vote with a reason using all available tokens on the contract's balance. /// @param params The ABI-encoded data for call. Can be obtained from VotingAdaptor.encodeVoteWithReasonCalldata. function voteWithReason(bytes calldata params) external onlyRecipient whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.voteWithReason, (params))); } /// @notice Disable further flow of tokens and revoke the unvested part to owner. function revokeUnvested() external onlyOwnerOrManager { uint256 revokable = locked(); if (revokable == 0) revert NOTHING_TO_REVOKE(); disabledAt = uint40(block.timestamp); token().safeTransfer(_owner(), revokable); emit UnvestedTokensRevoked(msg.sender, revokable); } /// @notice Disable further flow of tokens and revoke all tokens to owner. function revokeAll() external onlyOwner { if (!isFullyRevokable) revert NOT_FULLY_REVOKABLE(); if (isFullyRevoked) revert ALREADY_FULLY_REVOKED(); uint256 revokable = locked() + unclaimed(); if (revokable == 0) revert NOTHING_TO_REVOKE(); isFullyRevoked = true; disabledAt = uint40(block.timestamp); token().safeTransfer(_owner(), revokable); emit VestingFullyRevoked(msg.sender, revokable); } /// @notice Permanently disable full token revocation. function permanentlyDisableFullRevocation() external onlyOwner { if (!isFullyRevokable) revert NOT_FULLY_REVOKABLE(); isFullyRevokable = false; emit FullRevocationPermanentlyDisabled(msg.sender); } /// @notice Recover any ERC20 token to the recipient. /// @param token_ Address of the ERC20 token to recover. /// @param amount Amount of tokens to recover. function recoverERC20(address token_, uint256 amount) external { uint256 recoverable = amount; if (token_ == address(token())) { uint256 available = token().balanceOf(address(this)) - (locked() + unclaimed()); recoverable = Math.min(recoverable, available); } if (recoverable > 0) { IERC20(token_).safeTransfer(recipient(), recoverable); emit ERC20Recovered(token_, recoverable); } } /// @notice Recover any ETH to the recipient. function recoverEther() external { uint256 amount = address(this).balance; if (amount > 0) { payable(recipient()).sendValue(amount); emit ETHRecovered(amount); } } /// @dev Returns the factory owner. function _owner() internal view returns (address) { return factory().owner(); } /// @dev Returns the factory manager. function _manager() internal view returns (address) { return factory().manager(); } /// @dev Returns the factory voting adaptor. function _votingAdaptor() internal view returns (address) { return factory().votingAdaptor(); } /// @dev Throws if called by any account other than the owner. function _checkOwner() internal view { if (msg.sender != _owner()) { revert NOT_OWNER(msg.sender); } } /// @dev Throws if called by any account other than the owner or manager. function _checkOwnerOrManager() internal view { if (msg.sender != _owner() && msg.sender != _manager()) { revert NOT_OWNER_OR_MANAGER(msg.sender); } } /// @dev Throws if called by any account other than the recipient. function _checkRecipient() internal view { if (msg.sender != recipient()) { revert NOT_RECIPIENT(msg.sender); } } /// @dev Throws if the voting adaptor is not set. function _checkVotingAdaptorIsSet() internal view { if (_votingAdaptor() == address(0)) { revert VOTING_ADAPTOR_NOT_SET(); } } /// @notice Delegate voting power of all available tokens. /// @param params The ABI-encoded delegate params. function _delegate(bytes calldata params) internal whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.delegate, params)); } /// @dev Returns the vested token amount at a specific time. /// @param time The time to retrieve the vesting amount for. function _totalVestedAt(uint256 time) internal pure returns (uint256) { uint40 _startTime = startTime(); uint256 _totalLocked = totalLocked(); if (time < _startTime + cliffLength()) { return 0; } return Math.min(_totalLocked * (time - _startTime) / (endTime() - _startTime), _totalLocked); }} FOR VULNERABILITIES This contract seems to handle the vesting of tokens, with features for claiming vested tokens, revoking unvested tokens, and participating in governance votes. identifying the main components and their interactions. What are the key functions and entities TO FIND VALID ISSUE
- Assistant
To evaluate potential vulnerabilities in the given smart contract, we will first identify its key functions and components and then step through each of them for a security assessment.
Key Functions and Entities
-
Vesting Mechanics:
- The contract defines a vesting process for
IERC20tokens, from astartTimeto anendTime, with a possiblecliffLength. - The
totalLockedrepresents the number of tokens locked in the contract for the vesting process. - The
totalClaimedkeeps track of tokens already claimed by the recipient.
- The contract defines a vesting process for
-
Access Control Modifiers:
onlyOwnerensures that certain functions can only be called by the owner (presumably, the deploying entity or its delegate).onlyOwnerOrManagerextends the privileges to include a manager role.onlyRecipientrestricts some functions to the recipient of the vested tokens.
-
Revocation Mechanisms:
- The contract allows for revocation of tokens that are not vested (
revokeUnvested) and, if the vesting is marked asisFullyRevokable, all tokens (revokeAll).
- The contract allows for revocation of tokens that are not vested (
-
Governance Participation:
- Through a
votingAdaptor, the recipient is allowed to delegate voting power or participate in votes directly (vote,voteWithReason), as long as the address of thevotingAdaptoris set.
- Through a
-
Recovery Mechanics:
recoverERC20andrecoverEtherfunctions allow recovery of tokens or ETH sent to the contract by mistake.
-
Initialization Step:
initializemethod is called to set up the vesting specifics after the contract is cloned from a factory.
-
Helper Functions:
_delegate,_checkOwner,_checkOwnerOrManager,_checkRecipient, and_checkVotingAdaptorIsSetare helper functions used throughout the contract.
Security Assessment
Vesting Logic:
- The contract calculates vested tokens based on time as expected. One must be cautious with these calculations regarding timestamp manipulation by miners, but given the granularity and duration of vesting, the risk is limited.
- The
totalClaimedupdate is followed by thetoken().safeTransfercall within theclaimfunction. The ordering is appropriate to prevent reentrancy attacks.
Access Control:
- The modifiers are critical controls. A common practice is to ensure these are correctly implemented and cannot be bypassed or misconfigured.
Revocation Mechanisms:
- Audit the conditions under which revocation can occur. Ensure that
isFullyRevocableis set correctly and its state change is secured and logged.
Governance Participation:
- Since these functions interact with an external contract (presumably governed by the
votingAdaptorinterface), it is essential to ensure the voting adaptor contract is secure. If compromised, it could lead to exploit in the control flow.
Recovery Functions:
- These functions are prone to authorization flaws. Review to ensure that only the rightful entity can recover tokens or ETH.
Initialization:
- The
initializemethod should not be callable beyond its intended purpose and by unauthorized actors. In this contract, theif (msg.sender != _factory) revertcheck aims to ensure that only the factory can call initialize, which is a good defensive programming practice.
Contract Interactions:
- The use of
functionDelegateCallallows for dynamic execution of specified functions on other contracts. This should be reviewed carefully for potential security issues, as this pattern can lead to unintended behavior especially in the presence of malicious contracts it interacts with.
Potential Vulnerabilities to Investigate
-
Initialization Risks:
- Ensure that the
initializefunction can only be called once and only by the proper entity.
- Ensure that the
-
Contract Upgradeability and Ownership:
- Investigate ownership transfer functions within the factory contract to prevent unauthorized access.
-
External Interaction Risks:
- Review external dependencies like
Clone,Math,Address,SafeERC20, and the externalvotingAdaptor.
- Review external dependencies like
-
Reentrancy:
- While
SafeERC20mitigates reentrancy risks, it's still good practice to ensure all external calls are made after state updates.
- While
-
Time Manipulation and Overflows:
- Check that there is no vulnerability related to overflows/underflows or miner timestamp manipulation.
-
Logic Errors and Edge Cases:
- Review the contract for logical errors, especially in calculation logic under
_totalVestedAt.
- Review the contract for logical errors, especially in calculation logic under
-
Token Recovery Logic:
- Make sure the contract only allows for the recovery of tokens that are not vested or locked.
In summary, the smart contract needs a comprehensive audit focusing on initialization, access control, revocation logic, governance participation, recovery functions, interactions with other contracts, and overall contract logic, especially calculations around vested and locked tokens. Proper testing, including scenario-based and edge-case analysis, as well as a review by an experienced Solidity auditor, are highly recommended to uncover any potential issues.
-
- User
begin with the vesting mechanics and access control modifiers. Could you please clarify the relationships between the factory,VestingEscrow contract, and the recipient? How does the factory interact with the VestingEscrow, and what are the recipient's capabilities? here is the contract // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.23;
import {Clone} from '@solady/utils/Clone.sol'; import {Math} from '@openzeppelin/contracts/utils/math/Math.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import {IVestingEscrowFactory} from 'src/interfaces/IVestingEscrowFactory.sol'; import {IVestingEscrow} from 'src/interfaces/IVestingEscrow.sol'; import {IVotingAdaptor} from 'src/interfaces/IVotingAdaptor.sol';
contract VestingEscrow is IVestingEscrow, Clone { using SafeERC20 for IERC20; using Address for address; using Address for address payable;
/// @notice The factory that created this VestingEscrow instance. function factory() public pure returns (IVestingEscrowFactory) { return IVestingEscrowFactory(_getArgAddress(0)); } /// @notice The token. function token() public pure returns (IERC20) { return IERC20(_getArgAddress(20)); } /// @notice The token recipient. function recipient() public pure returns (address) { return _getArgAddress(40); } /// @notice The vesting start timestamp. function startTime() public pure returns (uint40) { return _getArgUint40(60); } /// @notice The vesting end timestamp. function endTime() public pure returns (uint40) { return _getArgUint40(65); } /// @notice The vesting cliff length. function cliffLength() public pure returns (uint40) { return _getArgUint40(70); } /// @notice The total amount of tokens locked. function totalLocked() public pure returns (uint256) { return _getArgUint256(75); } /// @notice The total amount of tokens that have been claimed. uint256 public totalClaimed; /// @notice The vesting end time or the time at which vesting was revoked. uint40 public disabledAt; /// @notice Whether vesting is fully revokable. bool public isFullyRevokable; /// @notice Whether vesting has been fully revoked. bool public isFullyRevoked; /// @notice Throws if called by any account other than the owner. modifier onlyOwner() { _checkOwner(); _; } /// @notice Throws if called by any account other than the owner or manager. modifier onlyOwnerOrManager() { _checkOwnerOrManager(); _; } /// @notice Throws if called by any account other than the recipient. modifier onlyRecipient() { _checkRecipient(); _; } /// @notice Throws if the voting adaptor is not set. modifier whenVotingAdaptorIsSet() { _checkVotingAdaptorIsSet(); _; } /// @notice Initializes the contract. /// @param _isFullyRevokable Whether the tokens are fully revokable. /// @param _initialDelegateParams The optional initial delegate information (skipped if empty bytes). function initialize(bool _isFullyRevokable, bytes calldata _initialDelegateParams) external { address _factory = address(factory()); uint256 _totalLocked = totalLocked(); uint40 _endTime = endTime(); IERC20 _token = token(); if (msg.sender != _factory) revert NOT_FACTORY(msg.sender); if (_token.balanceOf(address(this)) < _totalLocked) revert INSUFFICIENT_BALANCE(); disabledAt = _endTime; // Set to maximum time isFullyRevokable = _isFullyRevokable; if (_initialDelegateParams.length != 0) _delegate(_initialDelegateParams); emit VestingEscrowInitialized( _factory, recipient(), address(_token), _totalLocked, startTime(), _endTime, cliffLength(), _isFullyRevokable ); } /// @notice Get the number of unclaimed, vested tokens for recipient. function unclaimed() public view returns (uint256) { if (isFullyRevoked) return 0; uint256 claimTime = Math.min(block.timestamp, disabledAt); return _totalVestedAt(claimTime) - totalClaimed; } /// @notice Get the number of locked tokens for recipient. function locked() public view returns (uint256) { if (block.timestamp >= disabledAt) return 0; return totalLocked() - _totalVestedAt(block.timestamp); } /// @notice Claim tokens which have vested. /// @param beneficiary Address to transfer claimed tokens to. /// @param amount Amount of tokens to claim. function claim(address beneficiary, uint256 amount) external onlyRecipient returns (uint256) { uint256 claimable = Math.min(unclaimed(), amount); totalClaimed += claimable; token().safeTransfer(beneficiary, claimable); emit Claim(beneficiary, claimable); return claimable; } /// @notice Delegate voting power of all available tokens. /// @param params The ABI-encoded delegate params. function delegate(bytes calldata params) external onlyRecipient returns (bytes memory) { return _delegate(params); } /// @notice Participate in a governance vote using all available tokens on the contract's balance. /// @param params The ABI-encoded data for call. Can be obtained from VotingAdaptor.encodeVoteCalldata. function vote(bytes calldata params) external onlyRecipient whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.vote, (params))); } // forgefmt: disable-next-item /// @notice Participate in a governance vote with a reason using all available tokens on the contract's balance. /// @param params The ABI-encoded data for call. Can be obtained from VotingAdaptor.encodeVoteWithReasonCalldata. function voteWithReason(bytes calldata params) external onlyRecipient whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.voteWithReason, (params))); } /// @notice Disable further flow of tokens and revoke the unvested part to owner. function revokeUnvested() external onlyOwnerOrManager { uint256 revokable = locked(); if (revokable == 0) revert NOTHING_TO_REVOKE(); disabledAt = uint40(block.timestamp); token().safeTransfer(_owner(), revokable); emit UnvestedTokensRevoked(msg.sender, revokable); } /// @notice Disable further flow of tokens and revoke all tokens to owner. function revokeAll() external onlyOwner { if (!isFullyRevokable) revert NOT_FULLY_REVOKABLE(); if (isFullyRevoked) revert ALREADY_FULLY_REVOKED(); uint256 revokable = locked() + unclaimed(); if (revokable == 0) revert NOTHING_TO_REVOKE(); isFullyRevoked = true; disabledAt = uint40(block.timestamp); token().safeTransfer(_owner(), revokable); emit VestingFullyRevoked(msg.sender, revokable); } /// @notice Permanently disable full token revocation. function permanentlyDisableFullRevocation() external onlyOwner { if (!isFullyRevokable) revert NOT_FULLY_REVOKABLE(); isFullyRevokable = false; emit FullRevocationPermanentlyDisabled(msg.sender); } /// @notice Recover any ERC20 token to the recipient. /// @param token_ Address of the ERC20 token to recover. /// @param amount Amount of tokens to recover. function recoverERC20(address token_, uint256 amount) external { uint256 recoverable = amount; if (token_ == address(token())) { uint256 available = token().balanceOf(address(this)) - (locked() + unclaimed()); recoverable = Math.min(recoverable, available); } if (recoverable > 0) { IERC20(token_).safeTransfer(recipient(), recoverable); emit ERC20Recovered(token_, recoverable); } } /// @notice Recover any ETH to the recipient. function recoverEther() external { uint256 amount = address(this).balance; if (amount > 0) { payable(recipient()).sendValue(amount); emit ETHRecovered(amount); } } /// @dev Returns the factory owner. function _owner() internal view returns (address) { return factory().owner(); } /// @dev Returns the factory manager. function _manager() internal view returns (address) { return factory().manager(); } /// @dev Returns the factory voting adaptor. function _votingAdaptor() internal view returns (address) { return factory().votingAdaptor(); } /// @dev Throws if called by any account other than the owner. function _checkOwner() internal view { if (msg.sender != _owner()) { revert NOT_OWNER(msg.sender); } } /// @dev Throws if called by any account other than the owner or manager. function _checkOwnerOrManager() internal view { if (msg.sender != _owner() && msg.sender != _manager()) { revert NOT_OWNER_OR_MANAGER(msg.sender); } } /// @dev Throws if called by any account other than the recipient. function _checkRecipient() internal view { if (msg.sender != recipient()) { revert NOT_RECIPIENT(msg.sender); } } /// @dev Throws if the voting adaptor is not set. function _checkVotingAdaptorIsSet() internal view { if (_votingAdaptor() == address(0)) { revert VOTING_ADAPTOR_NOT_SET(); } } /// @notice Delegate voting power of all available tokens. /// @param params The ABI-encoded delegate params. function _delegate(bytes calldata params) internal whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.delegate, params)); } /// @dev Returns the vested token amount at a specific time. /// @param time The time to retrieve the vesting amount for. function _totalVestedAt(uint256 time) internal pure returns (uint256) { uint40 _startTime = startTime(); uint256 _totalLocked = totalLocked(); if (time < _startTime + cliffLength()) { return 0; } return Math.min(_totalLocked * (time - _startTime) / (endTime() - _startTime), _totalLocked); }}
- Assistant
The
VestingEscrowcontract is designed to handle the vesting of ERC20 tokens. Let's discuss the roles of each participant in the contract and how they interact with each other:Factory
The
factoryrefers to an instance of theIVestingEscrowFactorythat created theVestingEscrowcontract. It plays a few important roles:- Contract Creation: The factory likely contains logic to deploy instances of the
VestingEscrowcontract through a "clone" or "minimal proxy" pattern, pointed out by theCloneimport. Each new vesting contract is a separate entity with separate vesting terms. - Access Control: It houses the logic to determine the
ownerandmanagerroles, inheriting similar access control patterns as seen in OpenZeppelin'sOwnablepattern. These roles are crucial for privileged functions like revoking vested tokens. - Onboarding Logic: The factory, when creating a new
VestingEscrowcontract, could be responsible for passing in initialization parameters (e.g., token address, start time, end time, cliff length, locked amount), typically done immediately post-deployment.
VestingEscrow Contract
The
VestingEscrowcontract itself is responsible for the following:- Token Vesting: Manages the vesting of specific ERC20 tokens over time. This is achieved by keeping track of
startTime,endTime,cliffLength,totalLocked,totalClaimed, anddisabledAt. - Claims: Allows the recipient to claim vested tokens to a specified
beneficiaryaddress. - Revocation: Grants rights to the
ownerormanagerto revoke unvested tokens or, ifisFullyRevokableistrue, to revoke all tokens. - Delegation & Voting: Permits the recipient to participate in governance by delegating their voting power or voting using the
votingAdaptor. - Recovery Features: Lets the recipient recover any ERC20 tokens that are not part of the vesting process as well as any Ether that might have been accidentally sent to the contract.
Recipient
The
recipientis the address that theVestingEscrowcontract is vesting tokens for. The recipient has the capability to:- Claim Vested Tokens: Withdraw vested tokens that are due according to the vesting schedule.
- Delegate Votes: Take part in governance by delegating votes through the
votingAdaptor. - Vote: Directly participate in governance votes if a
votingAdaptoris set up. - Recover Assets: Claim back any non-vested ERC20 tokens or Ether from the contract.
Interaction Overview
- The
factorydeploys a newVestingEscrowcontract clone with specified parameters. - The
initializefunction is called to set up the vesting schedule and other properties. It is essential that this is secured and only callable by the factory itself to prevent unauthorized re-initialization. - The recipient can call
claimto withdraw vested tokens periodically, based on the vesting schedule. - The
factoryowner or manager has the ability torevokeUnvestedtokens, reverting unclaimed and non-vested tokens back to the owner, orrevokeAllif the contract was initialized as fully revokable. - Upon calling
recoverERC20orrecoverEther, the recipient can recover any tokens or Ether sent in error to the contract's address, as long as it doesn't interfere with the vested token balance. - The recipient, through the contract, can engage in governance actions via
delegate,vote, andvoteWithReason, assuming a validvotingAdaptoris provided by the factory and set up for use.
A critical security aspect in this contract is the
initializefunction, which should be shielded against any unauthorized access post-deployment. Additionally, the management of voting rights via an external adaptor increases the surface area for potential vulnerabilities and should be meticulously scrutinized. Overall, regular security practices such as preventing reentrancy, safeguarding privileged roles, and maintaining proper event logging should be maintained. - Contract Creation: The factory likely contains logic to deploy instances of the
- User
specify how the initialization parameters are passed to the VestingEscrow contract? Also, how does the recipient interact with the contract for claims, voting, and recovery? // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.23;
import {Clone} from '@solady/utils/Clone.sol'; import {Math} from '@openzeppelin/contracts/utils/math/Math.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import {IVestingEscrowFactory} from 'src/interfaces/IVestingEscrowFactory.sol'; import {IVestingEscrow} from 'src/interfaces/IVestingEscrow.sol'; import {IVotingAdaptor} from 'src/interfaces/IVotingAdaptor.sol';
contract VestingEscrow is IVestingEscrow, Clone { using SafeERC20 for IERC20; using Address for address; using Address for address payable;
/// @notice The factory that created this VestingEscrow instance. function factory() public pure returns (IVestingEscrowFactory) { return IVestingEscrowFactory(_getArgAddress(0)); } /// @notice The token. function token() public pure returns (IERC20) { return IERC20(_getArgAddress(20)); } /// @notice The token recipient. function recipient() public pure returns (address) { return _getArgAddress(40); } /// @notice The vesting start timestamp. function startTime() public pure returns (uint40) { return _getArgUint40(60); } /// @notice The vesting end timestamp. function endTime() public pure returns (uint40) { return _getArgUint40(65); } /// @notice The vesting cliff length. function cliffLength() public pure returns (uint40) { return _getArgUint40(70); } /// @notice The total amount of tokens locked. function totalLocked() public pure returns (uint256) { return _getArgUint256(75); } /// @notice The total amount of tokens that have been claimed. uint256 public totalClaimed; /// @notice The vesting end time or the time at which vesting was revoked. uint40 public disabledAt; /// @notice Whether vesting is fully revokable. bool public isFullyRevokable; /// @notice Whether vesting has been fully revoked. bool public isFullyRevoked; /// @notice Throws if called by any account other than the owner. modifier onlyOwner() { _checkOwner(); _; } /// @notice Throws if called by any account other than the owner or manager. modifier onlyOwnerOrManager() { _checkOwnerOrManager(); _; } /// @notice Throws if called by any account other than the recipient. modifier onlyRecipient() { _checkRecipient(); _; } /// @notice Throws if the voting adaptor is not set. modifier whenVotingAdaptorIsSet() { _checkVotingAdaptorIsSet(); _; } /// @notice Initializes the contract. /// @param _isFullyRevokable Whether the tokens are fully revokable. /// @param _initialDelegateParams The optional initial delegate information (skipped if empty bytes). function initialize(bool _isFullyRevokable, bytes calldata _initialDelegateParams) external { address _factory = address(factory()); uint256 _totalLocked = totalLocked(); uint40 _endTime = endTime(); IERC20 _token = token(); if (msg.sender != _factory) revert NOT_FACTORY(msg.sender); if (_token.balanceOf(address(this)) < _totalLocked) revert INSUFFICIENT_BALANCE(); disabledAt = _endTime; // Set to maximum time isFullyRevokable = _isFullyRevokable; if (_initialDelegateParams.length != 0) _delegate(_initialDelegateParams); emit VestingEscrowInitialized( _factory, recipient(), address(_token), _totalLocked, startTime(), _endTime, cliffLength(), _isFullyRevokable ); } /// @notice Get the number of unclaimed, vested tokens for recipient. function unclaimed() public view returns (uint256) { if (isFullyRevoked) return 0; uint256 claimTime = Math.min(block.timestamp, disabledAt); return _totalVestedAt(claimTime) - totalClaimed; } /// @notice Get the number of locked tokens for recipient. function locked() public view returns (uint256) { if (block.timestamp >= disabledAt) return 0; return totalLocked() - _totalVestedAt(block.timestamp); } /// @notice Claim tokens which have vested. /// @param beneficiary Address to transfer claimed tokens to. /// @param amount Amount of tokens to claim. function claim(address beneficiary, uint256 amount) external onlyRecipient returns (uint256) { uint256 claimable = Math.min(unclaimed(), amount); totalClaimed += claimable; token().safeTransfer(beneficiary, claimable); emit Claim(beneficiary, claimable); return claimable; } /// @notice Delegate voting power of all available tokens. /// @param params The ABI-encoded delegate params. function delegate(bytes calldata params) external onlyRecipient returns (bytes memory) { return _delegate(params); } /// @notice Participate in a governance vote using all available tokens on the contract's balance. /// @param params The ABI-encoded data for call. Can be obtained from VotingAdaptor.encodeVoteCalldata. function vote(bytes calldata params) external onlyRecipient whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.vote, (params))); } // forgefmt: disable-next-item /// @notice Participate in a governance vote with a reason using all available tokens on the contract's balance. /// @param params The ABI-encoded data for call. Can be obtained from VotingAdaptor.encodeVoteWithReasonCalldata. function voteWithReason(bytes calldata params) external onlyRecipient whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.voteWithReason, (params))); } /// @notice Disable further flow of tokens and revoke the unvested part to owner. function revokeUnvested() external onlyOwnerOrManager { uint256 revokable = locked(); if (revokable == 0) revert NOTHING_TO_REVOKE(); disabledAt = uint40(block.timestamp); token().safeTransfer(_owner(), revokable); emit UnvestedTokensRevoked(msg.sender, revokable); } /// @notice Disable further flow of tokens and revoke all tokens to owner. function revokeAll() external onlyOwner { if (!isFullyRevokable) revert NOT_FULLY_REVOKABLE(); if (isFullyRevoked) revert ALREADY_FULLY_REVOKED(); uint256 revokable = locked() + unclaimed(); if (revokable == 0) revert NOTHING_TO_REVOKE(); isFullyRevoked = true; disabledAt = uint40(block.timestamp); token().safeTransfer(_owner(), revokable); emit VestingFullyRevoked(msg.sender, revokable); } /// @notice Permanently disable full token revocation. function permanentlyDisableFullRevocation() external onlyOwner { if (!isFullyRevokable) revert NOT_FULLY_REVOKABLE(); isFullyRevokable = false; emit FullRevocationPermanentlyDisabled(msg.sender); } /// @notice Recover any ERC20 token to the recipient. /// @param token_ Address of the ERC20 token to recover. /// @param amount Amount of tokens to recover. function recoverERC20(address token_, uint256 amount) external { uint256 recoverable = amount; if (token_ == address(token())) { uint256 available = token().balanceOf(address(this)) - (locked() + unclaimed()); recoverable = Math.min(recoverable, available); } if (recoverable > 0) { IERC20(token_).safeTransfer(recipient(), recoverable); emit ERC20Recovered(token_, recoverable); } } /// @notice Recover any ETH to the recipient. function recoverEther() external { uint256 amount = address(this).balance; if (amount > 0) { payable(recipient()).sendValue(amount); emit ETHRecovered(amount); } } /// @dev Returns the factory owner. function _owner() internal view returns (address) { return factory().owner(); } /// @dev Returns the factory manager. function _manager() internal view returns (address) { return factory().manager(); } /// @dev Returns the factory voting adaptor. function _votingAdaptor() internal view returns (address) { return factory().votingAdaptor(); } /// @dev Throws if called by any account other than the owner. function _checkOwner() internal view { if (msg.sender != _owner()) { revert NOT_OWNER(msg.sender); } } /// @dev Throws if called by any account other than the owner or manager. function _checkOwnerOrManager() internal view { if (msg.sender != _owner() && msg.sender != _manager()) { revert NOT_OWNER_OR_MANAGER(msg.sender); } } /// @dev Throws if called by any account other than the recipient. function _checkRecipient() internal view { if (msg.sender != recipient()) { revert NOT_RECIPIENT(msg.sender); } } /// @dev Throws if the voting adaptor is not set. function _checkVotingAdaptorIsSet() internal view { if (_votingAdaptor() == address(0)) { revert VOTING_ADAPTOR_NOT_SET(); } } /// @notice Delegate voting power of all available tokens. /// @param params The ABI-encoded delegate params. function _delegate(bytes calldata params) internal whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.delegate, params)); } /// @dev Returns the vested token amount at a specific time. /// @param time The time to retrieve the vesting amount for. function _totalVestedAt(uint256 time) internal pure returns (uint256) { uint40 _startTime = startTime(); uint256 _totalLocked = totalLocked(); if (time < _startTime + cliffLength()) { return 0; } return Math.min(_totalLocked * (time - _startTime) / (endTime() - _startTime), _totalLocked); }}
- Assistant
Initialization Parameters and Vesting Schedule
The
VestingEscrowcontract inherits and makes use of functionality fromClone.sol, which indicates that this contract is intended to be used as part of a cloning or factory pattern. Cloning is a common pattern used to create new contracts with the same logic but different data to save on deployment gas costs.Initialization parameters are passed to the
VestingEscrowcontract by encoding them directly into the calldata of the cloning transaction. After the newVestingEscrowclone contract is deployed, theinitializefunction is called externally to set the initial state. The parameters for thefactory,token,recipient,startTime,endTime,cliffLength, andtotalLockedare extracted from calldata using internal functions_getArgAddressand_getArgUint40which are typically part of theClone.sollibrary (although not explicitly shown in the provided code).This initialization process connects the
factory,VestingEscrowcontract, andrecipient:- The
factoryis the creator and sets the initial parameters of theVestingEscrowcontract. - The
VestingEscrowis a clone that holds the token and dictates how and when they are vested and released. - The
recipientis the end beneficiary who will receive the vested tokens according to the schedule set during initialization.
How the Recipient Interacts with the Contract
-
Claims:
- The recipient can claim the vested tokens using
claim(address beneficiary, uint256 amount)function. To do so, the recipient specifies thebeneficiaryaddress where the tokens should be sent and theamountof tokens to claim. The contract ensures viaonlyRecipientmodifier that only the intended recipient can call this method and claims only the vested portion as calculated by the functionunclaimed.
- The recipient can claim the vested tokens using
-
Voting:
- If the contract's
votingAdaptorvariable is set, the recipient can engage in voting by calling thevote(bytes calldata params)andvoteWithReason(bytes calldata params)functions. The calldataparamswould contain the necessary parameters for voting encoded according to theIVotingAdaptorinterface. Again, theonlyRecipientmodifier is used to restrict access to these functions.
- If the contract's
-
Recovery:
- In case any tokens are mistakenly sent to the contract, the recipient can recover them by using
recoverERC20(address token_, uint256 amount)andrecoverEther()functions as long as the recovery amount does not include locked or unclaimed tokens due for vesting. ForrecoverERC20, the function comparesrecoverablewith the available balance minus locked and unclaimed tokens to ensure vested funds are not affected. As with the other functions, access is restricted to the recipient.
- In case any tokens are mistakenly sent to the contract, the recipient can recover them by using
The contract gives careful consideration to access control and execution context, particularly with modifiers that ensure functions can only be called by authorized addresses (such as
onlyOwner,onlyOwnerOrManager, andonlyRecipient). Moreover, functions likeinitializeandrevokeUnvestedrestrict access based on the sender's address in relation to the storedfactoryorowner/manageraddresses, thus enforcing that only the appropriate actors can trigger these operations. - The
- User
how the owner or manager can interact with the VestingEscrow contract. Could you explain the conditions under which revocation is possible and the steps involved? // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.23;
import {Clone} from '@solady/utils/Clone.sol'; import {Math} from '@openzeppelin/contracts/utils/math/Math.sol'; import {Address} from '@openzeppelin/contracts/utils/Address.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import {IVestingEscrowFactory} from 'src/interfaces/IVestingEscrowFactory.sol'; import {IVestingEscrow} from 'src/interfaces/IVestingEscrow.sol'; import {IVotingAdaptor} from 'src/interfaces/IVotingAdaptor.sol';
contract VestingEscrow is IVestingEscrow, Clone { using SafeERC20 for IERC20; using Address for address; using Address for address payable;
/// @notice The factory that created this VestingEscrow instance. function factory() public pure returns (IVestingEscrowFactory) { return IVestingEscrowFactory(_getArgAddress(0)); } /// @notice The token. function token() public pure returns (IERC20) { return IERC20(_getArgAddress(20)); } /// @notice The token recipient. function recipient() public pure returns (address) { return _getArgAddress(40); } /// @notice The vesting start timestamp. function startTime() public pure returns (uint40) { return _getArgUint40(60); } /// @notice The vesting end timestamp. function endTime() public pure returns (uint40) { return _getArgUint40(65); } /// @notice The vesting cliff length. function cliffLength() public pure returns (uint40) { return _getArgUint40(70); } /// @notice The total amount of tokens locked. function totalLocked() public pure returns (uint256) { return _getArgUint256(75); } /// @notice The total amount of tokens that have been claimed. uint256 public totalClaimed; /// @notice The vesting end time or the time at which vesting was revoked. uint40 public disabledAt; /// @notice Whether vesting is fully revokable. bool public isFullyRevokable; /// @notice Whether vesting has been fully revoked. bool public isFullyRevoked; /// @notice Throws if called by any account other than the owner. modifier onlyOwner() { _checkOwner(); _; } /// @notice Throws if called by any account other than the owner or manager. modifier onlyOwnerOrManager() { _checkOwnerOrManager(); _; } /// @notice Throws if called by any account other than the recipient. modifier onlyRecipient() { _checkRecipient(); _; } /// @notice Throws if the voting adaptor is not set. modifier whenVotingAdaptorIsSet() { _checkVotingAdaptorIsSet(); _; } /// @notice Initializes the contract. /// @param _isFullyRevokable Whether the tokens are fully revokable. /// @param _initialDelegateParams The optional initial delegate information (skipped if empty bytes). function initialize(bool _isFullyRevokable, bytes calldata _initialDelegateParams) external { address _factory = address(factory()); uint256 _totalLocked = totalLocked(); uint40 _endTime = endTime(); IERC20 _token = token(); if (msg.sender != _factory) revert NOT_FACTORY(msg.sender); if (_token.balanceOf(address(this)) < _totalLocked) revert INSUFFICIENT_BALANCE(); disabledAt = _endTime; // Set to maximum time isFullyRevokable = _isFullyRevokable; if (_initialDelegateParams.length != 0) _delegate(_initialDelegateParams); emit VestingEscrowInitialized( _factory, recipient(), address(_token), _totalLocked, startTime(), _endTime, cliffLength(), _isFullyRevokable ); } /// @notice Get the number of unclaimed, vested tokens for recipient. function unclaimed() public view returns (uint256) { if (isFullyRevoked) return 0; uint256 claimTime = Math.min(block.timestamp, disabledAt); return _totalVestedAt(claimTime) - totalClaimed; } /// @notice Get the number of locked tokens for recipient. function locked() public view returns (uint256) { if (block.timestamp >= disabledAt) return 0; return totalLocked() - _totalVestedAt(block.timestamp); } /// @notice Claim tokens which have vested. /// @param beneficiary Address to transfer claimed tokens to. /// @param amount Amount of tokens to claim. function claim(address beneficiary, uint256 amount) external onlyRecipient returns (uint256) { uint256 claimable = Math.min(unclaimed(), amount); totalClaimed += claimable; token().safeTransfer(beneficiary, claimable); emit Claim(beneficiary, claimable); return claimable; } /// @notice Delegate voting power of all available tokens. /// @param params The ABI-encoded delegate params. function delegate(bytes calldata params) external onlyRecipient returns (bytes memory) { return _delegate(params); } /// @notice Participate in a governance vote using all available tokens on the contract's balance. /// @param params The ABI-encoded data for call. Can be obtained from VotingAdaptor.encodeVoteCalldata. function vote(bytes calldata params) external onlyRecipient whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.vote, (params))); } // forgefmt: disable-next-item /// @notice Participate in a governance vote with a reason using all available tokens on the contract's balance. /// @param params The ABI-encoded data for call. Can be obtained from VotingAdaptor.encodeVoteWithReasonCalldata. function voteWithReason(bytes calldata params) external onlyRecipient whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.voteWithReason, (params))); } /// @notice Disable further flow of tokens and revoke the unvested part to owner. function revokeUnvested() external onlyOwnerOrManager { uint256 revokable = locked(); if (revokable == 0) revert NOTHING_TO_REVOKE(); disabledAt = uint40(block.timestamp); token().safeTransfer(_owner(), revokable); emit UnvestedTokensRevoked(msg.sender, revokable); } /// @notice Disable further flow of tokens and revoke all tokens to owner. function revokeAll() external onlyOwner { if (!isFullyRevokable) revert NOT_FULLY_REVOKABLE(); if (isFullyRevoked) revert ALREADY_FULLY_REVOKED(); uint256 revokable = locked() + unclaimed(); if (revokable == 0) revert NOTHING_TO_REVOKE(); isFullyRevoked = true; disabledAt = uint40(block.timestamp); token().safeTransfer(_owner(), revokable); emit VestingFullyRevoked(msg.sender, revokable); } /// @notice Permanently disable full token revocation. function permanentlyDisableFullRevocation() external onlyOwner { if (!isFullyRevokable) revert NOT_FULLY_REVOKABLE(); isFullyRevokable = false; emit FullRevocationPermanentlyDisabled(msg.sender); } /// @notice Recover any ERC20 token to the recipient. /// @param token_ Address of the ERC20 token to recover. /// @param amount Amount of tokens to recover. function recoverERC20(address token_, uint256 amount) external { uint256 recoverable = amount; if (token_ == address(token())) { uint256 available = token().balanceOf(address(this)) - (locked() + unclaimed()); recoverable = Math.min(recoverable, available); } if (recoverable > 0) { IERC20(token_).safeTransfer(recipient(), recoverable); emit ERC20Recovered(token_, recoverable); } } /// @notice Recover any ETH to the recipient. function recoverEther() external { uint256 amount = address(this).balance; if (amount > 0) { payable(recipient()).sendValue(amount); emit ETHRecovered(amount); } } /// @dev Returns the factory owner. function _owner() internal view returns (address) { return factory().owner(); } /// @dev Returns the factory manager. function _manager() internal view returns (address) { return factory().manager(); } /// @dev Returns the factory voting adaptor. function _votingAdaptor() internal view returns (address) { return factory().votingAdaptor(); } /// @dev Throws if called by any account other than the owner. function _checkOwner() internal view { if (msg.sender != _owner()) { revert NOT_OWNER(msg.sender); } } /// @dev Throws if called by any account other than the owner or manager. function _checkOwnerOrManager() internal view { if (msg.sender != _owner() && msg.sender != _manager()) { revert NOT_OWNER_OR_MANAGER(msg.sender); } } /// @dev Throws if called by any account other than the recipient. function _checkRecipient() internal view { if (msg.sender != recipient()) { revert NOT_RECIPIENT(msg.sender); } } /// @dev Throws if the voting adaptor is not set. function _checkVotingAdaptorIsSet() internal view { if (_votingAdaptor() == address(0)) { revert VOTING_ADAPTOR_NOT_SET(); } } /// @notice Delegate voting power of all available tokens. /// @param params The ABI-encoded delegate params. function _delegate(bytes calldata params) internal whenVotingAdaptorIsSet returns (bytes memory) { return _votingAdaptor().functionDelegateCall(abi.encodeCall(IVotingAdaptor.delegate, params)); } /// @dev Returns the vested token amount at a specific time. /// @param time The time to retrieve the vesting amount for. function _totalVestedAt(uint256 time) internal pure returns (uint256) { uint40 _startTime = startTime(); uint256 _totalLocked = totalLocked(); if (time < _startTime + cliffLength()) { return 0; } return Math.min(_totalLocked * (time - _startTime) / (endTime() - _startTime), _totalLocked); }}
- Assistant
The
VestingEscrowcontract provides mechanisms for the owner or manager to interact with it regarding the revocation of unvested or all tokens. Let's discuss how this can be done:Identifying the Owner and Manager
- The owner's address is returned by the internal
_owner()function, which retrieves the owner from the factory contract. - The manager's address is returned by the internal
_manager()function, also retrieved from the factory.
Revocation of Tokens
-
Unvested Tokens:
- The
revokeUnvested()function can be called by the owner or manager as enforced by theonlyOwnerOrManagermodifier. - The function first calculates the amount of
lockedtokens, which represents the tokens that are not yet vested according to the vesting schedule. - If there are tokens to revoke (i.e.,
revokable > 0), thedisabledAttimestamp is set to the current block timestamp, effectively stopping the vesting schedule. - The revokable tokens are then transferred to the owner's address, and an event
UnvestedTokensRevokedis emitted.
- The
-
All Tokens:
- The
revokeAll()function, on the other hand, can be called only by the owner as enforced by theonlyOwnermodifier. - This function is contingent on the
isFullyRevokableboolean variable being set totrue. If it's not set, the function reverts withNOT_FULLY_REVOKABLE. - Furthermore, it checks if the tokens have already been fully revoked by the
isFullyRevokedflag. If they have been, it reverts withALREADY_FULLY_REVOKED. - It calculates the revokable amount by summing
locked()andunclaimed()tokens. - If revocation is possible, the
isFullyRevokedflag is set totrueanddisabledAtis updated with the current block timestamp. - The ERC20
safeTransferfunction is then used to transfer all revokable tokens to the owner's address, and theVestingFullyRevokedevent is emitted.
- The
Permanently Disable Full Token Revocation
- There is an additional function
permanentlyDisableFullRevocation()that allows the owner to permanently disable the functionality to fully revoke all tokens, altering theisFullyRevokableflag tofalseand preventing further invocation of therevokeAll()function. This action cannot be undone and it emits aFullRevocationPermanentlyDisabledevent.
Steps Involved for Revocation
- The owner or manager decides to revoke tokens based on the vesting terms and current status.
- They call
revokeUnvested()for unvested tokens orrevokeAll()for fully revokable contracts. - The contract validates the permission, revocability status, and whether there are any revokable tokens.
- It transfers the correct amount of tokens to the owner's address, adjusting the
disabledAttimestamp and other related state variables as necessary. - The corresponding revocation event is emitted to provide a clear audit trail on the blockchain.
For the security of recipients, the conditions and flow of these operations ought to be transparent, with strict checks and balances to prevent any possibility of unauthorized token seizure. Owners and managers should only revoke tokens in accordance with the initial vesting agreement and any governing legal or community-approved framework.
- The owner's address is returned by the internal