Description:
Multi-signature wallet contract requiring multiple confirmations for transaction execution.
Blockchain: Ethereum
Source Code: View Code On The Blockchain
Solidity Source Code:
{{
"language": "Solidity",
"sources": {
"lib/ve-governance/src/escrow/VotingEscrowIncreasing_v1_2_0.sol": {
"content": "/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
// token interfaces
import {
IERC20Upgradeable as IERC20
} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {
IERC20MetadataUpgradeable as IERC20Metadata
} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import {IERC721EnumerableMintableBurnable as IERC721EMB} from "@lock/IERC721EMB.sol";
// veGovernance
import {IDAO} from "@aragon/osx-commons-contracts/src/dao/IDAO.sol";
import {IAddressGaugeVoter} from "@voting/IAddressGaugeVoter.sol";
import {
IEscrowCurveIncreasingV1_2_0 as IEscrowCurve
} from "@curve/IEscrowCurveIncreasing_v1_2_0.sol";
import {IExitQueue} from "@queue/IExitQueue.sol";
import {
IVotingEscrowIncreasingV1_2_0 as IVotingEscrow,
IVotingEscrowExiting,
IMerge,
ISplit,
IDelegateMoveVoteCaller
} from "@escrow/IVotingEscrowIncreasing_v1_2_0.sol";
import {IClockV1_2_0 as IClock} from "@clock/IClock_v1_2_0.sol";
// libraries
import {
SafeERC20Upgradeable as SafeERC20
} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {
SafeCastUpgradeable as SafeCast
} from "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
// parents
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {
ReentrancyGuardUpgradeable as ReentrancyGuard
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
PausableUpgradeable as Pausable
} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {
DaoAuthorizableUpgradeable as DaoAuthorizable
} from "@aragon/osx-commons-contracts/src/permission/auth/DaoAuthorizableUpgradeable.sol";
import {
IDelegateUpdateVotingPower,
IEscrowIVotesAdapter,
IDelegateMoveVoteRecipient
} from "../delegation/IEscrowIVotesAdapter.sol";
contract VotingEscrowV1_2_0 is
IVotingEscrow,
ReentrancyGuard,
Pausable,
DaoAuthorizable,
UUPSUpgradeable
{
using SafeERC20 for IERC20;
using SafeCast for uint256;
/// @notice Role required to manage the Escrow curve, this typically will be the DAO
bytes32 public constant ESCROW_ADMIN_ROLE = keccak256("ESCROW_ADMIN");
/// @notice Role required to pause the contract - can be given to emergency contracts
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER");
/// @notice Role required to withdraw underlying tokens from the contract
bytes32 public constant SWEEPER_ROLE = keccak256("SWEEPER");
/// @dev enables splits without whitelisting
address public constant SPLIT_WHITELIST_ANY_ADDRESS =
address(uint160(uint256(keccak256("SPLIT_WHITELIST_ANY_ADDRESS"))));
/*//////////////////////////////////////////////////////////////
NFT Data
//////////////////////////////////////////////////////////////*/
/// @notice Decimals of the voting power
uint8 public constant decimals = 18;
/// @notice Minimum deposit amount
uint256 public minDeposit;
/// @notice Auto-incrementing ID for the most recently created lock, does not decrease on withdrawal
uint256 public lastLockId;
/// @notice Total supply of underlying tokens deposited in the contract
uint256 public totalLocked;
/// @dev tracks the locked balance of each NFT
mapping(uint256 => LockedBalance) private _locked;
/*//////////////////////////////////////////////////////////////
Helper Contracts
//////////////////////////////////////////////////////////////*/
/// @notice Address of the underying ERC20 token.
/// @dev Only tokens with 18 decimals and no transfer fees are supported
address public token;
/// @notice Address of the gauge voting contract.
/// @dev We need to ensure votes are not left in this contract before allowing positing changes
address public voter;
/// @notice Address of the voting Escrow Curve contract that will calculate the voting power
address public curve;
/// @notice Address of the contract that manages exit queue logic for withdrawals
address public queue;
/// @notice Address of the clock contract that manages epoch and voting periods
address public clock;
/// @notice Address of the NFT contract that is the lock
address public lockNFT;
bool private _lockNFTSet;
/*//////////////////////////////////////////////////////////////
ADDED: in 1.2.0
//////////////////////////////////////////////////////////////*/
/// @notice Whitelisted contracts that are allowed to split
mapping(address => bool) public splitWhitelisted;
/// @notice Prevent withdrawals in same creation block
mapping(uint256 => uint256) internal withdrawalLock;
/// @notice Addess of the escrow ivotes adapter where delegations occur.
address public ivotesAdapter;
/*//////////////////////////////////////////////////////////////
Initialization
//////////////////////////////////////////////////////////////*/
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(
address _token,
address _dao,
address _clock,
uint256 _initialMinDeposit
) external initializer {
__ReentrancyGuard_init();
__Pausable_init();
__DaoAuthorizableUpgradeable_init(IDAO(_dao));
// if (IERC20Metadata(_token).decimals() != 18) revert MustBe18Decimals();
token = _token;
clock = _clock;
minDeposit = _initialMinDeposit;
emit MinDepositSet(_initialMinDeposit);
}
/// @notice Used to revert if admin tries to change the contract address 2nd time.
modifier contractAlreadySet(address _contract) {
if (_contract != address(0)) revert AddressAlreadySet();
_;
}
/*//////////////////////////////////////////////////////////////
Admin Setters
//////////////////////////////////////////////////////////////*/
/// @notice Added in 1.2.0 to set the ivotes adapter
function setIVotesAdapter(
address _ivotesAdapter
) external auth(ESCROW_ADMIN_ROLE) contractAlreadySet(ivotesAdapter) {
ivotesAdapter = _ivotesAdapter;
}
/// @notice Sets the curve contract that calculates the voting power
function setCurve(address _curve) external auth(ESCROW_ADMIN_ROLE) contractAlreadySet(curve) {
curve = _curve;
}
/// @notice Sets the voter contract that tracks votes
function setVoter(address _voter) external auth(ESCROW_ADMIN_ROLE) {
voter = _voter;
}
/// @notice Sets the exit queue contract that manages withdrawal eligibility
function setQueue(address _queue) external auth(ESCROW_ADMIN_ROLE) contractAlreadySet(queue) {
queue = _queue;
}
/// @notice Sets the clock contract that manages epoch and voting periods
function setClock(address _clock) external auth(ESCROW_ADMIN_ROLE) contractAlreadySet(clock) {
clock = _clock;
}
/// @notice Sets the NFT contract that is the lock
/// @dev By default this can only be set once due to the high risk of changing the lock
/// and having the ability to steal user funds.
function setLockNFT(address _nft) external auth(ESCROW_ADMIN_ROLE) {
if (_lockNFTSet) revert LockNFTAlreadySet();
lockNFT = _nft;
_lockNFTSet = true;
}
function pause() external auth(PAUSER_ROLE) {
_pause();
}
function unpause() external auth(PAUSER_ROLE) {
_unpause();
}
function setMinDeposit(uint256 _minDeposit) external auth(ESCROW_ADMIN_ROLE) {
minDeposit = _minDeposit;
emit MinDepositSet(_minDeposit);
}
/// @notice Split disabled by default, only whitelisted addresses can split.
function setEnableSplit(
address _account,
bool _isWhitelisted
) external auth(ESCROW_ADMIN_ROLE) {
splitWhitelisted[_account] = _isWhitelisted;
emit SplitWhitelistSet(_account, _isWhitelisted);
}
/// @notice Enable split to any address without whitelisting
function enableSplit() external auth(ESCROW_ADMIN_ROLE) {
splitWhitelisted[SPLIT_WHITELIST_ANY_ADDRESS] = true;
emit SplitWhitelistSet(SPLIT_WHITELIST_ANY_ADDRESS, true);
}
/// @notice Return true if any address is whitelisted or an `_account`.
function canSplit(address _account) public view virtual returns (bool) {
// Only allow split to whitelisted accounts.
return splitWhitelisted[SPLIT_WHITELIST_ANY_ADDRESS] || splitWhitelisted[_account];
}
/*//////////////////////////////////////////////////////////////
Getters: ERC721 Functions
//////////////////////////////////////////////////////////////*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) public view returns (bool) {
return IERC721EMB(lockNFT).isApprovedOrOwner(_spender, _tokenId);
}
/// @notice Fetch all NFTs owned by an address by leveraging the ERC721Enumerable interface
/// @param _owner Address to query
/// @return tokenIds Array of token IDs owned by the address
function ownedTokens(address _owner) public view returns (uint256[] memory tokenIds) {
IERC721EMB enumerable = IERC721EMB(lockNFT);
uint256 balance = enumerable.balanceOf(_owner);
uint256[] memory tokens = new uint256[](balance);
for (uint256 i = 0; i < balance; i++) {
tokens[i] = enumerable.tokenOfOwnerByIndex(_owner, i);
}
return tokens;
}
/*///////////////////////////////////////////////////////////////
Getters: Voting
//////////////////////////////////////////////////////////////*/
/// @return The voting power of the NFT at the current block
function votingPower(uint256 _tokenId) public view returns (uint256) {
return votingPowerAt(_tokenId, block.timestamp);
}
/// @return The voting power of the NFT at a specific timestamp
function votingPowerAt(uint256 _tokenId, uint256 _t) public view returns (uint256) {
return IEscrowCurve(curve).votingPowerAt(_tokenId, _t);
}
/// @return The total voting power at the current block
function totalVotingPower() external view returns (uint256) {
return totalVotingPowerAt(block.timestamp);
}
/// @return The total voting power at a specific timestamp
function totalVotingPowerAt(uint256 _timestamp) public view returns (uint256) {
return IEscrowCurve(curve).supplyAt(_timestamp);
}
/// @return The details of the underlying lock for a given veNFT
function locked(uint256 _tokenId) public view returns (LockedBalance memory) {
return _locked[_tokenId];
}
/// @return accountVotingPower The voting power of an account at the current block
/// @dev We cannot do historic voting power at this time because we don't current track
/// histories of token transfers.
function votingPowerForAccount(
address _account
) external view returns (uint256 accountVotingPower) {
uint256[] memory tokens = ownedTokens(_account);
for (uint256 i = 0; i < tokens.length; i++) {
accountVotingPower += votingPowerAt(tokens[i], block.timestamp);
}
}
/// @notice Checks if the NFT is currently voting. We require the user to reset their votes if so.
function isVoting(uint256 _tokenId) public view returns (bool) {
// If token doesn't exist, it reverts.
address owner = IERC721EMB(lockNFT).ownerOf(_tokenId);
// If token is not delegated, delegatee wouldn't exist, so we return false.
bool isTokenDelegated = IEscrowIVotesAdapter(ivotesAdapter).tokenIsDelegated(_tokenId);
if (!isTokenDelegated) return false;
// If token is delegated, it will always have a delegatee.
address delegatee = IEscrowIVotesAdapter(ivotesAdapter).delegates(owner);
return IAddressGaugeVoter(voter).isVoting(delegatee);
}
/*//////////////////////////////////////////////////////////////
ESCROW LOGIC
//////////////////////////////////////////////////////////////*/
function createLock(uint256 _value) external nonReentrant whenNotPaused returns (uint256) {
return _createLockFor(_value, _msgSender());
}
/// @notice Creates a lock on behalf of someone else.
function createLockFor(
uint256 _value,
address _to
) external nonReentrant whenNotPaused returns (uint256) {
return _createLockFor(_value, _to);
}
/// @dev Deposit `_value` tokens for `_to` starting at next deposit interval
/// @param _value Amount to deposit
/// @param _to Address to deposit
function _createLockFor(uint256 _value, address _to) internal returns (uint256) {
if (_value == 0) revert ZeroAmount();
if (_value < minDeposit) revert AmountTooSmall();
// query the duration lib to get the next time we can deposit
uint256 startTime = IClock(clock).epochPrevCheckpointTs();
// increment the total locked supply and get the new tokenId
totalLocked += _value;
uint256 newTokenId = ++lastLockId;
// Record the block timestamp for the new tokenId to prevent withdrawals in the same block.
withdrawalLock[newTokenId] = block.timestamp;
// write the lock and checkpoint the voting power
LockedBalance memory lock = LockedBalance(_value.toUint208(), startTime.toUint48());
_locked[newTokenId] = lock;
// we don't allow edits in this implementation, so only the new lock is used
_checkpoint(newTokenId, LockedBalance(0, 0), lock);
uint256 balanceBefore = IERC20(token).balanceOf(address(this));
// transfer the tokens into the contract
IERC20(token).safeTransferFrom(_msgSender(), address(this), _value);
// we currently don't support tokens that adjust balances on transfer
if (IERC20(token).balanceOf(address(this)) != balanceBefore + _value)
revert TransferBalanceIncorrect();
// Update `_to`'s delegate power.
_moveDelegateVotes(address(0), _to, newTokenId, lock);
// mint the NFT before and emit the event to complete the lock
IERC721EMB(lockNFT).mint(_to, newTokenId);
emit Deposit(_to, newTokenId, startTime, _value, totalLocked);
return newTokenId;
}
/// @inheritdoc IMerge
function merge(uint256 _from, uint256 _to) public whenNotPaused {
address sender = _msgSender();
if (_from == _to) revert SameNFT();
address ownerFrom = IERC721EMB(lockNFT).ownerOf(_from);
address ownerTo = IERC721EMB(lockNFT).ownerOf(_to);
// Both nfts must have the same owner.
if (ownerFrom != ownerTo) revert NotSameOwner();
// sender can either be approved or owner.
if (!isApprovedOrOwner(sender, _from) || !isApprovedOrOwner(sender, _to)) {
revert NotApprovedOrOwner();
}
LockedBalance memory oldLockedFrom = _locked[_from];
LockedBalance memory oldLockedTo = _locked[_to];
if (!canMerge(oldLockedFrom, oldLockedTo)) {
revert CannotMerge(_from, _to);
}
// If `_from` was created in this block, or if another token was merged into `_from` in this block,
// record the current timestamp for `_to` so that withdrawals for it are blocked in the same block.
if (withdrawalLock[_from] == block.timestamp) {
withdrawalLock[_to] = block.timestamp;
}
// We only allow merge when both tokens have the same owner.
// After the merge, owner still should have the same voting power
// as one token gets merged into another. For this reason,
// We call `_moveDelegateVotes` with empty locked, so it doesn't
// reduce/increase the same voting power for gas efficiency.
IEscrowIVotesAdapter(ivotesAdapter).mergeDelegateVotes(
IDelegateMoveVoteRecipient.TokenLock(ownerFrom, _from, oldLockedFrom),
IDelegateMoveVoteRecipient.TokenLock(ownerFrom, _to, oldLockedTo)
);
// Update for `_from`.
// Note that on the checkpoint, we still don't
// remove `start` for historical reasons.
IERC721EMB(lockNFT).burn(_from);
_locked[_from] = LockedBalance(0, 0);
_checkpoint(_from, oldLockedFrom, LockedBalance(0, oldLockedFrom.start));
// update for `_to`.
uint208 newLockedAmount = oldLockedFrom.amount + oldLockedTo.amount;
_checkpoint(_to, oldLockedTo, LockedBalance(newLockedAmount, oldLockedTo.start));
_locked[_to] = LockedBalance(newLockedAmount, oldLockedTo.start);
emit Merged(sender, _from, _to, oldLockedFrom.amount, oldLockedTo.amount, newLockedAmount);
}
/// @inheritdoc IMerge
function canMerge(
LockedBalance memory _fromLocked,
LockedBalance memory _toLocked
) public view returns (bool) {
uint256 maxTime = IEscrowCurve(curve).maxTime();
uint256 fromLockedEnd = _fromLocked.start + maxTime;
uint256 toLockedEnd = _toLocked.start + maxTime;
// Tokens either must have the same start dates or both must be mature.
if (
(_toLocked.start != _fromLocked.start) &&
(toLockedEnd >= block.timestamp || fromLockedEnd >= block.timestamp)
) {
return false;
}
return true;
}
/// @inheritdoc ISplit
function split(uint256 _from, uint256 _value) public whenNotPaused returns (uint256) {
if (_value == 0) revert ZeroAmount();
address sender = _msgSender();
// For some erc721, `ownerOf` reverts and for some,
// it returns address(0). For safety, if it doesn't revert,
// we also check if it's not address(0).
address owner = IERC721EMB(lockNFT).ownerOf(_from);
if (owner == address(0)) revert NoOwner();
if (!canSplit(owner)) revert SplitNotWhitelisted();
// Sender must either be approved or the owner.
if (!isApprovedOrOwner(sender, _from)) revert NotApprovedOrOwner();
LockedBalance memory locked_ = _locked[_from];
if (locked_.amount <= _value) revert SplitAmountTooBig();
// Ensure that amounts of new tokens will be greater than `minDeposit`.
uint208 amount1 = locked_.amount - _value.toUint208();
uint208 amount2 = _value.toUint208();
if (amount1 < minDeposit || amount2 < minDeposit) {
revert AmountTooSmall();
}
// update for `_from`.
_checkpoint(_from, locked_, LockedBalance(amount1, locked_.start));
_locked[_from] = LockedBalance(amount1, locked_.start);
uint256 newTokenId = ++lastLockId;
// preserve the withdrawal lock for `_from` if it exists.
if (withdrawalLock[_from] == block.timestamp) {
withdrawalLock[newTokenId] = block.timestamp;
}
// owner gets minted a new tokenId. Since `split` function
// just splits the same amount into two tokenIds, there's no need
// to update voting power on ivotesAdapter, as total doesn't change.
// We still call `_moveDelegateVotes` with zero LockedBalance to
// make sure we update delegatee's token count due to newtokenId.
IEscrowIVotesAdapter(ivotesAdapter).splitDelegateVotes(
IDelegateMoveVoteRecipient.TokenLock(owner, _from, LockedBalance(0, 0)),
IDelegateMoveVoteRecipient.TokenLock(owner, newTokenId, LockedBalance(0, 0))
);
// update for `newTokenId`.
locked_.amount = amount2;
_createSplitNFT(owner, newTokenId, locked_);
emit Split(_from, newTokenId, sender, amount1, amount2);
return newTokenId;
}
/// @notice creates a new token in checkpoint and mint.
/// @param _to The address to which new token id will be minted
/// @param _tokenId The id of the token that will be minted.
/// @param _newLocked New locked amount / start lock time for the new token
function _createSplitNFT(
address _to,
uint256 _tokenId,
LockedBalance memory _newLocked
) private {
_locked[_tokenId] = _newLocked;
_checkpoint(_tokenId, LockedBalance(0, 0), _newLocked);
IERC721EMB(lockNFT).mint(_to, _tokenId);
}
/// @notice Record per-user data to checkpoints. Used by VotingEscrow system.
/// @param _tokenId NFT token ID.
/// @dev Old locked balance is unused in the increasing case, at least in this implementation.
/// @param _fromLocked New locked amount / start lock time for the user
/// @param _newLocked New locked amount / start lock time for the user
function _checkpoint(
uint256 _tokenId,
LockedBalance memory _fromLocked,
LockedBalance memory _newLocked
) private {
IEscrowCurve(curve).checkpoint(_tokenId, _fromLocked, _newLocked);
}
/*//////////////////////////////////////////////////////////////
Exit and Withdraw Logic
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IVotingEscrowExiting
function currentExitingAmount() public view returns (uint256 total) {
IERC721EMB enumerable = IERC721EMB(lockNFT);
uint256 balance = enumerable.balanceOf(address(this));
for (uint256 i = 0; i < balance; i++) {
uint256 tokenId = enumerable.tokenOfOwnerByIndex(address(this), i);
total += locked(tokenId).amount;
}
}
/// @notice Resets the votes and begins the withdrawal process for a given tokenId
/// @dev Convenience function, the user must have authorized this contract to act on their behalf.
/// For backwards compatibility, even though `reset` call to gauge voter has been removed,
/// we still keep the function with the same name.
function resetVotesAndBeginWithdrawal(uint256 _tokenId) external whenNotPaused {
beginWithdrawal(_tokenId);
}
/// @notice Enters a tokenId into the withdrawal queue by transferring to this contract and creating a ticket.
/// @param _tokenId The tokenId to begin withdrawal for. Will be transferred to this contract before burning.
/// @dev The user must not have active votes in the voter contract.
function beginWithdrawal(uint256 _tokenId) public nonReentrant whenNotPaused {
// in the event of an increasing curve, 0 voting power means voting isn't active
if (votingPower(_tokenId) == 0) revert CannotExit();
// Safety checks:
// 1. Prevent creating a lock and starting withdrawal in the same block.
// 2. Prevent withdrawals if another token created in the same block
// was merged into `_tokenId`. Even though `_tokenId` itself was
// created in a previous block, the merged portion is "fresh" and
// would still be withdrawable without restriction.
IEscrowCurve.TokenPoint memory point = IEscrowCurve(curve).tokenPointHistory(_tokenId, 1);
if (block.timestamp == withdrawalLock[_tokenId]) {
revert CannotWithdrawInSameBlock();
}
address owner = IERC721EMB(lockNFT).ownerOf(_tokenId);
// we can remove the user's voting power as it's no longer locked
LockedBalance memory locked_ = _locked[_tokenId];
_checkpoint(_tokenId, locked_, LockedBalance(0, locked_.start));
// transfer NFT to this and queue the exit
IERC721EMB(lockNFT).transferFrom(_msgSender(), address(this), _tokenId);
IExitQueue(queue).queueExit(_tokenId, owner);
}
/// @notice Allows cancellation of a pending withdrawal request
/// @dev The caller must be one that also called `beginWithdrawal`.
/// @param _tokenId The tokenId to cancel the withdrawal request for.
function cancelWithdrawalRequest(uint256 _tokenId) public nonReentrant whenNotPaused {
address owner = IExitQueue(queue).ticketHolder(_tokenId);
address sender = _msgSender();
if (owner != sender) {
revert NotTicketHolder();
}
_checkpoint(_tokenId, LockedBalance(0, _locked[_tokenId].start), _locked[_tokenId]);
IExitQueue(queue).cancelExit(_tokenId);
IERC721EMB(lockNFT).transferFrom(address(this), sender, _tokenId);
}
/// @notice Withdraws tokens from the contract
function withdraw(uint256 _tokenId) external nonReentrant whenNotPaused {
address sender = _msgSender();
// we force the sender to be the ticket holder
if (!(IExitQueue(queue).ticketHolder(_tokenId) == sender)) revert NotTicketHolder();
// check that this ticket can exit
if (!(IExitQueue(queue).canExit(_tokenId))) revert CannotExit();
LockedBalance memory oldLocked = _locked[_tokenId];
uint256 value = oldLocked.amount;
// check for fees to be transferred
// do this before clearing the lock or it will be incorrect
uint256 fee = IExitQueue(queue).exit(_tokenId);
if (fee > 0) {
IERC20(token).safeTransfer(address(queue), fee);
}
// clear out the token data
_locked[_tokenId] = LockedBalance(0, 0);
totalLocked -= value;
// Burn the NFT and transfer the tokens to the user
IERC721EMB(lockNFT).burn(_tokenId);
IERC20(token).safeTransfer(sender, value - fee);
emit Withdraw(sender, _tokenId, value - fee, block.timestamp, totalLocked);
}
/// @notice withdraw excess tokens from the contract - possibly by accident
function sweep() external nonReentrant auth(SWEEPER_ROLE) {
// if there are extra tokens in the contract
// balance will be greater than the total locked
uint balance = IERC20(token).balanceOf(address(this));
uint excess = balance - totalLocked;
// if there isn't revert the tx
if (excess == 0) revert NothingToSweep();
// if there is, send them to the caller
IERC20(token).safeTransfer(_msgSender(), excess);
emit Sweep(_msgSender(), excess);
}
/// @notice the sweeper can send NFTs mistakenly sent to the contract to a designated address
/// @param _tokenId the tokenId to sweep - must be currently in this contract
/// @param _to the address to send the NFT to - must be a whitelisted address for transfers
/// @dev Cannot sweep NFTs that are in the exit queue for obvious reasons
function sweepNFT(uint256 _tokenId, address _to) external nonReentrant auth(SWEEPER_ROLE) {
// if the token id is not in the contract, revert
if (IERC721EMB(lockNFT).ownerOf(_tokenId) != address(this)) revert NothingToSweep();
// if the token id is in the queue, we cannot sweep it
if (IExitQueue(queue).ticketHolder(_tokenId) != address(0)) revert CannotExit();
IERC721EMB(lockNFT).transferFrom(address(this), _to, _tokenId);
emit SweepNFT(_to, _tokenId);
}
/*//////////////////////////////////////////////////////////////
Moving Delegation Votes Logic
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IDelegateMoveVoteCaller
function moveDelegateVotes(address _from, address _to, uint256 _tokenId) public whenNotPaused {
if (msg.sender != lockNFT) revert OnlyLockNFT();
LockedBalance memory locked_ = _locked[_tokenId];
_moveDelegateVotes(_from, _to, _tokenId, locked_);
}
function _moveDelegateVotes(
address _from,
address _to,
uint256 _tokenId,
LockedBalance memory _lockedBalance
) private {
IEscrowIVotesAdapter(ivotesAdapter).moveDelegateVotes(_from, _to, _tokenId, _lockedBalance);
}
function updateVotingPower(address _from, address _to) public whenNotPaused {
if (msg.sender != ivotesAdapter) revert OnlyIVotesAdapter();
IAddressGaugeVoter(voter).updateVotingPower(_from, _to);
}
/*///////////////////////////////////////////////////////////////
UUPS Upgrade
//////////////////////////////////////////////////////////////*/
/// @notice Returns the address of the implementation contract in the [proxy storage slot](https://eips.ethereum.org/EIPS/eip-1967) slot the [UUPS proxy](https://eips.ethereum.org/EIPS/eip-1822) is pointing to.
/// @return The address of the implementation contract.
function implementation() public view returns (address) {
return _getImplementation();
}
/// @notice Internal method authorizing the upgrade of the contract via the [upgradeability mechanism for UUPS proxies](https://docs.openzeppelin.com/contracts/4.x/api/proxy#UUPSUpgradeable) (see [ERC-1822](https://eips.ethereum.org/EIPS/eip-1822)).
function _authorizeUpgrade(address) internal virtual override auth(ESCROW_ADMIN_ROLE) {}
/// @dev Reserved storage space to allow for layout changes in the future.
/// Please note that the reserved slot number in previous version(39) was set
/// incorrectly as 39 instead of 40. Changing it to 40 now would overwrite existing slot values,
/// resulting in the loss of state. Therefore, we will continue using 36 in this version.
/// For future versions, any new variables should be added by subtracting from 36.
uint256[36] private __gap;
}
"
},
"lib/ve-governance/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol": {
"content": "// 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 IERC20Upgradeable {
/**
* @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);
}
"
},
"lib/ve-governance/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
"
},
"lib/ve-governance/src/lock/IERC721EMB.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {
IERC721Enumerable
} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
interface IERC721EnumerableMintableBurnable is IERC721Enumerable {
function mint(address to, uint256 tokenId) external;
function burn(uint256 tokenId) external;
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}
"
},
"lib/ve-governance/lib/osx-commons/contracts/src/dao/IDAO.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.8;
/// @title IDAO
/// @author Aragon X - 2022-2024
/// @notice The interface required for DAOs within the Aragon App DAO framework.
/// @custom:security-contact sirt@aragon.org
interface IDAO {
/// @notice Checks if an address has permission on a contract via a permission identifier and considers if `ANY_ADDRESS` was used in the granting process.
/// @param _where The address of the contract.
/// @param _who The address of a EOA or contract to give the permissions.
/// @param _permissionId The permission identifier.
/// @param _data The optional data passed to the `PermissionCondition` registered.
/// @return Returns true if the address has permission, false if not.
function hasPermission(
address _where,
address _who,
bytes32 _permissionId,
bytes memory _data
) external view returns (bool);
/// @notice Updates the DAO metadata (e.g., an IPFS hash).
/// @param _metadata The IPFS hash of the new metadata object.
function setMetadata(bytes calldata _metadata) external;
/// @notice Emitted when the DAO metadata is updated.
/// @param metadata The IPFS hash of the new metadata object.
event MetadataSet(bytes metadata);
/// @notice Emitted when a standard callback is registered.
/// @param interfaceId The ID of the interface.
/// @param callbackSelector The selector of the callback function.
/// @param magicNumber The magic number to be registered for the callback function selector.
event StandardCallbackRegistered(
bytes4 interfaceId,
bytes4 callbackSelector,
bytes4 magicNumber
);
/// @notice Deposits (native) tokens to the DAO contract with a reference string.
/// @param _token The address of the token or address(0) in case of the native token.
/// @param _amount The amount of tokens to deposit.
/// @param _reference The reference describing the deposit reason.
function deposit(address _token, uint256 _amount, string calldata _reference) external payable;
/// @notice Emitted when a token deposit has been made to the DAO.
/// @param sender The address of the sender.
/// @param token The address of the deposited token.
/// @param amount The amount of tokens deposited.
/// @param _reference The reference describing the deposit reason.
event Deposited(
address indexed sender,
address indexed token,
uint256 amount,
string _reference
);
/// @notice Emitted when a native token deposit has been made to the DAO.
/// @dev This event is intended to be emitted in the `receive` function and is therefore bound by the gas limitations for `send`/`transfer` calls introduced by [ERC-2929](https://eips.ethereum.org/EIPS/eip-2929).
/// @param sender The address of the sender.
/// @param amount The amount of native tokens deposited.
event NativeTokenDeposited(address sender, uint256 amount);
/// @notice Setter for the trusted forwarder verifying the meta transaction.
/// @param _trustedForwarder The trusted forwarder address.
function setTrustedForwarder(address _trustedForwarder) external;
/// @notice Getter for the trusted forwarder verifying the meta transaction.
/// @return The trusted forwarder address.
function getTrustedForwarder() external view returns (address);
/// @notice Emitted when a new TrustedForwarder is set on the DAO.
/// @param forwarder the new forwarder address.
event TrustedForwarderSet(address forwarder);
/// @notice Checks whether a signature is valid for a provided hash according to [ERC-1271](https://eips.ethereum.org/EIPS/eip-1271).
/// @param _hash The hash of the data to be signed.
/// @param _signature The signature byte array associated with `_hash`.
/// @return Returns the `bytes4` magic value `0x1626ba7e` if the signature is valid and `0xffffffff` if not.
function isValidSignature(bytes32 _hash, bytes memory _signature) external returns (bytes4);
/// @notice Registers an ERC standard having a callback by registering its [ERC-165](https://eips.ethereum.org/EIPS/eip-165) interface ID and callback function signature.
/// @param _interfaceId The ID of the interface.
/// @param _callbackSelector The selector of the callback function.
/// @param _magicNumber The magic number to be registered for the function signature.
function registerStandardCallback(
bytes4 _interfaceId,
bytes4 _callbackSelector,
bytes4 _magicNumber
) external;
/// @notice Removed function being left here to not corrupt the IDAO interface ID. Any call will revert.
/// @dev Introduced in v1.0.0. Removed in v1.4.0.
function setSignatureValidator(address) external;
}
"
},
"lib/ve-governance/src/voting/IAddressGaugeVoter.sol": {
"content": "/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IGaugeVoter.sol";
interface IAddressGaugeVote {
/// @param votes gauge => votes cast at that time
/// @param gaugesVotedFor array of gauges we have active votes for
/// @param usedVotingPower total voting power used at the time of the vote
/// @dev this changes so we need an historic snapshot
/// @param lastVoted is the last time the user voted
struct AddressVoteData {
mapping(address => uint256) voteWeights;
address[] gaugesVotedFor;
uint256 usedVotingPower;
uint256 lastVoted;
}
/// @param weight proportion of voting power the address will allocate to the gauge. Will be normalised.
/// @param gauge address of the gauge to vote for
struct GaugeVote {
uint256 weight;
address gauge;
}
}
/*///////////////////////////////////////////////////////////////
Gauge Voter
//////////////////////////////////////////////////////////////*/
interface IAddressGaugeVoterEvents {
/// @param votingPowerCastForGauge votes cast by this address for this gauge in this vote
/// @param totalVotingPowerInGauge total voting power in the gauge at the time of the vote, after applying the vote
/// @param totalVotingPowerInContract total voting power in the contract at the time of the vote, after applying the vote
event Voted(
address indexed voter,
address indexed gauge,
uint256 indexed epoch,
uint256 votingPowerCastForGauge,
uint256 totalVotingPowerInGauge,
uint256 totalVotingPowerInContract,
uint256 timestamp
);
/// @param votingPowerRemovedFromGauge votes removed by this address for this gauge, at the time of this rest
/// @param totalVotingPowerInGauge total voting power in the gauge at the time of the reset, after applying the reset
/// @param totalVotingPowerInContract total voting power in the contract at the time of the reset, after applying the reset
event Reset(
address indexed voter,
address indexed gauge,
uint256 indexed epoch,
uint256 votingPowerRemovedFromGauge,
uint256 totalVotingPowerInGauge,
uint256 totalVotingPowerInContract,
uint256 timestamp
);
}
interface IAddressGaugeVoterErrors {
error VotingInactive();
error NotApprovedOrOwner();
error GaugeDoesNotExist(address _pool);
error GaugeInactive(address _gauge);
error DoubleVote();
error NoVotes();
error NoVotingPower();
error NotCurrentlyVoting();
error OnlyEscrow();
error UpdateVotingPowerHookNotEnabled();
error AlreadyVoted(address _address);
}
interface IAddressGaugeVoter is
IAddressGaugeVoterEvents,
IAddressGaugeVoterErrors,
IAddressGaugeVote,
IGaugeManager,
IGauge
{
/// @notice Called by users to vote for pools. Votes distributed proportionally based on weights.
/// @param _votes Array of votes to be cast, contains gauge address and weight.
function vote(GaugeVote[] memory _votes) external;
/// @notice Called by users to reset voting state. Required when withdrawing or transferring veNFT.
function reset() external;
/// @notice Can be called to check if an address is currently voting
function isVoting(address _address) external view returns (bool);
function updateVotingPower(address _from, address _to) external;
}
/*///////////////////////////////////////////////////////////////
Address Gauge Voter
//////////////////////////////////////////////////////////////*/
interface IAddressGaugeVoterStorageEventsErrors is
IGaugeManagerEvents,
IGaugeManagerErrors,
IAddressGaugeVoterEvents,
IAddressGaugeVoterErrors
{
}
"
},
"lib/ve-governance/src/curve/IEscrowCurveIncreasing_v1_2_0.sol": {
"content": "/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IEscrowCurveIncreasing.sol";
import "../IDeprecated.sol";
/*///////////////////////////////////////////////////////////////
Global Curve
//////////////////////////////////////////////////////////////*/
interface IEscrowCurveGlobalStorage {
/// @notice Captures the shape of the aggregate voting curve at a specific point in time
/// @param bias The y intercept of the aggregate voting curve at the given time
/// @param slope The slope of the aggregate voting curve at the given time
/// @param writtenTs The timestamp at which the we last updated the aggregate voting curve
struct GlobalPoint {
int256 bias;
int256 slope;
uint48 writtenTs;
}
}
interface IEscrowCurveGlobal is IEscrowCurveGlobalStorage {
/// @notice Returns the global point at the passed epoch
/// @param _index The index in an array to return the point for
function globalPointHistory(uint256 _index) external view returns (GlobalPoint memory);
}
/*///////////////////////////////////////////////////////////////
Token Curve
//////////////////////////////////////////////////////////////*/
interface IEscrowCurveTokenV1_2_0 is IEscrowCurveTokenStorage {
/// @notice Returns the latest index of the tokenId which can be used
/// to retrive token point from `tokenPointHistory` function.
/// @dev This has been renamed to `tokenPointLatestIndex` in the latest upgrade, but
/// for backwards-compatibility, the function still stays in the contract.
/// Note that we treat it as deprecated, So use `tokenPointLatestIndex` instead.
/// @return The latest index of the token id.
function tokenPointIntervals(uint256 _tokenId) external view returns (uint256);
/// @notice Returns the latest index of the tokenId which can be used
/// to retrive token point from `tokenPointHistory` function.
/// @param _tokenId The NFT to return the latest token point index
/// @return The latest index of the token id.
function tokenPointLatestIndex(uint256 _tokenId) external view returns (uint256);
/// @notice Returns the TokenPoint at the passed `_index`.
/// @param _tokenId The NFT to return the TokenPoint for
/// @param _index The index to return the TokenPoint at.
function tokenPointHistory(
uint256 _tokenId,
uint256 _index
) external view returns (TokenPoint memory);
}
interface IEscrowCurveMaxTime is IEscrowCurveErrorsAndEvents {
/// @return The max time allowed for the lock duration.
function maxTime() external view returns (uint256);
}
/*///////////////////////////////////////////////////////////////
INCREASING CURVE
//////////////////////////////////////////////////////////////*/
interface IEscrowCurveIncreasingV1_2_0 is
IEscrowCurveCore,
IEscrowCurveMath,
IEscrowCurveTokenV1_2_0,
IEscrowCurveMaxTime,
IEscrowCurveGlobal,
IDeprecated
{}
interface IEscrowCurveIncreasingV1_2_0_NoSupply is
IEscrowCurveCore,
IEscrowCurveMath,
IEscrowCurveTokenV1_2_0,
IEscrowCurveMaxTime,
IDeprecated
{}
"
},
"lib/ve-governance/src/queue/IExitQueue.sol": {
"content": "/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IExitQueueCoreErrorsAndEvents {
error OnlyEscrow();
error AlreadyQueued();
error ZeroAddress();
error CannotExit();
error NoLockBalance();
event ExitQueued(uint256 indexed tokenId, address indexed holder, uint256 exitDate);
event Exit(uint256 indexed tokenId, uint256 fee);
}
interface ITicket {
struct Ticket {
address holder;
uint256 exitDate;
}
}
/*///////////////////////////////////////////////////////////////
Fee Collection
//////////////////////////////////////////////////////////////*/
interface IExitQueueFeeErrorsAndEvents {
error FeeTooHigh(uint256 maxFee);
event Withdraw(address indexed to, uint256 amount);
event FeePercentSet(uint256 feePercent);
}
interface IExitQueueFee is IExitQueueFeeErrorsAndEvents {
/// @notice optional fee charged for exiting the queue
function feePercent() external view returns (uint256);
/// @notice The exit queue manager can set the fee
function setFeePercent(uint256 _fee) external;
/// @notice withdraw accumulated fees
function withdraw(uint256 _amount) external;
}
/*///////////////////////////////////////////////////////////////
Cooldown
//////////////////////////////////////////////////////////////*/
interface IExitQueueCooldownErrorsAndEvents {
error CooldownTooHigh();
event CooldownSet(uint48 cooldown);
}
interface IExitQueueCooldown is IExitQueueCooldownErrorsAndEvents {
/// @notice time in seconds between exit and withdrawal
function cooldown() external view returns (uint48);
/// @notice The exit queue manager can set the cooldown period
/// @param _cooldown time in seconds between exit and withdrawal
function setCooldown(uint48 _cooldown) external;
}
/*///////////////////////////////////////////////////////////////
Min Lock
//////////////////////////////////////////////////////////////*/
interface IExitMinLockCooldownErrorsAndEvents {
event MinLockSet(uint48 minLock);
error MinLockOutOfBounds();
error MinLockNotReached(uint256 tokenId, uint48 minLock, uint48 earliestExitDate);
}
interface IExitQueueMinLock is IExitMinLockCooldownErrorsAndEvents {
/// @notice minimum time from the original lock date before one can enter the queue
function minLock() external view returns (uint48);
/// @notice The exit queue manager can set the minimum lock time
function setMinLock(uint48 _cooldown) external;
}
/*///////////////////////////////////////////////////////////////
Exit Queue
//////////////////////////////////////////////////////////////*/
interface IExitQueueCancelErrorsAndEvents {
error CannotCancelExit();
event ExitCancelled(uint256 indexed tokenId, address indexed holder);
}
interface IExitQueueCancel {
function cancelExit(uint256 _tokenId) external;
}
/*///////////////////////////////////////////////////////////////
Exit Queue
//////////////////////////////////////////////////////////////*/
interface IExitQueueErrorsAndEvents is
IExitQueueCoreErrorsAndEvents,
IExitQueueFeeErrorsAndEvents,
IExitQueueCooldownErrorsAndEvents,
IExitMinLockCooldownErrorsAndEvents,
IExitQueueCancelErrorsAndEvents
{}
interface IExitQueue is
IExitQueueErrorsAndEvents,
ITicket,
IExitQueueFee,
IExitQueueCooldown,
IExitQueueMinLock,
IExitQueueCancel
{
/// @notice tokenId => Ticket
function queue(uint256 _tokenId) external view returns (Ticket memory);
/// @notice queue an exit for a given tokenId, granting the ticket to the passed holder
/// @param _tokenId the tokenId to queue an exit for
/// @param _ticketHolder the address that will be granted the ticket
function queueExit(uint256 _tokenId, address _ticketHolder) external;
function cancelExit(uint256 _tokenId) external;
/// @notice exit the queue for a given tokenId. Requires the cooldown period to have passed
/// @return exitAmount the amount of tokens that can be withdrawn
function exit(uint256 _tokenId) external returns (uint256 exitAmount);
/// @return true if the tokenId corresponds to a valid ticket and the cooldown period has passed
function canExit(uint256 _tokenId) external view returns (bool);
/// @return the ticket holder for a given tokenId
function ticketHolder(uint256 _tokenId) external view returns (address);
}
"
},
"lib/ve-governance/src/escrow/IVotingEscrowIncreasing_v1_2_0.sol": {
"content": "/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IVotingEscrowIncreasing.sol";
import {IEscrowIVotesAdapter, IDelegateUpdateVotingPower} from "@delegation/IEscrowIVotesAdapter.sol";
interface IVotingEscrowExiting {
/// @notice How much amount has been exiting.
/// @return total The total amount for which beginWithdrawal has been called
/// but withdraw has not yet been executed.
function currentExitingAmount() external view returns (uint256);
}
interface IMergeEventsAndErrors {
event Merged(
address indexed _sender,
uint256 indexed _from,
uint256 indexed _to,
uint208 _amountFrom,
uint208 _amountTo,
uint208 _amountFinal
);
error CannotMerge(uint256 _from, uint256 _to);
error SameNFT();
}
interface IMerge is ILockedBalanceIncreasing, IMergeEventsAndErrors {
/// @notice Merge two tokens - i.e `from` into `_to`.
/// @param _from The token id from which merge is occuring
/// @param _to The token id to which `_from` is merging
function merge(uint256 _from, uint256 _to) external;
/// @notice Whether 2 tokens can be merged.
/// @param _from The token id from which merge should occur.
/// @param _to The token id to which `_from` should merge.
function canMerge(
LockedBalance memory _from,
LockedBalance memory _to
) external view returns (bool);
}
interface ISplitEventsAndErrors {
event Split(
uint256 indexed _from,
uint256 indexed newTokenId,
address _sender,
uint208 _splitAmount1,
uint208 _splitAmount2
);
event SplitWhitelistSet(address indexed account, bool status);
error SplitNotWhitelisted();
error SplitAmountTooBig();
}
interface ISplit is ISplitEventsAndErrors {
/// @notice Split token into two new, separate tokens.
/// @param _from The token id that should be split
/// @param _value The amount that determines how token is split
/// @return _newTokenId The new token id after split.
function split(
uint256 _from,
uint256 _value
) external returns (uint256 _newTokenId);
}
interface IDelegateMoveVoteCaller {
/// @notice After a token transfer, decreases `_from`'s voting power and increases `_to`'s voting power.
/// @dev Called upon a token transfer.
/// @param _from The current delegatee of `_tokenId`.
/// @param _to The new delegatee of `_tokenId`
/// @param _tokenId The token id that is being transferred.
function moveDelegateVotes(
address _from,
address _to,
uint256 _tokenId
) external;
}
interface IVotingEscrowIncreasingV1_2_0 is
IVotingEscrowIncreasing,
IVotingEscrowExiting,
IMerge,
ISplit,
IDelegateUpdateVotingPower,
IDelegateMoveVoteCaller
{}
"
},
"lib/ve-governance/src/clock/IClock_v1_2_0.sol": {
"content": "/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IClock.sol";
interface IClockV1_2_0 is IClock {
function epochPrevCheckpointTs() external view returns (uint256);
function resolveEpochPrevCheckpointTs(uint256 timestamp) external pure returns (uint256);
}
"
},
"lib/ve-governance/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to
* 0 before setting it to a non-zero value.
*/
function forceApprove(IERC20Upgradeable 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(
IERC20PermitUpgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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))) && AddressUpgradeable.isContract(address(token));
}
}
"
},
"lib/ve-governance/lib/openzeppelin-contracts-upgradeable/contracts/utils/math/SafeCastUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's
Submitted on: 2025-11-07 20:49:44
Comments
Log in to comment.
No comments yet.