// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)pragmasolidity ^0.8.20;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/errorAddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/errorAddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/errorFailedInnerCall();
/**
* @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].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
if (address(this).balance< amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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
* {FailedInnerCall} 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.
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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`.
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
if (address(this).balance< value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytesmemory 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.
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
(bool success, bytesmemory 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 {FailedInnerCall}) in case of an
* unsuccessful call.
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata
) internalviewreturns (bytesmemory) {
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 contractif (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 {FailedInnerCall} error.
*/functionverifyCallResult(bool success, bytesmemory returndata) internalpurereturns (bytesmemory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/function_revert(bytesmemory returndata) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
Contract Source Code
File 2 of 28: Base64.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/Base64.sol)pragmasolidity ^0.8.20;/**
* @dev Provides a set of functions to operate with Base64 strings.
*/libraryBase64{
/**
* @dev Base64 Encoding/Decoding Table
*/stringinternalconstant _TABLE ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/**
* @dev Converts a `bytes` to its Bytes64 `string` representation.
*/functionencode(bytesmemory data) internalpurereturns (stringmemory) {
/**
* Inspired by Brecht Devos (Brechtpd) implementation - MIT licence
* https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol
*/if (data.length==0) return"";
// Loads the table into memorystringmemory table = _TABLE;
// Encoding takes 3 bytes chunks of binary data from `bytes` data parameter// and split into 4 numbers of 6 bits.// The final Base64 length should be `bytes` data length multiplied by 4/3 rounded up// - `data.length + 2` -> Round up// - `/ 3` -> Number of 3-bytes chunks// - `4 *` -> 4 characters for each chunkstringmemory result =newstring(4* ((data.length+2) /3));
/// @solidity memory-safe-assemblyassembly {
// Prepare the lookup table (skip the first "length" byte)let tablePtr :=add(table, 1)
// Prepare result pointer, jump over lengthlet resultPtr :=add(result, 32)
// Run over the input, 3 bytes at a timefor {
let dataPtr := data
let endPtr :=add(data, mload(data))
} lt(dataPtr, endPtr) {
} {
// Advance 3 bytes
dataPtr :=add(dataPtr, 3)
let input :=mload(dataPtr)
// To write each character, shift the 3 bytes (18 bits) chunk// 4 times in blocks of 6 bits for each character (18, 12, 6, 0)// and apply logical AND with 0x3F which is the number of// the previous character in the ASCII table prior to the Base64 Table// The result is then added to the table to get the character to write,// and finally write it in the result pointer but with a left shift// of 256 (1 byte) - 8 (1 ASCII char) = 248 bitsmstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr :=add(resultPtr, 1) // Advancemstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr :=add(resultPtr, 1) // Advancemstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))
resultPtr :=add(resultPtr, 1) // Advancemstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))
resultPtr :=add(resultPtr, 1) // Advance
}
// When data `bytes` is not exactly 3 bytes long// it is padded with `=` characters at the endswitchmod(mload(data), 3)
case1 {
mstore8(sub(resultPtr, 1), 0x3d)
mstore8(sub(resultPtr, 2), 0x3d)
}
case2 {
mstore8(sub(resultPtr, 1), 0x3d)
}
}
return result;
}
}
Contract Source Code
File 3 of 28: Configuration.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;import { IERC20 } from"@openzeppelin/contracts/interfaces/IERC20.sol";
import { IVestMembership } from"src/IVestMembership.sol";
import { IVestMembershipDescriptor } from"src/VestMembershipDescriptor.sol";
/// @notice Namespace for the structs related with the presale configuration.libraryPresale{
structFees {
uint16 tokenANumerator;
uint16 tokenADenominator;
uint16 tokenBNumerator;
uint16 tokenBDenominator;
}
structConfiguration {
Fees fees;
IERC20 tokenA;
IERC20 tokenB;
address manager;
address beneficiary;
uint256 tgeTimestamp;
uint256 listingTimestamp;
uint256 claimbackPeriod;
}
}
/// @notice Namespace for the structs related with the membership configuration.libraryMembership{
structFees {
uint16 numerator;
uint16 denominator;
}
structConfiguration {
Fees fees;
IVestMembership.Metadata metadata;
IVestMembershipDescriptor descriptor;
}
}
Contract Source Code
File 4 of 28: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)pragmasolidity ^0.8.20;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
function_contextSuffixLength() internalviewvirtualreturns (uint256) {
return0;
}
}
Contract Source Code
File 5 of 28: ERC20Helper.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;import { IERC20 } from"@openzeppelin/contracts/interfaces/IERC20.sol";
import { SafeERC20 } from"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Metadata } from"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @title ERC20Helper/// @notice Contains helper methods for interacting with ERC20 tokens.libraryERC20Helper{
/// @notice Transfers tokens from the calling contract to a recipient./// @param token The contract address of the token which will be transferred./// @param to The recipient of the transfer./// @param value The value of the transfer.functiontransfer(IERC20 token, address to, uint256 value) internal{
SafeERC20.safeTransfer(token, to, value);
}
/**
* @notice Transfers tokens from sender to a recipient and returns transferred amount.
* @param token The contract address of the token which will be transferred.
* @param sender The sender of the transfer.
* @param to The recipient of the transfer.
* @param value The value of the transfer.
*
* @dev Transferring tokens in some protocol functions cannot rely on given `amount`
* because in the case of a token that collects tax or handles the `transfer` in a
* custom way. In that case the value may not reflect the actual transferred value.
*
* Solution:
* - before the transfer: save the current balance
* - after the transfer: subtract this value from the new balance
*/functiontransferFrom(IERC20 token, address sender, address to, uint256 value) internalreturns (uint256) {
uint256 balance = token.balanceOf(to);
SafeERC20.safeTransferFrom(token, sender, to, value);
return token.balanceOf(to) - balance;
}
/// @notice Returns the decimals places of the token./// @param token The contract address of the token.functiondecimals(IERC20 token) internalviewreturns (uint256) {
return IERC20Metadata(address(token)).decimals();
}
}
Contract Source Code
File 6 of 28: EnumerableSet.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol)// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.pragmasolidity ^0.8.20;/**
* @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.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [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.
* ====
*/libraryEnumerableSet{
// 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.structSet {
// Storage of set valuesbytes32[] _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) privatereturns (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;
returntrue;
} else {
returnfalse;
}
}
/**
* @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) privatereturns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slotuint256 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 slotdelete set._positions[value];
returntrue;
} else {
returnfalse;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/function_contains(Set storage set, bytes32 value) privateviewreturns (bool) {
return set._positions[value] !=0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/function_length(Set storage set) privateviewreturns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/function_at(Set storage set, uint256 index) privateviewreturns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/function_values(Set storage set) privateviewreturns (bytes32[] memory) {
return set._values;
}
// Bytes32SetstructBytes32Set {
Set _inner;
}
/**
* @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.
*/functionadd(Bytes32Set storage set, bytes32 value) internalreturns (bool) {
return _add(set._inner, value);
}
/**
* @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.
*/functionremove(Bytes32Set storage set, bytes32 value) internalreturns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(Bytes32Set storage set, bytes32 value) internalviewreturns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(Bytes32Set storage set) internalviewreturns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/functionat(Bytes32Set storage set, uint256 index) internalviewreturns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionvalues(Bytes32Set storage set) internalviewreturns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
// AddressSetstructAddressSet {
Set _inner;
}
/**
* @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.
*/functionadd(AddressSet storage set, address value) internalreturns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @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.
*/functionremove(AddressSet storage set, address value) internalreturns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(AddressSet storage set, address value) internalviewreturns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(AddressSet storage set) internalviewreturns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/functionat(AddressSet storage set, uint256 index) internalviewreturns (address) {
returnaddress(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionvalues(AddressSet storage set) internalviewreturns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
// UintSetstructUintSet {
Set _inner;
}
/**
* @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.
*/functionadd(UintSet storage set, uint256 value) internalreturns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @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.
*/functionremove(UintSet storage set, uint256 value) internalreturns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(UintSet storage set, uint256 value) internalviewreturns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(UintSet storage set) internalviewreturns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/functionat(UintSet storage set, uint256 index) internalviewreturns (uint256) {
returnuint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionvalues(UintSet storage set) internalviewreturns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
}
Contract Source Code
File 7 of 28: Errors.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;libraryErrors{
/// @notice Given value is out of safe bounds.errorUnacceptableValue();
/// @notice Given reference is `address(0)`.errorUnacceptableReference();
/// @notice The caller account is not authorized to perform an operation./// @param account Address of the account.errorUnauthorized(address account);
/// @notice The caller account is not authorized to perform an operation./// @param account Address of the account.errorAccountMismatch(address account);
/// @notice Denominators cannot equal zero because division by zero is not allowed.errorDenominatorZero();
}
Contract Source Code
File 8 of 28: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)pragmasolidity ^0.8.20;/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/interfaceIERC165{
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 9 of 28: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.20;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (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.
*/functiontransfer(address to, uint256 value) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (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.
*/functionapprove(address spender, uint256 value) externalreturns (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.
*/functiontransferFrom(addressfrom, address to, uint256 value) externalreturns (bool);
}
Contract Source Code
File 10 of 28: IERC20Metadata.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)pragmasolidity ^0.8.20;import {IERC20} from"../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
Contract Source Code
File 11 of 28: IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^0.8.20;/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/interfaceIERC20Permit{
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/functionnonces(address owner) externalviewreturns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
Contract Source Code
File 12 of 28: IERC2981.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC2981.sol)pragmasolidity ^0.8.20;import {IERC165} from"../utils/introspection/IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*/interfaceIERC2981isIERC165{
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
*/functionroyaltyInfo(uint256 tokenId,
uint256 salePrice
) externalviewreturns (address receiver, uint256 royaltyAmount);
}
Contract Source Code
File 13 of 28: IERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721.sol)pragmasolidity ^0.8.20;import {IERC165} from"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/interfaceIERC721isIERC165{
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/eventApproval(addressindexed owner, addressindexed approved, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/eventApprovalForAll(addressindexed owner, addressindexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/functionbalanceOf(address owner) externalviewreturns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) externalviewreturns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom, address to, uint256 tokenId, bytescalldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/functionapprove(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/functionsetApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (bool);
}
Contract Source Code
File 14 of 28: IERC721Enumerable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)pragmasolidity ^0.8.20;import {IERC721} from"../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/interfaceIERC721EnumerableisIERC721{
/**
* @dev Returns the total amount of tokens stored by the contract.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/functiontokenOfOwnerByIndex(address owner, uint256 index) externalviewreturns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/functiontokenByIndex(uint256 index) externalviewreturns (uint256);
}
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;import { IERC721 } from"@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IERC2981 } from"@openzeppelin/contracts/interfaces/IERC2981.sol";
import { IERC721Enumerable } from"@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @title IVestMembership
* @author
* @notice
*/interfaceIVestMembershipisIERC2981, IERC721, IERC721Enumerable{
structUsage {
uint256 max;
uint256 current;
}
structMetadata {
address token;
string color;
string description;
}
structAttributes {
uint256 price;
uint256 allocation;
uint256 claimbackPeriod;
uint32 tgeNumerator;
uint32 tgeDenominator;
uint32 cliffDuration;
uint32 cliffNumerator;
uint32 cliffDenominator;
uint32 vestingPeriodCount;
uint32 vestingPeriodDuration;
uint8 tradeable;
}
/// @notice Creates new membership and transfers it to given owner./// @param owner_ Address of new address owner./// @param roundId Id of the assigned round./// @param maxUsage Max usage of the new membership./// @param attributes Attributes attached to the membership.functionmint(address owner_, uint256 roundId, uint256 currentUsage, uint256 maxUsage, Attributes memory attributes)
externalreturns (uint256);
/// @notice Extends the membership maximum usage./// @param publicId Id of the membership./// @param amount The amount by which the maximum usage is to be increased.functionextend(uint256 publicId, uint256 amount) externalreturns (uint256 newId);
/// @notice Reduces the membership maximum usage./// @param publicId Id of the membership./// @param amount The amount by which the maximum usage is to be reduced.functionreduce(uint256 publicId, uint256 amount) externalreturns (uint256 newId);
/// @notice Increases the membership current usage./// @param publicId Id of the membership./// @param amount The amount by which the current usage is to be increased.functionconsume(uint256 publicId, uint256 amount) externalreturns (uint256 newId);
/// @notice Returns the start timestamp.functiongetStartTimestamp() externalviewreturns (uint256);
/// @notice Returns the usage by given membership id./// @param publicId Id of the membership.functiongetUsage(uint256 publicId) externalviewreturns (Usage memory);
/// @notice Returns the round by given membership id./// @param publicId Id of the membership.functiongetRoundId(uint256 publicId) externalviewreturns (uint256);
/// @notice Returns the attributes by given membership id./// @param publicId Id of the membership.functiongetAttributes(uint256 publicId) externalviewreturns (Attributes memory);
/// @notice Returns releasable amount in the given timestamp./// @param publicId Id of the membership.functionunlocked(uint256 publicId) externalviewreturns (uint256);
functionunlocked(uint256 start, uint256 allocation, Attributes memory attributes)
externalviewreturns (uint256);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)pragmasolidity ^0.8.20;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMath{
/**
* @dev Muldiv operation overflow.
*/errorMathOverflowedMulDiv();
enumRounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/functiontryAdd(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/functiontrySub(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/functiontryMul(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the// benefit is lost if 'b' is also tested.// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522if (a ==0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/functiontryDiv(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
if (b ==0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/functiontryMod(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
if (b ==0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/functionmax(uint256 a, uint256 b) internalpurereturns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/functionaverage(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b) / 2 can overflow.return (a & b) + (a ^ b) /2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/functionceilDiv(uint256 a, uint256 b) internalpurereturns (uint256) {
if (b ==0) {
// Guarantee the same behavior as in a regular Solidity division.return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.return a ==0 ? 0 : (a -1) / b +1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/functionmulDiv(uint256 x, uint256 y, uint256 denominator) internalpurereturns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256// variables such that product = prod1 * 2^256 + prod0.uint256 prod0 = x * y; // Least significant 256 bits of the productuint256 prod1; // Most significant 256 bits of the productassembly {
let mm :=mulmod(x, y, not(0))
prod1 :=sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.if (prod1 ==0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.// The surrounding unchecked block does not change this fact.// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////// 512 by 256 division.///////////////////////////////////////////////// Make division exact by subtracting the remainder from [prod1 prod0].uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder :=mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 :=sub(prod1, gt(remainder, prod0))
prod0 :=sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.uint256 twos = denominator & (0- denominator);
assembly {
// Divide denominator by twos.
denominator :=div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 :=div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos :=add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for// four bits. That is, denominator * inv = 1 mod 2^4.uint256 inverse = (3* denominator) ^2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also// works in modular arithmetic, doubling the correct bits in each step.
inverse *=2- denominator * inverse; // inverse mod 2^8
inverse *=2- denominator * inverse; // inverse mod 2^16
inverse *=2- denominator * inverse; // inverse mod 2^32
inverse *=2- denominator * inverse; // inverse mod 2^64
inverse *=2- denominator * inverse; // inverse mod 2^128
inverse *=2- denominator * inverse; // inverse mod 2^256// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/functionmulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internalpurereturns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) &&mulmod(x, y, denominator) >0) {
result +=1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/functionsqrt(uint256 a) internalpurereturns (uint256) {
if (a ==0) {
return0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.//// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.//// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`//// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.uint256 result =1<< (log2(a) >>1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision// into the expected uint128 result.unchecked {
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/functionsqrt(uint256 a, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/functionlog2(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=128;
}
if (value >>64>0) {
value >>=64;
result +=64;
}
if (value >>32>0) {
value >>=32;
result +=32;
}
if (value >>16>0) {
value >>=16;
result +=16;
}
if (value >>8>0) {
value >>=8;
result +=8;
}
if (value >>4>0) {
value >>=4;
result +=4;
}
if (value >>2>0) {
value >>=2;
result +=2;
}
if (value >>1>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog2(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result =log2(value);
return result + (unsignedRoundsUp(rounding) &&1<< result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/functionlog10(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >=10**64) {
value /=10**64;
result +=64;
}
if (value >=10**32) {
value /=10**32;
result +=32;
}
if (value >=10**16) {
value /=10**16;
result +=16;
}
if (value >=10**8) {
value /=10**8;
result +=8;
}
if (value >=10**4) {
value /=10**4;
result +=4;
}
if (value >=10**2) {
value /=10**2;
result +=2;
}
if (value >=10**1) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog10(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) &&10** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/functionlog256(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=16;
}
if (value >>64>0) {
value >>=64;
result +=8;
}
if (value >>32>0) {
value >>=32;
result +=4;
}
if (value >>16>0) {
value >>=16;
result +=2;
}
if (value >>8>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog256(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) &&1<< (result <<3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/functionunsignedRoundsUp(Rounding rounding) internalpurereturns (bool) {
returnuint8(rounding) %2==1;
}
}
Contract Source Code
File 19 of 28: MathHelper.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;/**
* @title MathHelper
* @notice A utility library for performing mathematical operations on values.
*/libraryMathHelper{
/// @notice Returns a smaller number./// @param a Number to compare./// @param b Number to compare.functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a > b ? b : a;
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)pragmasolidity ^0.8.20;/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*/libraryMerkleProof{
/**
*@dev The multiproof provided is not valid.
*/errorMerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/functionverify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internalpurereturns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*/functionverifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internalpurereturns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*/functionprocessProof(bytes32[] memory proof, bytes32 leaf) internalpurereturns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i =0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*/functionprocessProofCalldata(bytes32[] calldata proof, bytes32 leaf) internalpurereturns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i =0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/functionmultiProofVerify(bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internalpurereturns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/functionmultiProofVerifyCalldata(bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internalpurereturns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*/functionprocessMultiProof(bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internalpurereturns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of// the Merkle tree.uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.if (leavesLen + proofLen != totalHashes +1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".bytes32[] memory hashes =newbytes32[](totalHashes);
uint256 leafPos =0;
uint256 hashPos =0;
uint256 proofPos =0;
// At each step, we compute the next hash using two values:// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we// get the next hash.// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the// `proof` array.for (uint256 i =0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes >0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes -1];
}
} elseif (leavesLen >0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/functionprocessMultiProofCalldata(bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internalpurereturns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of// the Merkle tree.uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.if (leavesLen + proofLen != totalHashes +1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".bytes32[] memory hashes =newbytes32[](totalHashes);
uint256 leafPos =0;
uint256 hashPos =0;
uint256 proofPos =0;
// At each step, we compute the next hash using two values:// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we// get the next hash.// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the// `proof` array.for (uint256 i =0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes >0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes -1];
}
} elseif (leavesLen >0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Sorts the pair (a, b) and hashes the result.
*/function_hashPair(bytes32 a, bytes32 b) privatepurereturns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/function_efficientHash(bytes32 a, bytes32 b) privatepurereturns (bytes32 value) {
/// @solidity memory-safe-assemblyassembly {
mstore(0x00, a)
mstore(0x20, b)
value :=keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.20;import {IERC20} from"../IERC20.sol";
import {IERC20Permit} from"../extensions/IERC20Permit.sol";
import {Address} from"../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/librarySafeERC20{
usingAddressforaddress;
/**
* @dev An operation with an ERC20 token failed.
*/errorSafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/errorSafeERC20FailedDecreaseAllowance(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.
*/functionsafeTransfer(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.
*/functionsafeTransferFrom(IERC20 token, addressfrom, address to, uint256 value) internal{
_callOptionalReturn(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.
*/functionsafeIncreaseAllowance(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.
*/functionsafeDecreaseAllowance(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.
*/functionforceApprove(IERC20 token, address spender, uint256 value) internal{
bytesmemory approvalCall =abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/function_callOptionalReturn(IERC20 token, bytesmemory 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.bytesmemory returndata =address(token).functionCall(data);
if (returndata.length!=0&&!abi.decode(returndata, (bool))) {
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 silents catches all reverts and returns a bool instead.
*/function_callOptionalReturnBool(IERC20 token, bytesmemory data) privatereturns (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, bytesmemory returndata) =address(token).call(data);
return success && (returndata.length==0||abi.decode(returndata, (bool))) &&address(token).code.length>0;
}
}
Contract Source Code
File 24 of 28: SignedMath.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)pragmasolidity ^0.8.20;/**
* @dev Standard signed math utilities missing in the Solidity language.
*/librarySignedMath{
/**
* @dev Returns the largest of two signed numbers.
*/functionmax(int256 a, int256 b) internalpurereturns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/functionmin(int256 a, int256 b) internalpurereturns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/functionaverage(int256 a, int256 b) internalpurereturns (int256) {
// Formula from the book "Hacker's Delight"int256 x = (a & b) + ((a ^ b) >>1);
return x + (int256(uint256(x) >>255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/functionabs(int256 n) internalpurereturns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`returnuint256(n >=0 ? n : -n);
}
}
}
Contract Source Code
File 25 of 28: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)pragmasolidity ^0.8.20;import {Math} from"./math/Math.sol";
import {SignedMath} from"./math/SignedMath.sol";
/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant HEX_DIGITS ="0123456789abcdef";
uint8privateconstant ADDRESS_LENGTH =20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/errorStringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
uint256 length = Math.log10(value) +1;
stringmemory buffer =newstring(length);
uint256 ptr;
/// @solidity memory-safe-assemblyassembly {
ptr :=add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assemblyassembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /=10;
if (value ==0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/functiontoStringSigned(int256 value) internalpurereturns (stringmemory) {
returnstring.concat(value <0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
return toHexString(value, Math.log256(value) +1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
uint256 localValue = value;
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = HEX_DIGITS[localValue &0xf];
localValue >>=4;
}
if (localValue !=0) {
revert StringsInsufficientHexLength(value, length);
}
returnstring(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/functiontoHexString(address addr) internalpurereturns (stringmemory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/functionequal(stringmemory a, stringmemory b) internalpurereturns (bool) {
returnbytes(a).length==bytes(b).length&&keccak256(bytes(a)) ==keccak256(bytes(b));
}
}
Contract Source Code
File 26 of 28: VestMembershipDescriptor.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;import { Base64 } from"@openzeppelin/contracts/utils/Base64.sol";
import { Strings } from"@openzeppelin/contracts/utils/Strings.sol";
import { IERC20Metadata } from"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IVestMembership } from"src/IVestMembership.sol";
import { MembershipSVG } from"src/libraries/MembershipSVG.sol";
interfaceIVestMembershipDescriptor{
/// @notice Generates the name of the membership./// @param metadata Metadata of the membership.functionname(IVestMembership.Metadata memory metadata) externalviewreturns (stringmemory);
/// @notice Generates the symbol of the membership./// @param metadata Metadata of the membership.functionsymbol(IVestMembership.Metadata memory metadata) externalviewreturns (stringmemory);
/// @notice Generates encoded JSON metadata./// @param start Date of the start./// @param usage Usage of the membership./// @param metadata Metadata of the membership./// @param attributes Attributes of the membership./// @return encoded JSON metadata in base64.functiontokenURI(uint256 start,
IVestMembership.Usage memory usage,
IVestMembership.Metadata memory metadata,
IVestMembership.Attributes memory attributes
) externalviewreturns (stringmemory);
}
contractVestMembershipDescriptorisIVestMembershipDescriptor{
usingStringsforaddress;
usingStringsforuint32;
usingStringsforuint256;
/// @inheritdoc IVestMembershipDescriptorfunctionname(IVestMembership.Metadata memory metadata) publicviewreturns (stringmemory) {
stringmemory name_ = IERC20Metadata(address(metadata.token)).name();
returnstring.concat(name_, " Vesting");
}
/// @inheritdoc IVestMembershipDescriptorfunctionsymbol(IVestMembership.Metadata memory metadata) publicviewreturns (stringmemory) {
stringmemory symbol_ = IERC20Metadata(address(metadata.token)).symbol();
returnstring.concat("v", symbol_);
}
/// @inheritdoc IVestMembershipDescriptorfunctiontokenURI(uint256 start,
IVestMembership.Usage memory usage,
IVestMembership.Metadata memory metadata,
IVestMembership.Attributes memory attributes
) publicviewvirtualreturns (stringmemory) {
stringmemory json =string.concat(
'{"attributes":',
_traits(start, usage, metadata, attributes),
',"description":"',
metadata.description,
'","name":"',
_title(metadata),
'","image":"',
_image(usage, metadata),
'"}'
);
returnstring.concat("data:application/json;base64,", Base64.encode(bytes(json)));
}
/// @notice Generates title for given membership./// @param metadata Metadata of the membership.function_title(IVestMembership.Metadata memory metadata) internalviewreturns (stringmemory) {
stringmemory symbol_ = IERC20Metadata(address(metadata.token)).symbol();
returnstring.concat("Vesting of ", symbol_);
}
/// @notice Generates encoded image./// @param usage Usage of the membership./// @param metadata Metadata of the membership./// @return encoded image.function_image(IVestMembership.Usage memory usage, IVestMembership.Metadata memory metadata)
internalviewreturns (stringmemory)
{
uint256 denominator =10** IERC20Metadata(address(metadata.token)).decimals();
stringmemory svg = MembershipSVG.generate(
MembershipSVG.Params({
color: metadata.color,
title: name(metadata),
max: usage.max/ denominator,
current: usage.current / denominator
})
);
returnstring.concat("data:image/svg+xml;base64,", Base64.encode(bytes(svg)));
}
/// @notice Generates traits metadata./// @param start Date of the start./// @param usage Usage of the membership./// @param metadata Metadata of the membership./// @return encoded image.function_traits(uint256 start,
IVestMembership.Usage memory usage,
IVestMembership.Metadata memory metadata,
IVestMembership.Attributes memory attributes
) internalviewreturns (stringmemory) {
uint256 denominator =10** IERC20Metadata(address(metadata.token)).decimals();
stringmemory traits0 =string.concat(
'[{"trait_type":"Usage","display_type":"boost_percentage","value":',
(usage.max>0 ? usage.current *100/ usage.max : 0).toString(),
'},{"trait_type":"Vested tokens","display_type":"number","value":',
Strings.toString(usage.max/ denominator),
'},{"trait_type":"Claimed tokens","display_type":"number","value":',
Strings.toString(usage.current / denominator),
'},{"trait_type":"TGE","display_type":"boost_percentage","value":',
(attributes.tgeDenominator >0 ? attributes.tgeNumerator *100/ attributes.tgeDenominator : 0).toString(),
'},{"trait_type":"Vesting start","display_type":"date","value":',
start.toString(),
'},{"trait_type":"Vesting end","display_type":"date","value":',
(start + attributes.cliffDuration + (attributes.vestingPeriodCount * attributes.vestingPeriodDuration))
.toString()
);
/// @dev split to avoid the stack too deep errorstringmemory traits1 =string.concat(
'},{"trait_type":"Cliff duration","value":"',
_getCliffDurationText(attributes.cliffDuration),
'"},{"trait_type":"Cliff unlock","display_type":"boost_percentage","value":',
(attributes.cliffDenominator >0 ? attributes.cliffNumerator *100/ attributes.cliffDenominator : 0)
.toString(),
'},{"trait_type":"Unlock frequency","value":"',
_getUnlockFrequencyText(attributes.vestingPeriodDuration),
'"},{"trait_type":"Vested token name","value":"',
IERC20Metadata(address(metadata.token)).name(),
'"},{"trait_type":"Vested token symbol","value":"',
IERC20Metadata(address(metadata.token)).symbol(),
'"},{"trait_type":"Vested token address","value":"',
Strings.toHexString(uint160(metadata.token), 20),
'"}]'
);
returnstring.concat(traits0, traits1);
}
/// @notice Convert the cliff duration to human-readable value./// @param value Value of the cliff duration./// @return Human-readable value.function_getCliffDurationText(uint256 value) internalpurevirtualreturns (stringmemory) {
if (value ==0) return"no cliff";
(uint256 period, stringmemory label) = _humanize(value);
returnstring.concat(period.toString(), " ", label);
}
/// @notice Convert the unlock frequency to human-readable value./// @param value Value of the unlock frequency./// @return Human-readable value.function_getUnlockFrequencyText(uint256 value) internalpurevirtualreturns (stringmemory) {
if (value ==0) return"none";
(uint256 period, stringmemory label) = _humanize(value);
if (period ==1) returnstring.concat("every ", label);
returnstring.concat("every ", period.toString(), " ", label);
}
/// @notice Convert the period to a human-readable value./// @param value Period to humanize./// @return Period in as text value.function_humanize(uint256 value) internalpurevirtualreturns (uint256, stringmemory) {
if (value <1hours) return _pluralize(value /1minutes, "minute", "minutes");
if (value <1days) return _pluralize(value /1hours, "hour", "hours");
return _pluralize(value /1days, "day", "days");
}
/// @notice Returns a label based on the given value./// @param value The value on which the selection of the label is based./// @param singular Singular label./// @param plural Plural label./// @return Generated label.function_pluralize(uint256 value, stringmemory singular, stringmemory plural)
internalpurevirtualreturns (uint256, stringmemory)
{
return (value, value ==1 ? singular : plural);
}
}
Contract Source Code
File 27 of 28: VestPresale.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;import { Context } from"@openzeppelin/contracts/utils/Context.sol";
import { IERC20 } from"@openzeppelin/contracts/interfaces/IERC20.sol";
import { EnumerableSet } from"@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { MerkleProof } from"@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import { Withdrawable } from"delegatecall/Withdrawable.sol";
import { Errors } from"src/libraries/Errors.sol";
import { MathHelper } from"src/libraries/MathHelper.sol";
import { ERC20Helper } from"src/libraries/ERC20Helper.sol";
import { Round, RoundState } from"src/types/Round.sol";
import { Presale } from"src/types/Configuration.sol";
import { IVestMembership } from"src/IVestMembership.sol";
import { IVestPresaleScheduler } from"src/IVestPresaleScheduler.sol";
import { IVestFeeCollectorProvider } from"src/IVestFeeCollectorProvider.sol";
/**
* @title VestPresale
* @notice An implementation of smart contract to handle the process of presale and vesting.
*/contractVestPresaleisContext, Withdrawable, IVestPresaleScheduler{
usingEnumerableSetforEnumerableSet.UintSet;
uint256internalconstant ROUND_LOCK_PERIOD =1hours;
/// @notice ERC20 implementation of the token sold.
IERC20 publicimmutable tokenA;
/// @notice ERC20 implementation of the token collected.
IERC20 publicimmutable tokenB;
/// @notice An address of a external membership smart contract.
IVestMembership publicimmutable membership;
/// @notice An address of a external smart contract that provide the fee collector address.
IVestFeeCollectorProvider publicimmutable feeCollectorProvider;
/// @notice Address of the manager.addresspublic manager;
/// @notice Address of the beneficiary.addresspublic beneficiary;
/// @notice Amount of tokens available to distribution during the vesting.uint256public liquidityA;
/// @notice Amount of tokens collected during the sale.uint256public liquidityB;
/// @notice Amount of tokens collected during the sale that are available to withdraw.uint256public nonClaimableBackTokenB;
/// @notice Timestamp indicating when the tge should be available.uint256internal tgeTimestamp;
/// @notice Timestamp indicating starting point from which the claim back period begins.uint256internal listingTimestamp;
/// @notice How much time in seconds since `listingTimestamp` do Users have to claimback TokenAuint256publicimmutable claimbackPeriod;
/// @notice Indicates whether the account participated in the sale state of given round.mapping(uint256 roundId =>mapping(bytes32=>bool)) public roundParticipants;
/// @notice Incremental value for indexing rounds.uint256internal roundSerialId;
/// @notice Fees applicable to this presale
Presale.Fees internal fees;
/// @notice List of rounds ids.
EnumerableSet.UintSet internal roundsIds;
/// @notice Collection of the rounds.mapping(uint256 roundId => Round) internal rounds;
/// @notice Event emitted when the funds has been claimed./// @param vMembershipId Id of the membership./// @param amountA Amount of the claimed funds.eventClaimed(uint256indexed vMembershipId, uint256 amountA);
/// @notice Event emitted when the funds has been claimed back./// @param vMembershipId Id of the membership./// @param amountA Amount of the claimed back funds.eventClaimedBack(uint256indexed vMembershipId, uint256 amountA);
/// @notice Event emitted when the funds has been deposited./// @param amount Amount of the deposited funds.eventDepositedA(uint256 amount);
/// @notice Event emitted when the funds has been withdrawn./// @param amount Amount of the withdrawn funds.eventWithdrawnA(uint256 amount);
/// @notice Event emitted when the funds has been withdrawn./// @param amount Amount of the withdrawn funds.eventWithdrawnB(uint256 amount);
/// @notice Event emitted when the round has been updated.eventRoundUpdated(uint256indexed id);
/// @notice Event emitted when the manager has been updated.eventManagerUpdated(address current);
/// @notice Event emitted when the beneficiary has been updated.eventBeneficiaryUpdated(address current);
/// @notice Event emitted when the tge start timestamp has been updated./// @param timestamp The new timestamp.eventListingTimestampUpdated(uint256 timestamp);
/// @notice Event emitted when the tge listing difference timestamp has been updated./// @param value The new value.eventTgeTimestampUpdated(uint256 value);
//-------------------------------------------------------------------------// Errors/// @notice Cannot update the locked round./// @param id Id of the round.errorRoundIsLocked(uint256 id);
/// @notice The round with given id does not exist./// @param id Id of the round.errorRoundNotExists(uint256 id);
/// @notice Round is in a different state./// @param id The id of updated round./// @param current Current state of the round./// @param expected Expected state of the round.errorRoundStateMismatch(uint256 id, RoundState current, RoundState expected);
/// @notice Claim not allowed by given membership./// @param membershipId Id of the membership.errorClaimNotAllowed(uint256 membershipId);
/// @notice Claimback not allowed for given membership./// @param membershipId Id of the membership.errorClaimbackNotAllowed(uint256 membershipId);
/// @notice Cliffs that unblock tokens immediately are not allowederrorCliffWithImmediateUnlock();
/// @notice Vesting periods with duration 0 are not allowederrorVestingWithImmediateUnlock();
/// @notice Vesting with only one period is too short. Either use cliff or increase period count.errorCliffLikeVesting();
/// @notice The vesting is configured such that it would never unlock any tokens.errorVestingWithoutUnlocks();
/// @notice Cliff height is specified but no vesting periods follow. In that case, all tokens will be unlocked at cliff end so cliffNumerator should equal zero.errorCliffHeightWithoutSubsequentUnlocks();
/// @notice When vesting is configured such that it will never release 100% tokens or it will release more than 100% of tokens.errorVestingSize();
/// @notice This protocol does not support tokens with transfer feeserrorTokenWithTransferFees(address tokenAddress);
/// @notice `LiquidityA` is lower than needed.errorOutOfLiquidityA();
/// @notice Given `account` is already a participant in the round.errorAlreadyRoundParticipant(uint256 roundId, address account);
/// @notice Ensures that the account is eligible for withdrawal.modifierprotectedWithdrawal() override{
if (_msgSender() != manager) revert Errors.Unauthorized(_msgSender());
_;
}
/// @notice Ensure the sender is the manager./// @param account Address of the sender.modifieronlyManager(address account) {
if (account != manager) revert Errors.Unauthorized(account);
_;
}
/// @notice Ensure the sender is the beneficiary./// @param account Address of the sender.modifieronlyBeneficiary(address account) {
if (account != beneficiary) revert Errors.Unauthorized(account);
_;
}
/// @notice Ensure the sender is the owner of the membership./// @param membershipId Id of the membership.modifieronlyMember(uint256 membershipId) {
if (membership.ownerOf(membershipId) != _msgSender()) revert Errors.AccountMismatch(_msgSender());
_;
}
/// @notice Ensures that the selected round has given state./// @param roundId Id of the round./// @param expected Expected state of the round.modifieronlyRoundInState(uint256 roundId, RoundState expected) {
RoundState current = getRoundState(roundId);
if (current != expected) revert RoundStateMismatch(roundId, current, expected);
_;
}
/// @notice Contract state initialization.constructor(
IVestMembership membership_,
IVestFeeCollectorProvider feeCollectorProvider_,
Presale.Configuration memory configuration,
Round[] memory rounds_
) {
if (address(membership_) ==address(0)) revert Errors.UnacceptableReference();
if (address(feeCollectorProvider_) ==address(0)) revert Errors.UnacceptableReference();
if (address(configuration.tokenA) ==address(0)) revert Errors.UnacceptableReference();
if (address(configuration.tokenB) ==address(0)) revert Errors.UnacceptableReference();
if (configuration.manager ==address(0)) revert Errors.UnacceptableReference();
if (configuration.beneficiary ==address(0)) revert Errors.UnacceptableReference();
if (configuration.listingTimestamp !=0&& configuration.tgeTimestamp ==0) {
revert Errors.UnacceptableValue();
}
if (configuration.listingTimestamp !=0&& configuration.tgeTimestamp > configuration.listingTimestamp) {
revert Errors.UnacceptableValue();
}
// not emitting an event since fees can’t change after being set in a constructor
fees = configuration.fees;
tokenB = configuration.tokenB;
tokenA = configuration.tokenA;
manager = configuration.manager;
beneficiary = configuration.beneficiary;
membership = membership_;
feeCollectorProvider = feeCollectorProvider_;
tgeTimestamp = configuration.tgeTimestamp;
claimbackPeriod = configuration.claimbackPeriod;
listingTimestamp = configuration.listingTimestamp;
uint256 size = rounds_.length;
for (uint256 i =0; i < size; i++) {
_addRound(rounds_[i]);
}
}
//--------------------------------------------------------------------------// Domainfunctionclaim(uint256 membershipId) externalonlyMember(membershipId) returns (uint256) {
IVestMembership.Usage memory usage = membership.getUsage(membershipId);
// when is the first claimif (usage.current ==0) {
uint256 timestamp =block.timestamp;
// must be after tgeTimestampif (tgeTimestamp ==0|| timestamp < tgeTimestamp) revert ClaimNotAllowed(membershipId);
IVestMembership.Attributes memory attributes = membership.getAttributes(membershipId);
if (attributes.price >0) {
uint256 denominator =10** ERC20Helper.decimals(tokenA);
// overflow not possible because `nonClaimableBackTokenB` always less than tokenB total supply.unchecked {
nonClaimableBackTokenB += usage.max* attributes.price / denominator;
}
}
}
uint256 unlocked = membership.unlocked(tgeTimestamp, usage.max, membership.getAttributes(membershipId));
uint256 releasable = unlocked - usage.current;
if (releasable ==0) revert ClaimNotAllowed(membershipId);
uint256 newId = membership.consume(membershipId, releasable);
ERC20Helper.transfer(tokenA, _msgSender(), releasable);
emit Claimed(membershipId, releasable);
return newId;
}
/// @notice Transfers `tokenB` tokens and creates the membership./// @param roundId Id of the round./// @param amountA amount of token A to buy/// @param attributes The membership attributes./// @param proof Merkle tree proof.functionbuy(uint256 roundId,
uint256 amountA,
IVestMembership.Attributes calldata attributes,
bytes32[] calldata proof
) externalonlyRoundInState(roundId, RoundState.SALE) returns (uint256) {
if (amountA ==0) revert Errors.UnacceptableValue();
if (amountA > attributes.allocation) revert Errors.UnacceptableValue();
_requireValidAttributes(attributes);
_requireCallerCanParticipateInSale(roundId, attributes, proof);
uint256 boughtA = _buy(0, attributes.allocation, attributes.price, amountA);
return membership.mint(_msgSender(), roundId, 0, boughtA, attributes);
}
/// @notice Transfers `tokenB` tokens and updates usage of the given membership./// @param membershipId Id of the membership./// @param amountA Amount of tokens to extend the membership.functionextend(uint256 membershipId, uint256 amountA)
externalonlyRoundInState(membership.getRoundId(membershipId), RoundState.SALE)
onlyMember(membershipId)
returns (uint256)
{
IVestMembership.Usage memory usage = membership.getUsage(membershipId);
IVestMembership.Attributes memory attributes = membership.getAttributes(membershipId);
uint256 released = _buy(usage.max, attributes.allocation, attributes.price, amountA);
if (attributes.price >0&& usage.current >0) {
uint256 denominator =10** ERC20Helper.decimals(tokenA);
// overflow not possible because `nonClaimableBackTokenB` always less than tokenB total supply.unchecked {
nonClaimableBackTokenB += amountA * attributes.price / denominator;
}
}
return membership.extend(membershipId, released);
}
/**
* @notice Claimback `tokenB` tokens to the membership owner and adds `tokenA` tokens back to the `liquidityA`.
* @param membershipId Id of the membership.
* @param amountA Amount of `tokenA` tokens to claimback.
*
* Requirements:
* - the caller must have a membership
* - the membership `claimbackPeriod` attribute must be greater than zero
* - when the `listingTimestamp` is different from zero => the current timestamp
* must be earlier than the sum of `listingTimestamp` and `period`
*/functionclaimback(uint256 membershipId, uint256 amountA)
externalonlyMember(membershipId)
returns (uint256 newPublicId)
{
if (amountA ==0) revert ClaimbackNotAllowed(membershipId);
IVestMembership.Attributes memory attributes = membership.getAttributes(membershipId);
if (attributes.claimbackPeriod ==0) revert ClaimbackNotAllowed(membershipId);
/**
* The `period` cannot be greater than the `Presale.claimbackPeriod`, as this
* is related to the `withdrawTokenB` function. The `withdrawTokenB` method allows
* all `tokenB` funds to be withdrawn after the time for which the
* `Presale.claimbackPeriod` is used to calculate.
*/uint256 period = MathHelper.min(claimbackPeriod, attributes.claimbackPeriod);
if (listingTimestamp !=0&&block.timestamp>= listingTimestamp + period) {
revert ClaimbackNotAllowed(membershipId);
}
IVestMembership.Usage memory usage = membership.getUsage(membershipId);
if (usage.current >0) revert ClaimbackNotAllowed(membershipId);
uint256 claimableBackA = MathHelper.min(amountA, usage.max);
// Calculates the number of `tokenB` tokens to be claimed back to the membership owner.uint256 denominatorA =10** ERC20Helper.decimals(tokenA);
uint256 claimableBackB = claimableBackA * attributes.price / denominatorA;
if (claimableBackB ==0) revert ClaimbackNotAllowed(membershipId);
unchecked {
liquidityA += claimableBackA;
liquidityB -= claimableBackB;
}
newPublicId = membership.reduce(membershipId, claimableBackA);
ERC20Helper.transfer(tokenB, _msgSender(), claimableBackB);
emit ClaimedBack(membershipId, claimableBackA);
}
/// @notice Updates the manager address./// @param value Address of the new manager.functionupdateManager(address value) externalonlyManager(_msgSender()) {
if (value ==address(0)) revert Errors.UnacceptableReference();
manager = value;
emit ManagerUpdated(value);
}
/// @notice Updates the beneficiary address./// @param value Address of the new beneficiary.functionupdateBeneficiary(address value) externalonlyBeneficiary(_msgSender()) {
if (value ==address(0)) revert Errors.UnacceptableReference();
beneficiary = value;
emit BeneficiaryUpdated(value);
}
/// @notice Updates tge timestamp value./// @param timestamp new tge timestamp.functionupdateTgeTimestamp(uint256 timestamp) externalonlyBeneficiary(_msgSender()) {
// The value cannot be in the past.if (timestamp <block.timestamp) revert Errors.UnacceptableValue();
// Cannot set tge timestamp to be greater than listing timestamp.if (listingTimestamp !=0&& timestamp > listingTimestamp) revert Errors.UnacceptableValue();
tgeTimestamp = timestamp;
emit TgeTimestampUpdated(timestamp);
}
/// @notice Updates listing timestamp value./// @param timestamp new listing timestamp.functionupdateListingTimestamp(uint256 timestamp) externalonlyBeneficiary(_msgSender()) {
// The value cannot be in the past.if (timestamp <block.timestamp) revert Errors.UnacceptableValue();
// Cannot set listing timestamp to be less than tge timestamp.if (tgeTimestamp ==0|| timestamp < tgeTimestamp) revert Errors.UnacceptableValue();
listingTimestamp = timestamp;
emit ListingTimestampUpdated(timestamp);
}
/// @notice Deposits the `tokenA`./// @param amountA Amount of the tokens to deposit.functiondepositTokenA(uint256 amountA) external{
uint256 deposited = ERC20Helper.transferFrom(tokenA, _msgSender(), address(this), amountA);
if (deposited != amountA) revert TokenWithTransferFees(address(tokenA));
// overflow is not possible because transferred amount cannot be higher than token supply.unchecked {
liquidityA += deposited;
}
emit DepositedA(deposited);
}
/// @inheritdoc WithdrawablefunctionwithdrawToken(address to, IERC20 token, uint256 amount) publicoverrideprotectedWithdrawal{
if (address(token) ==address(tokenA) ||address(token) ==address(tokenB)) {
revert Errors.UnacceptableReference();
}
super.withdrawToken(to, token, amount);
}
/// @notice Beneficiary can withdraw `tokenA` at any time./// @param amount amount of `tokenA` to withdraw.functionwithdrawTokenA(uint256 amount) externalonlyBeneficiary(_msgSender()) {
if (amount > liquidityA) revert Errors.UnacceptableValue();
// underflow not possible because we checked before that `amount` < `liquidityA`unchecked {
liquidityA -= amount;
}
ERC20Helper.transfer(tokenA, beneficiary, amount);
emit WithdrawnA(amount);
}
/// @notice Withdraws the `tokenB` tokens to the beneficiary.functionwithdrawTokenB() external{
if (listingTimestamp ==0) revert Errors.UnacceptableValue();
uint256 withdrawable = nonClaimableBackTokenB;
// if claimback timestamp in past beneficiary can get all liquidity.if (block.timestamp> listingTimestamp + claimbackPeriod) {
withdrawable = liquidityB;
}
if (withdrawable ==0) revert Errors.UnacceptableValue();
nonClaimableBackTokenB =0;
unchecked {
liquidityB -= withdrawable;
}
uint256 fee;
Presale.Fees memory fees_ = fees;
if (fees_.tokenBNumerator !=0&& fees_.tokenBDenominator !=0) {
// over/underflow not possible here because fee always will be less than `withdrawable` such as percent of fee cannot be higher or equal than 100.unchecked {
fee = (withdrawable * fees_.tokenBNumerator) / fees_.tokenBDenominator;
}
if (fee >0) {
unchecked {
withdrawable -= fee;
}
ERC20Helper.transfer(tokenB, getFeeCollector(), fee);
}
}
ERC20Helper.transfer(tokenB, beneficiary, withdrawable);
emit WithdrawnB(withdrawable + fee);
}
//--------------------------------------------------------------------------// Rounds configuration/// @notice Adds new round./// @param round Configuration of the round.functionaddRound(Round memory round) externalonlyManager(_msgSender()) {
_addRound(round);
}
/// @notice Updates the round./// @param roundId Id of the round./// @param round Configuration of the round.functionupdateRound(uint256 roundId, Round memory round) externalonlyManager(_msgSender()) {
if (round.startTimestamp >= round.endTimestamp) revert Errors.UnacceptableValue();
if (block.timestamp>= rounds[roundId].startTimestamp - ROUND_LOCK_PERIOD) {
revert RoundIsLocked(roundId);
}
rounds[roundId] = round;
emit RoundUpdated(roundId);
}
/// @notice Removes the round./// @param roundId Id of the round.functionremoveRound(uint256 roundId) externalonlyManager(_msgSender()) {
if (!roundsIds.contains(roundId)) revert RoundNotExists(roundId);
if (block.timestamp>= rounds[roundId].startTimestamp - ROUND_LOCK_PERIOD) {
revert RoundIsLocked(roundId);
}
roundsIds.remove(roundId);
emit RoundUpdated(roundId);
}
/// @notice Updates the round whitelist configuration./// @param roundId Id of the round./// @param whitelistRoot Merkle tree root./// @param proofsUri The uri of the proofs.functionupdateWhitelist(uint256 roundId, bytes32 whitelistRoot, stringmemory proofsUri)
externalonlyManager(_msgSender())
{
if (!roundsIds.contains(roundId)) revert RoundNotExists(roundId);
rounds[roundId].proofsUri = proofsUri;
rounds[roundId].whitelistRoot = whitelistRoot;
emit RoundUpdated(roundId);
}
//--------------------------------------------------------------------------// Misc/// @notice Returns the fees configuration.functiongetFees() externalviewreturns (Presale.Fees memory) {
return fees;
}
/// @notice Returns the list of the rounds and their ids and states.functiongetRounds()
externalviewreturns (uint256[] memory ids, Round[] memory rounds_, RoundState[] memory states)
{
ids = roundsIds.values();
uint256 size = ids.length;
rounds_ =new Round[](size);
states =new RoundState[](size);
for (uint256 i =0; i < size; i++) {
rounds_[i] = rounds[ids[i]];
states[i] = getRoundState(ids[i]);
}
return (ids, rounds_, states);
}
/// @notice Returns the round./// @param roundId Id of the round.functiongetRound(uint256 roundId) publicviewreturns (Round memory) {
if (!roundsIds.contains(roundId)) revert RoundNotExists(roundId);
return rounds[roundId];
}
/// @notice Returns the round state./// @param roundId Id of the round.functiongetRoundState(uint256 roundId) publicviewreturns (RoundState) {
if (!roundsIds.contains(roundId)) revert RoundNotExists(roundId);
uint256 timestamp =block.timestamp;
if (timestamp < rounds[roundId].startTimestamp) return RoundState.PENDING;
if (timestamp >= rounds[roundId].endTimestamp || liquidityA ==0) {
return RoundState.VESTING;
}
return RoundState.SALE;
}
/// @inheritdoc IVestPresaleSchedulerfunctiongetTgeTimestamp() publicviewreturns (uint256) {
return tgeTimestamp;
}
/// @inheritdoc IVestPresaleSchedulerfunctiongetListingTimestamp() publicviewreturns (uint256) {
return listingTimestamp;
}
/// @notice Returns the fee collector address.functiongetFeeCollector() publicviewreturns (address) {
return feeCollectorProvider.getFeeCollector();
}
/// @notice Adds new round./// @param round Configuration of the round.function_addRound(Round memory round) internal{
if (bytes(round.name).length==0) revert Errors.UnacceptableValue();
if (round.startTimestamp ==0|| round.endTimestamp ==0) revert Errors.UnacceptableValue();
if (round.startTimestamp >= round.endTimestamp) revert Errors.UnacceptableValue();
unchecked {
++roundSerialId;
}
roundsIds.add(roundSerialId);
rounds[roundSerialId] = round;
emit RoundUpdated(roundSerialId);
}
/**
* @notice Pays for `tokenA` with `tokenB`
* @param bought how much a participant already bought
* @param allocation what’s participant’s allocation
* @param price attributes.price of the membership
* @param amountA Amount of tokenA to extend the membership.
*/// slither-disable-next-line reentrancy-no-ethfunction_buy(uint256 bought, uint256 allocation, uint256 price, uint256 amountA) internalreturns (uint256) {
uint256 available = MathHelper.min(liquidityA, allocation - bought);
uint256 buyingA = MathHelper.min(amountA, available);
if (buyingA ==0) revert OutOfLiquidityA();
uint256 tokenADecimals = ERC20Helper.decimals(tokenA);
uint256 amountBPaidSoFar = bought * price /10** tokenADecimals;
uint256 amountBSumAfterThisTransaction = (bought + buyingA) * price /10** tokenADecimals;
uint256 amountB = amountBSumAfterThisTransaction - amountBPaidSoFar;
if (amountB >0) {
uint256 receivedB = ERC20Helper.transferFrom(tokenB, _msgSender(), address(this), amountB);
if (receivedB != amountB) revert TokenWithTransferFees(address(tokenB));
unchecked {
liquidityB += amountB;
}
}
unchecked {
liquidityA -= buyingA;
}
return buyingA;
}
/**
* @notice Ensure the given attributes meet the requirements.
*
* @param attributes The membership attributes.
*/function_requireValidAttributes(IVestMembership.Attributes calldata attributes) internalpure{
if (attributes.tgeDenominator ==0|| attributes.cliffDenominator ==0) revert Errors.DenominatorZero();
if (attributes.cliffNumerator >0&& attributes.cliffDuration ==0) revert CliffWithImmediateUnlock();
if (attributes.vestingPeriodCount >0&& attributes.vestingPeriodDuration ==0) {
revert VestingWithImmediateUnlock();
}
if (attributes.vestingPeriodCount ==1) revert CliffLikeVesting();
if (attributes.tgeNumerator ==0&& attributes.cliffDuration ==0&& attributes.vestingPeriodCount ==0) {
revert VestingWithoutUnlocks();
}
if (attributes.vestingPeriodCount ==0&& attributes.cliffNumerator >0) {
revert CliffHeightWithoutSubsequentUnlocks();
}
if (
attributes.cliffDuration ==0&& attributes.vestingPeriodCount ==0&& attributes.tgeNumerator != attributes.tgeDenominator
) revert VestingSize();
if (attributes.tgeNumerator > attributes.tgeDenominator) revert VestingSize();
if (attributes.cliffNumerator > attributes.cliffDenominator) revert VestingSize();
if (attributes.tgeNumerator >0&& attributes.cliffNumerator >0) {
uint256 commonDenominator = attributes.tgeDenominator * attributes.cliffDenominator;
uint256 totalUnlocks = attributes.tgeNumerator * attributes.cliffDenominator
+ attributes.cliffNumerator * attributes.tgeDenominator;
if (totalUnlocks > commonDenominator) revert VestingSize();
}
}
/**
* @notice Ensure the sender can participate in sale state of a given round.
*
* Account cannot participate in the sale state if it is not on the whitelist or has
* already participated in a round.
*
* @param roundId Id of the round.
* @param attributes The membership attributes.
* @param proof Merkle tree proof.
*/function_requireCallerCanParticipateInSale(uint256 roundId,
IVestMembership.Attributes calldata attributes,
bytes32[] calldata proof
) internal{
address account = _msgSender();
bytes32 key =keccak256(
abi.encode(
account,
attributes.price,
attributes.allocation,
attributes.claimbackPeriod,
attributes.tgeNumerator,
attributes.tgeDenominator,
attributes.cliffDuration,
attributes.cliffNumerator,
attributes.cliffDenominator,
attributes.vestingPeriodCount,
attributes.vestingPeriodDuration,
attributes.tradeable
)
);
if (roundParticipants[roundId][key]) revert AlreadyRoundParticipant(roundId, account);
if (!MerkleProof.verify(proof, rounds[roundId].whitelistRoot, key)) revert Errors.AccountMismatch(account);
roundParticipants[roundId][key] =true;
}
}
Contract Source Code
File 28 of 28: Withdrawable.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;import { IERC20 } from"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title Withdrawable
*
* @notice This contract allows for withdrawing tokens and native Ether from the contract.
* It also provides a method to receive Ether into the contract.
*/abstractcontractWithdrawable{
usingSafeERC20forIERC20;
/// @notice Reference address is `address(0)`.errorWithdrawToZeroAddress();
/// @notice Ensures the caller is eligible to withdraw.modifierprotectedWithdrawal() virtual;
receive() externalpayablevirtual{ }
/// @notice Withdraws the token to the recipient./// @param to Address of the recipient./// @param token_ Address of the token./// @param amount Amount to withdraw.functionwithdrawToken(address to, IERC20 token_, uint256 amount) publicvirtualprotectedWithdrawal{
if (to ==address(0)) revert WithdrawToZeroAddress();
token_.safeTransfer(to, amount);
}
/// @notice Withdraws the native coin to the recipient./// @param to Address of the recipient.functionwithdrawCoin(addresspayable to) publicvirtualprotectedWithdrawal{
if (to ==address(0)) revert WithdrawToZeroAddress();
to.transfer(address(this).balance);
}
}