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": {
"src/PepuLock.sol": {
"content": "// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable2Step.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./FullMath.sol";
/**
* @title PepuLock
* @dev A token locking contract that supports both simple time-locked tokens and vesting schedules.
* This contract allows users to lock ERC20 tokens for a specified period or create vesting schedules
* with TGE (Token Generation Event) releases and periodic unlocks. The contract charges a flat fee
* for each lock operation and maintains comprehensive tracking of all locked tokens.
*
* Features:
* - Simple time-locked tokens that unlock at a specific date
* - Vesting schedules with TGE percentage and periodic releases
* - Multiple vesting locks in a single transaction
* - Lock editing capabilities (amount and unlock date)
* - Comprehensive querying functions for locks and statistics
* - Fee collection mechanism
*
* @author PepuLock Team
*/
contract PepuLock is Ownable2Step, ReentrancyGuard {
using Address for address payable;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
using SafeERC20 for IERC20;
// =============================================== //
// ================== STRUCTURE ================== //
// =============================================== //
struct Lock {
uint256 id;
address token;
address owner;
uint256 amount;
uint256 lockDate;
uint256 tgeDate; // TGE date for vesting locks, unlock date for normal locks
uint256 tgeBps; // In bips. Is 0 for normal locks
uint256 cycle; // Is 0 for normal locks
uint256 cycleBps; // In bips. Is 0 for normal locks
uint256 unlockedAmount;
string description;
}
struct CumulativeLockInfo {
address token;
uint256 amount;
}
uint256 public constant TIMELOCK = 7 days;
uint256 public fee;
address public feeWallet;
uint256 public pendingFee;
uint256 public feeUpdateTime;
Lock[] private _locks;
mapping(address => EnumerableSet.UintSet) private _userLockIds;
EnumerableSet.AddressSet private _lockedTokens;
mapping(address => CumulativeLockInfo) public cumulativeLockInfo;
mapping(address => EnumerableSet.UintSet) private _tokenToLockIds;
// ============================================ //
// ================== EVENTS ================== //
// ============================================ //
event LockAdded(
uint256 indexed id,
address token,
address owner,
uint256 amount,
uint256 unlockDate
);
event LockUpdated(
uint256 indexed id,
address token,
address owner,
uint256 newAmount,
uint256 newUnlockDate
);
event LockRemoved(
uint256 indexed id,
address token,
address owner,
uint256 amount,
uint256 unlockedAt
);
event LockVested(
uint256 indexed id,
address token,
address owner,
uint256 amount,
uint256 remaining,
uint256 timestamp
);
event LockDescriptionChanged(uint256 lockId);
event FeeUpdated(uint256 newFee);
event FeeWalletUpdated(address newWallet);
event FeeProposed(uint256 newFee, uint256 effectiveTime);
event FeeProposalCancelled(uint256 cancelledFee);
// ============================================ //
// ================== ERRORS ================== //
// ============================================ //
error InvalidFeeWallet();
error InsufficientFee();
error InvalidUnlockTime();
error InvalidToken();
error ZeroAmount();
error InvalidTgeDate();
error InvalidCycle();
error InvalidTgeBps();
error InvalidCycleBps();
error InvalidTgeBpsAndCycleBps();
error LengthMismatched();
error NotLockOwner();
error LockAlreadyUnlocked();
error InvalidNewUnlockTime();
error InvalidNewAmount();
error InvalidIndex();
error NotTimeToUnlock();
error NothingToUnlock();
error InsufficientTokenTransfer();
error InvalidLockId();
error AmountCannotBeZero();
error TransferFailed();
error TimelockNotExpired();
error NoPendingFeeUpdate();
// =============================================== //
// ================== MODIFIERS ================== //
// =============================================== //
/**
* @dev Validates that the provided lock ID exists in the contract.
* @param lockId The ID of the lock to validate
*/
modifier validLock(uint256 lockId) {
if (lockId >= _locks.length) revert InvalidLockId();
_;
}
// ================================================= //
// ================== CONSTRUCTOR ================== //
// ================================================= //
/**
* @dev Initializes the contract with a fee wallet and initial fee.
* @param _owner The address of contract owner and where fees will be sent.
* @param _fee The initial flat fee for locking tokens.
*/
constructor(address _owner, uint256 _fee) Ownable(_owner) {
if (_owner == address(0)) revert InvalidFeeWallet();
if (_owner.code.length > 23) revert InvalidFeeWallet();
feeWallet = _owner;
fee = _fee;
}
// ======================================================== //
// ================== EXTERNAL FUNCTIONS ================== //
// ======================================================== //
/**
* @dev Proposes a new flat fee for locking tokens with a timelock delay. Only callable by the owner.
* Users get a 3-day warning period before the new fee takes effect.
* @param newFee The new fee amount in native tokens (wei).
*/
function proposeFee(uint256 newFee) external onlyOwner {
pendingFee = newFee;
feeUpdateTime = block.timestamp + TIMELOCK;
emit FeeProposed(newFee, feeUpdateTime);
}
/**
* @dev Applies the pending fee update after the timelock period has expired.
* Can be called by anyone once the timelock has expired.
*/
function applyFee() external {
if (feeUpdateTime == 0) revert NoPendingFeeUpdate();
if (block.timestamp < feeUpdateTime) revert TimelockNotExpired();
_applyFee();
}
/**
* @dev Cancels a pending fee update. Only callable by the owner.
* This allows the owner to cancel a fee proposal before it takes effect.
*/
function cancelFeeProposal() external onlyOwner {
if (feeUpdateTime == 0) revert NoPendingFeeUpdate();
uint256 cancelledFee = pendingFee;
pendingFee = 0;
feeUpdateTime = 0;
emit FeeProposalCancelled(cancelledFee);
}
/**
* @dev Updates the wallet address where fees are sent. Only callable by the owner.
* @param newWallet The new fee wallet address.
*/
function updateFeeWallet(address newWallet) external onlyOwner {
if (newWallet == address(0)) revert InvalidFeeWallet();
if (newWallet.code.length > 23) revert InvalidFeeWallet();
feeWallet = newWallet;
emit FeeWalletUpdated(newWallet);
}
/**
* @dev Creates a simple time-locked token lock that unlocks entirely at a specific date.
* @param owner The address that will own the lock and can unlock the tokens
* @param token The ERC20 token contract address to be locked
* @param amount The amount of tokens to lock
* @param unlockDate The timestamp when the tokens can be unlocked
* @param description A description for the lock
* @return id The unique identifier for the created lock
*/
function lock(
address owner,
address token,
uint256 amount,
uint256 unlockDate,
string memory description
) external payable nonReentrant returns (uint256 id) {
if (msg.value != fee) revert InsufficientFee();
if (token == address(0)) revert InvalidToken();
if (amount == 0) revert ZeroAmount();
if (unlockDate <= block.timestamp) revert InvalidUnlockTime();
(bool sent, ) = payable(feeWallet).call{value: msg.value}("");
if (!sent) revert TransferFailed();
id = _createLock(
owner,
token,
amount,
unlockDate,
0,
0,
0,
description
);
_safeTransferFromEnsureExactAmount(
token,
msg.sender,
address(this),
amount
);
_applyFee();
emit LockAdded(id, token, owner, amount, unlockDate);
return id;
}
/**
* @dev Creates a vesting lock with TGE release and periodic unlocks.
* @param owner The address that will own the lock and can unlock the tokens
* @param token The ERC20 token contract address to be locked
* @param amount The total amount of tokens to lock
* @param tgeDate The timestamp when TGE occurs and vesting begins
* @param tgeBps The percentage (in basis points) to release at TGE (1-9999)
* @param cycle The duration in seconds between each vesting release
* @param cycleBps The percentage (in basis points) to release each cycle (1-9999)
* @param description A description for the lock
* @return id The unique identifier for the created lock
*/
function vestingLock(
address owner,
address token,
uint256 amount,
uint256 tgeDate,
uint256 tgeBps,
uint256 cycle,
uint256 cycleBps,
string memory description
) external payable nonReentrant returns (uint256 id) {
if (msg.value != fee) revert InsufficientFee();
if (token == address(0)) revert InvalidToken();
if (amount == 0) revert ZeroAmount();
if (tgeDate <= block.timestamp) revert InvalidTgeDate();
if (cycle == 0) revert InvalidCycle();
if (tgeBps == 0 || tgeBps >= 10_000) revert InvalidTgeBps();
if (cycleBps == 0 || cycleBps >= 10_000) revert InvalidCycleBps();
if (tgeBps + cycleBps > 10_000) revert InvalidTgeBpsAndCycleBps();
(bool sent, ) = payable(feeWallet).call{value: msg.value}("");
if (!sent) revert TransferFailed();
id = _createLock(
owner,
token,
amount,
tgeDate,
tgeBps,
cycle,
cycleBps,
description
);
_safeTransferFromEnsureExactAmount(
token,
msg.sender,
address(this),
amount
);
_applyFee();
emit LockAdded(id, token, owner, amount, tgeDate);
return id;
}
/**
* @dev Creates multiple vesting locks with the same parameters for different owners and amounts.
* @param owners Array of addresses that will own each lock
* @param amounts Array of token amounts for each lock (must match owners length)
* @param token The ERC20 token contract address to be locked
* @param tgeDate The timestamp when TGE occurs and vesting begins
* @param tgeBps The percentage (in basis points) to release at TGE (1-9999)
* @param cycle The duration in seconds between each vesting release
* @param cycleBps The percentage (in basis points) to release each cycle (1-9999)
* @param description A description for all locks
* @return Array of unique identifiers for the created locks
*/
function multipleVestingLock(
address[] calldata owners,
uint256[] calldata amounts,
address token,
uint256 tgeDate,
uint256 tgeBps,
uint256 cycle,
uint256 cycleBps,
string memory description
) external payable nonReentrant returns (uint256[] memory) {
if (msg.value != fee * owners.length) revert InsufficientFee();
if (token == address(0)) revert InvalidToken();
if (owners.length != amounts.length) revert LengthMismatched();
if (tgeDate <= block.timestamp) revert InvalidTgeDate();
if (cycle == 0) revert InvalidCycle();
if (tgeBps == 0 || tgeBps >= 10_000) revert InvalidTgeBps();
if (cycleBps == 0 || cycleBps >= 10_000) revert InvalidCycleBps();
if (tgeBps + cycleBps > 10_000) revert InvalidTgeBpsAndCycleBps();
(bool sent, ) = payable(feeWallet).call{value: msg.value}("");
if (!sent) revert TransferFailed();
_applyFee();
return
_multipleVestingLock(
owners,
amounts,
token,
[tgeDate, tgeBps, cycle, cycleBps],
description
);
}
/**
* @dev Unlocks tokens from a lock. Handles both simple locks and vesting locks.
* For simple locks, unlocks all tokens if the unlock date has passed.
* For vesting locks, unlocks the currently available vested amount.
* @param lockId The ID of the lock to unlock tokens from
*/
function unlock(uint256 lockId) external validLock(lockId) nonReentrant {
Lock storage userLock = _locks[lockId];
if (userLock.owner != msg.sender) revert NotLockOwner();
if (userLock.tgeBps > 0) {
_vestingUnlock(userLock);
} else {
_normalUnlock(userLock);
}
_applyFee();
}
/**
* @dev Edits an existing lock to increase the amount and/or extend the unlock date.
* Can only increase amounts and extend dates, not decrease them.
* @param lockId The ID of the lock to edit
* @param newAmount The new total amount for the lock (must be >= current amount, 0 = no change)
* @param newUnlockDate The new unlock date (must be > current date, 0 = no change)
*/
function editLock(
uint256 lockId,
uint256 newAmount,
uint256 newUnlockDate
) external validLock(lockId) nonReentrant {
Lock storage userLock = _locks[lockId];
if (userLock.owner != msg.sender) revert NotLockOwner();
if (userLock.unlockedAmount != 0) revert LockAlreadyUnlocked();
if (newUnlockDate > 0) {
if (
newUnlockDate < userLock.tgeDate ||
newUnlockDate <= block.timestamp
) {
revert InvalidNewUnlockTime();
}
userLock.tgeDate = newUnlockDate;
}
if (newAmount > 0) {
if (newAmount < userLock.amount) {
revert InvalidNewAmount();
}
uint256 diff = newAmount - userLock.amount;
if (diff > 0) {
userLock.amount = newAmount;
CumulativeLockInfo storage tokenInfo = cumulativeLockInfo[
userLock.token
];
tokenInfo.amount = tokenInfo.amount + diff;
_safeTransferFromEnsureExactAmount(
userLock.token,
msg.sender,
address(this),
diff
);
}
}
_applyFee();
emit LockUpdated(
userLock.id,
userLock.token,
userLock.owner,
userLock.amount,
userLock.tgeDate
);
}
/**
* @dev Updates the description of an existing lock.
* @param lockId The ID of the lock to update
* @param description The new description for the lock
*/
function editLockDescription(
uint256 lockId,
string memory description
) external validLock(lockId) {
Lock storage userLock = _locks[lockId];
if (userLock.owner != msg.sender) revert NotLockOwner();
userLock.description = description;
emit LockDescriptionChanged(lockId);
}
/**
* @dev Calculates the amount of tokens that can currently be withdrawn from a vesting lock.
* @param lockId The ID of the lock to check
* @return The amount of tokens currently available for withdrawal
*/
function withdrawableTokens(
uint256 lockId
) external view returns (uint256) {
Lock memory userLock = getLockById(lockId);
return _withdrawableTokens(userLock);
}
/**
* @dev Returns the total number of locks created (including unlocked ones).
* @return The total count of all locks ever created
*/
function getTotalLockCount() external view returns (uint256) {
// Returns total lock count, regardless of whether it has been unlocked or not
return _locks.length;
}
/**
* @dev Returns the lock data at a specific index in the locks array.
* @param index The index of the lock to retrieve
* @return The Lock struct containing all lock information
*/
function getLockAt(uint256 index) external view returns (Lock memory) {
return _locks[index];
}
/**
* @dev Returns cumulative lock information for a token at a specific index.
* @param index The index in the locked tokens array
* @return CumulativeLockInfo struct with token address and total locked amount
*/
function getCumulativeTokenLockInfoAt(
uint256 index
) external view returns (CumulativeLockInfo memory) {
return cumulativeLockInfo[_lockedTokens.at(index)];
}
/**
* @dev Returns cumulative lock information for multiple tokens within a range.
* @param start The starting index (inclusive)
* @param end The ending index (inclusive, will be capped to array length)
* @return Array of CumulativeLockInfo structs
*/
function getCumulativeTokenLockInfo(
uint256 start,
uint256 end
) external view returns (CumulativeLockInfo[] memory) {
if (end >= _lockedTokens.length()) {
end = _lockedTokens.length() - 1;
}
uint256 length = end - start + 1;
CumulativeLockInfo[] memory lockInfo = new CumulativeLockInfo[](length);
uint256 currentIndex = 0;
for (uint256 i = start; i <= end; i++) {
lockInfo[currentIndex] = cumulativeLockInfo[_lockedTokens.at(i)];
currentIndex++;
}
return lockInfo;
}
/**
* @dev Returns the total number of unique tokens that have active locks.
* @return The count of unique locked tokens
*/
function totalTokenLockedCount() external view returns (uint256) {
return _lockedTokens.length();
}
/**
* @dev Returns all locks owned by a specific user.
* @param user The address to get locks for
* @return Array of Lock structs owned by the user
*/
function locksForUser(address user) external view returns (Lock[] memory) {
uint256 length = _userLockIds[user].length();
Lock[] memory userLocks = new Lock[](length);
for (uint256 i = 0; i < length; i++) {
userLocks[i] = getLockById(_userLockIds[user].at(i));
}
return userLocks;
}
/**
* @dev Returns a specific lock owned by a user at the given index.
* @param user The address that owns the locks
* @param index The index of the lock in the user's lock array
* @return The Lock struct at the specified index
*/
function lockForUserAtIndex(
address user,
uint256 index
) external view returns (Lock memory) {
if (lockCountForUser(user) <= index) revert InvalidIndex();
return getLockById(_userLockIds[user].at(index));
}
/**
* @dev Returns the total number of locks owned by a specific user.
* @param user The address to count locks for
* @return The number of locks owned by the user
*/
function totalLockCountForUser(
address user
) external view returns (uint256) {
return lockCountForUser(user);
}
/**
* @dev Returns the total number of locks for a specific token.
* @param token The token address to count locks for
* @return The number of locks for the token
*/
function totalLockCountForToken(
address token
) external view returns (uint256) {
return _tokenToLockIds[token].length();
}
// ====================================================== //
// ================== PUBLIC FUNCTIONS ================== //
// ====================================================== //
/**
* @dev Returns the lock data for a specific lock ID.
* @param lockId The ID of the lock to retrieve
* @return The Lock struct containing all lock information
*/
function getLockById(
uint256 lockId
) public view validLock(lockId) returns (Lock memory) {
return _locks[lockId];
}
/**
* @dev Returns the number of locks owned by a specific user.
* @param user The address to count locks for
* @return The number of locks owned by the user
*/
function lockCountForUser(address user) public view returns (uint256) {
return _userLockIds[user].length();
}
/**
* @dev Returns locks for a specific token within a given range.
* @param token The token address to get locks for
* @param start The starting index (inclusive)
* @param end The ending index (inclusive, will be capped to array length)
* @return Array of Lock structs for the token within the range
*/
function getLocksForToken(
address token,
uint256 start,
uint256 end
) public view returns (Lock[] memory) {
if (end >= _tokenToLockIds[token].length()) {
end = _tokenToLockIds[token].length() - 1;
}
uint256 length = end - start + 1;
Lock[] memory locks = new Lock[](length);
uint256 currentIndex = 0;
for (uint256 i = start; i <= end; i++) {
locks[currentIndex] = getLockById(_tokenToLockIds[token].at(i));
currentIndex++;
}
return locks;
}
// ======================================================== //
// ================== INTERNAL FUNCTIONS ================== //
// ======================================================== //
/**
* @dev Internal function to apply the pending fee update.
*/
function _applyFee() internal {
if (feeUpdateTime == 0 || block.timestamp < feeUpdateTime) return;
uint256 newFee = pendingFee;
fee = newFee;
pendingFee = 0;
feeUpdateTime = 0;
emit FeeUpdated(newFee);
}
/**
* @dev Internal function to create multiple vesting locks with the same parameters.
* @param owners Array of lock owners
* @param amounts Array of lock amounts
* @param token The token to lock
* @param vestingSettings Array containing [tgeDate, tgeBps, cycle, cycleBps]
* @param description Description for all locks
* @return Array of created lock IDs
*/
function _multipleVestingLock(
address[] calldata owners,
uint256[] calldata amounts,
address token,
uint256[4] memory vestingSettings, // avoid stack too deep
string memory description
) internal returns (uint256[] memory) {
if (token == address(0)) revert InvalidToken();
uint256 sumAmount = _sumAmount(amounts);
uint256 count = owners.length;
uint256[] memory ids = new uint256[](count);
for (uint256 i = 0; i < count; i++) {
ids[i] = _createLock(
owners[i],
token,
amounts[i],
vestingSettings[0], // TGE date
vestingSettings[1], // TGE bps
vestingSettings[2], // cycle
vestingSettings[3], // cycle bps
description
);
emit LockAdded(
ids[i],
token,
owners[i],
amounts[i],
vestingSettings[0] // TGE date
);
}
_safeTransferFromEnsureExactAmount(
token,
msg.sender,
address(this),
sumAmount
);
return ids;
}
/**
* @dev Internal function to create a lock with the specified parameters.
* @param owner The owner of the lock
* @param token The token to lock
* @param amount The amount to lock
* @param tgeDate The TGE/unlock date
* @param tgeBps The TGE basis points (0 for normal locks)
* @param cycle The vesting cycle (0 for normal locks)
* @param cycleBps The cycle basis points (0 for normal locks)
* @param description The lock description
* @return The ID of the created lock
*/
function _createLock(
address owner,
address token,
uint256 amount,
uint256 tgeDate,
uint256 tgeBps,
uint256 cycle,
uint256 cycleBps,
string memory description
) internal returns (uint256) {
return
_lockToken(
owner,
token,
amount,
tgeDate,
tgeBps,
cycle,
cycleBps,
description
);
}
/**
* @dev Internal function to handle unlocking of simple time-locked tokens.
* @param userLock The lock storage reference to unlock
*/
function _normalUnlock(Lock storage userLock) internal {
if (block.timestamp < userLock.tgeDate) revert NotTimeToUnlock();
if (userLock.unlockedAmount != 0) revert NothingToUnlock();
CumulativeLockInfo storage tokenInfo = cumulativeLockInfo[
userLock.token
];
_userLockIds[msg.sender].remove(userLock.id);
uint256 unlockAmount = userLock.amount;
if (tokenInfo.amount <= unlockAmount) {
tokenInfo.amount = 0;
} else {
tokenInfo.amount = tokenInfo.amount - unlockAmount;
}
if (tokenInfo.amount == 0) _lockedTokens.remove(userLock.token);
userLock.unlockedAmount = unlockAmount;
_tokenToLockIds[userLock.token].remove(userLock.id);
IERC20(userLock.token).safeTransfer(msg.sender, unlockAmount);
emit LockRemoved(
userLock.id,
userLock.token,
msg.sender,
unlockAmount,
block.timestamp
);
}
/**
* @dev Internal function to handle unlocking of vesting tokens.
* @param userLock The lock storage reference to unlock from
*/
function _vestingUnlock(Lock storage userLock) internal {
uint256 withdrawable = _withdrawableTokens(userLock);
uint256 newTotalUnlockAmount = userLock.unlockedAmount + withdrawable;
if (withdrawable == 0 || newTotalUnlockAmount > userLock.amount) {
revert NothingToUnlock();
}
CumulativeLockInfo storage tokenInfo = cumulativeLockInfo[
userLock.token
];
if (newTotalUnlockAmount == userLock.amount) {
_userLockIds[msg.sender].remove(userLock.id);
_tokenToLockIds[userLock.token].remove(userLock.id);
emit LockRemoved(
userLock.id,
userLock.token,
msg.sender,
newTotalUnlockAmount,
block.timestamp
);
}
if (tokenInfo.amount <= withdrawable) {
tokenInfo.amount = 0;
} else {
tokenInfo.amount = tokenInfo.amount - withdrawable;
}
if (tokenInfo.amount == 0) _lockedTokens.remove(userLock.token);
userLock.unlockedAmount = newTotalUnlockAmount;
IERC20(userLock.token).safeTransfer(userLock.owner, withdrawable);
emit LockVested(
userLock.id,
userLock.token,
msg.sender,
withdrawable,
userLock.amount - userLock.unlockedAmount,
block.timestamp
);
}
/**
* @dev Internal function to safely transfer tokens and ensure exact amount is received.
* This handles tokens with transfer fees by checking balances before and after.
* @param token The token to transfer
* @param sender The sender address
* @param recipient The recipient address
* @param amount The expected amount to be received
*/
function _safeTransferFromEnsureExactAmount(
address token,
address sender,
address recipient,
uint256 amount
) internal {
uint256 oldRecipientBalance = IERC20(token).balanceOf(recipient);
IERC20(token).safeTransferFrom(sender, recipient, amount);
uint256 newRecipientBalance = IERC20(token).balanceOf(recipient);
if (newRecipientBalance - oldRecipientBalance != amount) {
revert InsufficientTokenTransfer();
}
}
/**
* @dev Internal function to calculate withdrawable tokens for a vesting lock.
* @param userLock The lock to calculate withdrawable tokens for
* @return The amount of tokens that can currently be withdrawn
*/
function _withdrawableTokens(
Lock memory userLock
) internal view returns (uint256) {
if (userLock.amount == 0) return 0;
if (userLock.unlockedAmount >= userLock.amount) return 0;
if (block.timestamp < userLock.tgeDate) return 0;
if (userLock.cycle == 0) return 0;
uint256 tgeReleaseAmount = FullMath.mulDiv(
userLock.amount,
userLock.tgeBps,
10_000
);
uint256 cycleReleaseAmount = FullMath.mulDiv(
userLock.amount,
userLock.cycleBps,
10_000
);
uint256 currentTotal = 0;
if (block.timestamp >= userLock.tgeDate) {
currentTotal =
(((block.timestamp - userLock.tgeDate) / userLock.cycle) *
cycleReleaseAmount) +
tgeReleaseAmount; // Truncation is expected here
}
uint256 withdrawable = 0;
if (currentTotal > userLock.amount) {
withdrawable = userLock.amount - userLock.unlockedAmount;
} else {
withdrawable = currentTotal - userLock.unlockedAmount;
}
return withdrawable;
}
/**
* @dev Internal function to sum an array of amounts and validate none are zero.
* @param amounts Array of amounts to sum
* @return sum The total sum of all amounts
*/
function _sumAmount(
uint256[] calldata amounts
) internal pure returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < amounts.length; i++) {
if (amounts[i] == 0) {
revert AmountCannotBeZero();
}
sum += amounts[i];
}
return sum;
}
// ======================================================= //
// ================== PRIVATE FUNCTIONS ================== //
// ======================================================= //
/**
* @dev Private function to handle the locking of tokens and updating internal state.
* @param owner The owner of the lock
* @param token The token to lock
* @param amount The amount to lock
* @param tgeDate The TGE/unlock date
* @param tgeBps The TGE basis points
* @param cycle The vesting cycle
* @param cycleBps The cycle basis points
* @param description The lock description
* @return id The ID of the created lock
*/
function _lockToken(
address owner,
address token,
uint256 amount,
uint256 tgeDate,
uint256 tgeBps,
uint256 cycle,
uint256 cycleBps,
string memory description
) private returns (uint256 id) {
id = _registerLock(
owner,
token,
amount,
tgeDate,
tgeBps,
cycle,
cycleBps,
description
);
_userLockIds[owner].add(id);
_lockedTokens.add(token);
CumulativeLockInfo storage tokenInfo = cumulativeLockInfo[token];
if (tokenInfo.token == address(0)) {
tokenInfo.token = token;
}
tokenInfo.amount += amount;
_tokenToLockIds[token].add(id);
}
/**
* @dev Private function to register a new lock in the locks array.
* @param owner The owner of the lock
* @param token The token to lock
* @param amount The amount to lock
* @param tgeDate The TGE/unlock date
* @param tgeBps The TGE basis points
* @param cycle The vesting cycle
* @param cycleBps The cycle basis points
* @param description The lock description
* @return id The ID of the created lock
*/
function _registerLock(
address owner,
address token,
uint256 amount,
uint256 tgeDate,
uint256 tgeBps,
uint256 cycle,
uint256 cycleBps,
string memory description
) private returns (uint256 id) {
id = _locks.length;
Lock memory newLock = Lock({
id: id,
token: token,
owner: owner,
amount: amount,
lockDate: block.timestamp,
tgeDate: tgeDate,
tgeBps: tgeBps,
cycle: cycle,
cycleBps: cycleBps,
unlockedAmount: 0,
description: description
});
_locks.push(newLock);
}
}
"
},
"lib/openzeppelin-contracts/contracts/utils/Address.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
} else {
revert Errors.FailedCall();
}
}
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
"
},
"lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
"
},
"lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
"
},
"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, 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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
"
},
"lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol": {
"content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
* - Set can be cleared (all elements removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* The following types are supported:
*
* - `bytes32` (`Bytes32Set`) since v3.3.0
* - `address` (`AddressSet`) since v3.3.0
* - `uint256` (`UintSet`) since v3.3.0
* - `string` (`StringSet`) since v5.4.0
* - `bytes` (`BytesSet`) since v5.4.0
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
*
Submitted on: 2025-10-17 20:37:10
Comments
Log in to comment.
No comments yet.