// 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 2 of 29: Boolean.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;/**
* Booleans are more expensive than uint256 or any type that takes up a full
* word because each write operation emits an extra SLOAD to first read the
* slot's contents, replace the bits taken up by the boolean, and then write
* back. This is the compiler's defense against contract upgrades and
* pointer aliasing, and it cannot be disabled.
*
* The most efficient way to store true/false values, then, is to use 1 for
* false and 2 for true.
*/libraryBoolean{
uint8publicconstant TRUE =2;
uint8publicconstant FALSE =1;
}
Contract Source Code
File 3 of 29: 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 29: 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 29: DynamicIds.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;/**
* Low-level utility library for manipulating Dynamic NFT ids.
*/libraryDynamicIds{
/**
* Creates a public id of an NFT by hashing a payload and using its first 16 bytes as an id suffix.
* @param id mint or public id of an NFT
* @param payload abi.encode() of properties fundamental for assesing NFT value
*/functioncreatePublicId(uint256 id, bytesmemory payload) internalpurereturns (uint256) {
returnuint256(bytes32(abi.encodePacked(getFirst16Bytes(id), getFirst16Bytes(keccak256(payload)))));
}
/**
* Creates a mint id of an NFT with the last 16 bytes equal to zero.
* @param mintPreimage abi.encode() of values uniquely identifying this NFT during minting.
* It’s advised to include block.timestamp to prevent DOS.
*/functioncreateMintId(bytesmemory mintPreimage) internalpurereturns (uint256) {
returnuint256(zeroLast16Bytes(keccak256(mintPreimage)));
}
/**
* Returns the first 16 bytes of a number
* @param value any 32-bytes long number
*/functiongetFirst16Bytes(uint256 value) internalpurereturns (bytes16) {
return getFirst16Bytes(bytes32(value));
}
/**
* Returns the first 16 bytes of a value
* @param value any 32-bytes long value
*/functiongetFirst16Bytes(bytes32 value) internalpurereturns (bytes16) {
returnbytes16(value);
}
/**
* Returns the last 16 bytes of a number
* @param value any 32-bytes long number
*/functiongetLast16Bytes(uint256 value) internalpurereturns (bytes16) {
return getLast16Bytes(bytes32(value));
}
/**
* Returns the last 16 bytes of a value
* @param value any 32-bytes long value
*/functiongetLast16Bytes(bytes32 value) internalpurereturns (bytes16) {
returnbytes16(value <<128);
}
/**
* Zeros the last 16 bytes of a number
* @param value any 32-bytes long number
*/functionzeroLast16Bytes(uint256 value) internalpurereturns (uint256) {
returnuint256(zeroLast16Bytes(bytes32(value)));
}
/**
* Zeros the last 16 bytes of a value
* @param value any 32-bytes long value
*/functionzeroLast16Bytes(bytes32 value) internalpurereturns (bytes32) {
return value >>128<<128;
}
}
Contract Source Code
File 6 of 29: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)pragmasolidity ^0.8.20;import {IERC165} from"./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualreturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 7 of 29: ERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)pragmasolidity ^0.8.20;import {IERC721} from"./IERC721.sol";
import {IERC721Receiver} from"./IERC721Receiver.sol";
import {IERC721Metadata} from"./extensions/IERC721Metadata.sol";
import {Context} from"../../utils/Context.sol";
import {Strings} from"../../utils/Strings.sol";
import {IERC165, ERC165} from"../../utils/introspection/ERC165.sol";
import {IERC721Errors} from"../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/abstractcontractERC721isContext, ERC165, IERC721, IERC721Metadata, IERC721Errors{
usingStringsforuint256;
// Token namestringprivate _name;
// Token symbolstringprivate _symbol;
mapping(uint256 tokenId =>address) private _owners;
mapping(address owner =>uint256) private _balances;
mapping(uint256 tokenId =>address) private _tokenApprovals;
mapping(address owner =>mapping(address operator =>bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return
interfaceId ==type(IERC721).interfaceId||
interfaceId ==type(IERC721Metadata).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/functionbalanceOf(address owner) publicviewvirtualreturns (uint256) {
if (owner ==address(0)) {
revert ERC721InvalidOwner(address(0));
}
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId) publicviewvirtualreturns (address) {
return _requireOwned(tokenId);
}
/**
* @dev See {IERC721Metadata-name}.
*/functionname() publicviewvirtualreturns (stringmemory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/functionsymbol() publicviewvirtualreturns (stringmemory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/functiontokenURI(uint256 tokenId) publicviewvirtualreturns (stringmemory) {
_requireOwned(tokenId);
stringmemory baseURI = _baseURI();
returnbytes(baseURI).length>0 ? string.concat(baseURI, tokenId.toString()) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/function_baseURI() internalviewvirtualreturns (stringmemory) {
return"";
}
/**
* @dev See {IERC721-approve}.
*/functionapprove(address to, uint256 tokenId) publicvirtual{
_approve(to, tokenId, _msgSender());
}
/**
* @dev See {IERC721-getApproved}.
*/functiongetApproved(uint256 tokenId) publicviewvirtualreturns (address) {
_requireOwned(tokenId);
return _getApproved(tokenId);
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicvirtual{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/functionisApprovedForAll(address owner, address operator) publicviewvirtualreturns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/functiontransferFrom(addressfrom, address to, uint256 tokenId) publicvirtual{
if (to ==address(0)) {
revert ERC721InvalidReceiver(address(0));
}
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.address previousOwner = _update(to, tokenId, _msgSender());
if (previousOwner !=from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom, address to, uint256 tokenId) public{
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom, address to, uint256 tokenId, bytesmemory data) publicvirtual{
transferFrom(from, to, tokenId);
_checkOnERC721Received(from, to, tokenId, data);
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*
* IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
* core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances
* consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
* `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
*/function_ownerOf(uint256 tokenId) internalviewvirtualreturns (address) {
return _owners[tokenId];
}
/**
* @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
*/function_getApproved(uint256 tokenId) internalviewvirtualreturns (address) {
return _tokenApprovals[tokenId];
}
/**
* @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
* particular (ignoring whether it is owned by `owner`).
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/function_isAuthorized(address owner, address spender, uint256 tokenId) internalviewvirtualreturns (bool) {
return
spender !=address(0) &&
(owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
}
/**
* @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
* Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets
* the `spender` for the specific `tokenId`.
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/function_checkAuthorized(address owner, address spender, uint256 tokenId) internalviewvirtual{
if (!_isAuthorized(owner, spender, tokenId)) {
if (owner ==address(0)) {
revert ERC721NonexistentToken(tokenId);
} else {
revert ERC721InsufficientApproval(spender, tokenId);
}
}
}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
* a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
*
* WARNING: Increasing an account's balance using this function tends to be paired with an override of the
* {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
* remain consistent with one another.
*/function_increaseBalance(address account, uint128 value) internalvirtual{
unchecked {
_balances[account] += value;
}
}
/**
* @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
* (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that
* `auth` is either the owner of the token, or approved to operate on the token (by the owner).
*
* Emits a {Transfer} event.
*
* NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
*/function_update(address to, uint256 tokenId, address auth) internalvirtualreturns (address) {
addressfrom= _ownerOf(tokenId);
// Perform (optional) operator checkif (auth !=address(0)) {
_checkAuthorized(from, auth, tokenId);
}
// Execute the updateif (from!=address(0)) {
// Clear approval. No need to re-authorize or emit the Approval event
_approve(address(0), tokenId, address(0), false);
unchecked {
_balances[from] -=1;
}
}
if (to !=address(0)) {
unchecked {
_balances[to] +=1;
}
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
returnfrom;
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/function_mint(address to, uint256 tokenId) internal{
if (to ==address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner !=address(0)) {
revert ERC721InvalidSender(address(0));
}
}
/**
* @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/function_safeMint(address to, uint256 tokenId) internal{
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/function_safeMint(address to, uint256 tokenId, bytesmemory data) internalvirtual{
_mint(to, tokenId);
_checkOnERC721Received(address(0), to, tokenId, data);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/function_burn(uint256 tokenId) internal{
address previousOwner = _update(address(0), tokenId, address(0));
if (previousOwner ==address(0)) {
revert ERC721NonexistentToken(tokenId);
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/function_transfer(addressfrom, address to, uint256 tokenId) internal{
if (to ==address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner ==address(0)) {
revert ERC721NonexistentToken(tokenId);
} elseif (previousOwner !=from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
* are aware of the ERC721 standard to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is like {safeTransferFrom} in the sense that it invokes
* {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `tokenId` token must exist and be owned by `from`.
* - `to` cannot be the zero address.
* - `from` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/function_safeTransfer(addressfrom, address to, uint256 tokenId) internal{
_safeTransfer(from, to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/function_safeTransfer(addressfrom, address to, uint256 tokenId, bytesmemory data) internalvirtual{
_transfer(from, to, tokenId);
_checkOnERC721Received(from, to, tokenId, data);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
* either the owner of the token, or approved to operate on all tokens held by this owner.
*
* Emits an {Approval} event.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/function_approve(address to, uint256 tokenId, address auth) internal{
_approve(to, tokenId, auth, true);
}
/**
* @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
* emitted in the context of transfers.
*/function_approve(address to, uint256 tokenId, address auth, bool emitEvent) internalvirtual{
// Avoid reading the owner unless necessaryif (emitEvent || auth !=address(0)) {
address owner = _requireOwned(tokenId);
// We do not use _isAuthorized because single-token approvals should not be able to call approveif (auth !=address(0) && owner != auth &&!isApprovedForAll(owner, auth)) {
revert ERC721InvalidApprover(auth);
}
if (emitEvent) {
emit Approval(owner, to, tokenId);
}
}
_tokenApprovals[tokenId] = to;
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Requirements:
* - operator can't be the address zero.
*
* Emits an {ApprovalForAll} event.
*/function_setApprovalForAll(address owner, address operator, bool approved) internalvirtual{
if (operator ==address(0)) {
revert ERC721InvalidOperator(operator);
}
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
* Returns the owner.
*
* Overrides to ownership logic should be done to {_ownerOf}.
*/function_requireOwned(uint256 tokenId) internalviewreturns (address) {
address owner = _ownerOf(tokenId);
if (owner ==address(0)) {
revert ERC721NonexistentToken(tokenId);
}
return owner;
}
/**
* @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the
* recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
*/function_checkOnERC721Received(addressfrom, address to, uint256 tokenId, bytesmemory data) internal{
if (to.code.length>0) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
if (retval != IERC721Receiver.onERC721Received.selector) {
revert ERC721InvalidReceiver(to);
}
} catch (bytesmemory reason) {
if (reason.length==0) {
revert ERC721InvalidReceiver(to);
} else {
/// @solidity memory-safe-assemblyassembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
}
Contract Source Code
File 8 of 29: ERC721DynamicIds.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;import { ERC721 } from"@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { IERC721 } from"@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { ERC721Enumerable } from"@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import { DynamicIds } from"src/libraries/DynamicIds.sol";
/**
* @dev ERC721DynamicIds is a clever trick to make trading NFTs with dynamic traits safe.
*
* Stable value represented by an NFT is a prerequisite for safe trading today.
*
* If the value of an NFT can be changed by the seller, they can rug the buyer by using up the NFT before they accept they buy offer.
*
* Dynamic ids solve that problem by burning the old NFT and minting a new one every time the value of an NFT changes.
* That invalidates all offers made for an NFT before the value changed.
*
* A naive implementation would perform literal burn and mint every time but that’s extremely gas-inefficient.
*
* A clever implementation changes NFT id every time its value changes, emits Transfer events as if the NFT was
* burned and minted, while in reality no storage writes are performed.
*
* For this to work, we use 32-byte numbers as ids where:
* - the first 16 bytes are calculated during the mint and never change again.
* - the last 16 bytes are calculated every time the value changes.
*
* This results in a new id being issued every time the value changes while keeping some unique part of it (the first 16 bytes)
* constant so that we can keep track of owners, allowances, and other properties.
*
* An id emitted in Transfer events and visible to the outside world is called a publicId.
* An id used internally to keep track of things is called a mintId.
*
* The last 16 bytes of mintId MUST equal zero.
*
* A watchful reader will notice that by splitting ids in two 16-bytes long parts, we increase the risk of id collision.
* This risk is described by The Birthday Problem.
* For 16-bytes long ids, the risk of collision raises above 1% after generating 52 * 10^18 perfectly random ids.
* That makes a collision unlikely for most protocols using this technique.
*
* Note that _safeMint function prevents minting NFTs with an id that already exists.
*
* To prevent DOS due to id collision, it’s advised protocols mix in block.timestamp into the mintId payload.
*
* Note: this contract requires a patch on OpenZeppelin ERC721 implementation such that the _update function does not emit
* the Transfer event because it only has access to a mintId while Transfer events should be emitted using publicId.
*
* @notice This contract is marked as abstract because inheriting contract MUST override _getPayload function so that it returns
* a unique payload every time the value of the NFT changes.
*/abstractcontractERC721DynamicIdsisERC721Enumerable{
/**
* An event emited during the NFT minting that allows for efficient querying of an arbitrary data attached to the NFT.
* @param mintId an immutable id with last 16 bytes zeroed. The same that is used internally.
* @param data arbitrary data assigned to the NFT. This can include data that is either immutable or does not cause public id to change when updated.
*/eventDynamicIdNFTMinted(uint256indexed mintId, addressindexed owner, bytes data);
/**
* This is a special event that allows for easy tracking of the NFT across value changes.
* @param mintId an immutable id with last 16 bytes zeroed. The same that is used internally.
* @param newPublicId new public id after the update happened.
* @param payload payload resulting in the new public id.
*/eventDynamicIdNFTUpdated(uint256indexed mintId, uint256indexed newPublicId, bytes payload);
errorInvalidMintId(uint256 mintId);
/**
* This mint function SHOULD be used instead of _safeMint as it takes care of emitting the right events.
* @param to an address receiving an NFT
* @param mintId an immutable id with last 16 bytes zeroed. The same that is used internally.
* @param data arbitrary data assigned to the NFT. This can include data that is either immutable or does not cause public id to change when updated.
*/function_mintDynamicIdNFT(address to, uint256 mintId, bytesmemory data) internalreturns (uint256) {
bytesmemory payload = _getPayload(mintId);
uint256 publicId = DynamicIds.createPublicId(mintId, payload);
_safeMint(to, publicId, data);
emit DynamicIdNFTMinted(mintId, to, data);
emit DynamicIdNFTUpdated(mintId, publicId, payload);
return publicId;
}
/**
* This MUST be used every time a publicId is consumed as a parameter to:
* - validate given publicId is valid
* - get mintId to perform access storage correctly
*
* It is similar to _requireOwned from OpenZeppelin’s ERC721 implementation.
*
* @param publicId a public id of an NFT
*/function_requireValidPublicId(uint256 publicId) internalviewreturns (uint256 mintId) {
mintId = DynamicIds.zeroLast16Bytes(publicId);
bytes16 publicIdLast16Bytes = DynamicIds.getLast16Bytes(publicId);
if (DynamicIds.getFirst16Bytes(keccak256(_getPayload(mintId))) != publicIdLast16Bytes) {
revert ERC721NonexistentToken(publicId);
}
}
/**
* This MUST be used once in every transaction that changes the value of an NFT such that
* the payload returned by the _getPayload function is diffrent than before.
*
* This lets the outside world know the old NFT has been burned and the new NFT has been minted.
*
* @param prevPublicId a public id of an NFT
* @param mintId a mint id of an NFT
*/function_updatePublicId(uint256 prevPublicId, uint256 mintId) internalreturns (uint256 newId) {
bytesmemory payload = _getPayload(mintId);
newId = _getPublicId(mintId, payload);
address owner = _ownerOf(mintId);
_checkOnERC721Received(address(0), owner, newId, "");
emit IERC721.Transfer(owner, address(0), prevPublicId);
emit IERC721.Transfer(address(0), owner, newId);
emit DynamicIdNFTUpdated(mintId, newId, payload);
}
/**
* This function MUST be overriten by an inheriting smart contract such that the payload
* changes every time the value of an underlying NFT changes.
* @param mintId a mint id of an NFT
*/function_getPayload(uint256 mintId) internalviewvirtualreturns (bytesmemory payload);
/**
* Translates mintId to publicId. Useful for overriding functions that return mintId.
* @param mintId a mint id of an NFT
* @param payload the result of the _getPayload function
*/function_getPublicId(uint256 mintId, bytesmemory payload) privatepurereturns (uint256 publicId) {
return DynamicIds.createPublicId(mintId, payload);
}
/*
* ERC721 overrides.
*
* We override all public methods that take tokenId as a parameter
* except safeTransferFrom(address from, address to, uint256 tokenId)
* because it calls
* function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data)
* so translating tokenId twice would be wasteful.
*
* All internal transactions must receive mintId to work correctly.
*
* We also override _safeMint to validate mintId and emit a proper Transfer event.
*/functionownerOf(uint256 publicId) publicviewoverride(ERC721, IERC721) returns (address) {
uint256 mintId = _requireValidPublicId(publicId);
returnsuper.ownerOf(mintId);
}
functiontokenURI(uint256 publicId) publicviewvirtualoverridereturns (stringmemory) {
uint256 mintId = _requireValidPublicId(publicId);
returnsuper.tokenURI(mintId);
}
functionapprove(address to, uint256 publicId) publicoverride(ERC721, IERC721) {
uint256 mintId = _requireValidPublicId(publicId);
super.approve(to, mintId);
emit IERC721.Approval(_msgSender(), to, publicId);
}
functiongetApproved(uint256 publicId) publicviewoverride(ERC721, IERC721) returns (address) {
uint256 mintId = _requireValidPublicId(publicId);
returnsuper.getApproved(mintId);
}
functiontransferFrom(addressfrom, address to, uint256 publicId) publicvirtualoverride(ERC721, IERC721) {
uint256 mintId = _requireValidPublicId(publicId);
super.transferFrom(from, to, mintId);
emit IERC721.Transfer(from, to, publicId);
}
functionsafeTransferFrom(addressfrom, address to, uint256 publicId, bytesmemory data)
publicoverride(ERC721, IERC721)
{
transferFrom(from, to, publicId);
_checkOnERC721Received(from, to, publicId, data);
}
function_safeMint(address to, uint256 publicId, bytesmemory data) internaloverride{
if (DynamicIds.getLast16Bytes(publicId) ==0) revert InvalidMintId(publicId);
uint256 mintId = _requireValidPublicId(publicId);
super._safeMint(to, mintId, data);
emit IERC721.Transfer(address(0), to, publicId);
}
/*
* ERC721Enumerable overrides.
*
* We override all public methods that take tokenId as a parameter or return tokenId.
*
* All internal transactions must receive mintId to work correctly.
*/functiontokenOfOwnerByIndex(address owner, uint256 index) publicviewoverridereturns (uint256) {
uint256 mintId =super.tokenOfOwnerByIndex(owner, index);
return _getPublicId(mintId, _getPayload(mintId));
}
functiontokenByIndex(uint256 index) publicviewoverridereturns (uint256) {
uint256 mintId =super.tokenByIndex(index);
return _getPublicId(mintId, _getPayload(mintId));
}
}
Contract Source Code
File 9 of 29: ERC721Enumerable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/ERC721Enumerable.sol)pragmasolidity ^0.8.20;import {ERC721} from"../ERC721.sol";
import {IERC721Enumerable} from"./IERC721Enumerable.sol";
import {IERC165} from"../../../utils/introspection/ERC165.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds enumerability
* of all the token ids in the contract as well as all token ids owned by each account.
*
* CAUTION: `ERC721` extensions that implement custom `balanceOf` logic, such as `ERC721Consecutive`,
* interfere with enumerability and should not be used together with `ERC721Enumerable`.
*/abstractcontractERC721EnumerableisERC721, IERC721Enumerable{
mapping(address owner =>mapping(uint256 index =>uint256)) private _ownedTokens;
mapping(uint256 tokenId =>uint256) private _ownedTokensIndex;
uint256[] private _allTokens;
mapping(uint256 tokenId =>uint256) private _allTokensIndex;
/**
* @dev An `owner`'s token query was out of bounds for `index`.
*
* NOTE: The owner being `address(0)` indicates a global out of bounds index.
*/errorERC721OutOfBoundsIndex(address owner, uint256 index);
/**
* @dev Batch mint is not allowed.
*/errorERC721EnumerableForbiddenBatchMint();
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(IERC165, ERC721) returns (bool) {
return interfaceId ==type(IERC721Enumerable).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/functiontokenOfOwnerByIndex(address owner, uint256 index) publicviewvirtualreturns (uint256) {
if (index >= balanceOf(owner)) {
revert ERC721OutOfBoundsIndex(owner, index);
}
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/functiontotalSupply() publicviewvirtualreturns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/functiontokenByIndex(uint256 index) publicviewvirtualreturns (uint256) {
if (index >= totalSupply()) {
revert ERC721OutOfBoundsIndex(address(0), index);
}
return _allTokens[index];
}
/**
* @dev See {ERC721-_update}.
*/function_update(address to, uint256 tokenId, address auth) internalvirtualoverridereturns (address) {
address previousOwner =super._update(to, tokenId, auth);
if (previousOwner ==address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} elseif (previousOwner != to) {
_removeTokenFromOwnerEnumeration(previousOwner, tokenId);
}
if (to ==address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} elseif (previousOwner != to) {
_addTokenToOwnerEnumeration(to, tokenId);
}
return previousOwner;
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/function_addTokenToOwnerEnumeration(address to, uint256 tokenId) private{
uint256 length = balanceOf(to) -1;
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/function_addTokenToAllTokensEnumeration(uint256 tokenId) private{
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/function_removeTokenFromOwnerEnumeration(addressfrom, uint256 tokenId) private{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and// then delete the last slot (swap and pop).uint256 lastTokenIndex = balanceOf(from);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessaryif (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the arraydelete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/function_removeTokenFromAllTokensEnumeration(uint256 tokenId) private{
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and// then delete the last slot (swap and pop).uint256 lastTokenIndex = _allTokens.length-1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding// an 'if' statement (like in _removeTokenFromOwnerEnumeration)uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index// This also deletes the contents at the last position of the arraydelete _allTokensIndex[tokenId];
_allTokens.pop();
}
/**
* See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch
*/function_increaseBalance(address account, uint128 amount) internalvirtualoverride{
if (amount >0) {
revert ERC721EnumerableForbiddenBatchMint();
}
super._increaseBalance(account, amount);
}
}
Contract Source Code
File 10 of 29: 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 11 of 29: 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 12 of 29: 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 13 of 29: 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 14 of 29: 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 15 of 29: 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 16 of 29: 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: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)pragmasolidity ^0.8.20;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
// 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;
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)pragmasolidity ^0.8.20;import {Context} from"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/errorOwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/errorOwnableInvalidOwner(address owner);
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/constructor(address initialOwner) {
if (initialOwner ==address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
if (newOwner ==address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 25 of 29: 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 26 of 29: 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 27 of 29: VestMembership.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.23;import { Ownable } from"@openzeppelin/contracts/access/Ownable.sol";
import { ERC721 } from"@openzeppelin/contracts/token/ERC721/ERC721.sol";
import { IERC721 } from"@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IERC721Metadata } from"@openzeppelin/contracts/interfaces/IERC721Metadata.sol";
import { IERC2981 } from"@openzeppelin/contracts/interfaces/IERC2981.sol";
import { Errors } from"src/libraries/Errors.sol";
import { Boolean } from"src/libraries/Boolean.sol";
import { Membership } from"src/types/Configuration.sol";
import { DynamicIds } from"src/libraries/DynamicIds.sol";
import { ERC721DynamicIds } from"src/utils/ERC721DynamicIds.sol";
import { IVestMembership } from"src/IVestMembership.sol";
import { IVestMembershipDescriptor } from"src/VestMembershipDescriptor.sol";
import { IVestPresaleScheduler } from"src/IVestPresaleScheduler.sol";
import { IVestFeeCollectorProvider } from"./IVestFeeCollectorProvider.sol";
/**
* @title VestMembership
* @notice An implementation of smart contract representing membership in a presale.
*/contractVestMembershipisIERC2981, ERC721DynamicIds, IVestMembership, Ownable{
/// @notice Collection of the metadata.
Metadata internal _metadata;
/// @notice Fees configuration.
Membership.Fees internal _fees;
/// @notice Reference to external scheduler contract.
IVestPresaleScheduler internalimmutable _scheduler;
/// @notice Reference to external descriptor contract.
IVestMembershipDescriptor internalimmutable _descriptor;
/// @notice Reference to external fee collector provider.
IVestFeeCollectorProvider internalimmutable _feeCollectorProvider;
/// @notice Information about the usage by membership.mapping(uint256 mintId => Usage) internal _usages;
/// @notice Information about the membership round.mapping(uint256 mintId =>uint256) internal _rounds;
/// @notice Collection of the attributes of each membership.mapping(uint256 mintId => Attributes) internal _attributes;
/// @notice Transfer not allowed for the given membership./// @param publicId Id of the membership.errorTransferNotAllowed(uint256 publicId);
/// @notice Contract state initialization./// @param scheduler Address of the external scheduler./// @param feeCollectorProvider Address of the external fee collector provider./// @param configuration Configuration of the membership.constructor(address owner_,
IVestPresaleScheduler scheduler,
IVestFeeCollectorProvider feeCollectorProvider,
Membership.Configuration memory configuration
)
Ownable(owner_)
ERC721(
configuration.descriptor.name(configuration.metadata),
configuration.descriptor.symbol(configuration.metadata)
)
{
if (address(scheduler) ==address(0)) revert Errors.UnacceptableReference();
if (address(feeCollectorProvider) ==address(0)) revert Errors.UnacceptableReference();
_fees = configuration.fees;
_scheduler = scheduler;
_metadata = configuration.metadata;
_descriptor = configuration.descriptor;
_feeCollectorProvider = feeCollectorProvider;
}
/**
* Increases the usage.current
* @notice This function does no validation except for the valid id.
* It’s up to the consumer to ensure any invariants.
* @param publicId publicId of an NFT
* @param amount usage.current increases by amount
*/functionconsume(uint256 publicId, uint256 amount) publiconlyOwnerreturns (uint256) {
uint256 mintId = _requireValidPublicId(publicId);
_usages[mintId].current += amount;
return _updatePublicId(publicId, mintId);
}
/**
* Increases the usage.max
* @notice This function does no validation except for the valid id.
* It’s up to the consumer to ensure any invariants.
* @param publicId publicId of an NFT
* @param amount usage.max increases by amount
*/functionextend(uint256 publicId, uint256 amount) publiconlyOwnerreturns (uint256) {
uint256 mintId = _requireValidPublicId(publicId);
_usages[mintId].max+= amount;
return _updatePublicId(publicId, mintId);
}
/**
* Decreases the usage.max
* @notice This function does no validation except for the valid id.
* It’s up to the consumer to ensure any invariants.
* @param publicId publicId of an NFT
* @param amount usage.max subtrahend
*/functionreduce(uint256 publicId, uint256 amount) publiconlyOwnerreturns (uint256) {
uint256 mintId = _requireValidPublicId(publicId);
_usages[mintId].max-= amount;
return _updatePublicId(publicId, mintId);
}
/// @inheritdoc IVestMembershipfunctiongetRoundId(uint256 publicId) externalviewreturns (uint256) {
uint256 mintId = _requireValidPublicId(publicId);
return _rounds[mintId];
}
/// @inheritdoc IVestMembershipfunctionunlocked(uint256 publicId) externalviewreturns (uint256) {
uint256 mintId = _requireValidPublicId(publicId);
uint256 start = getStartTimestamp();
uint256 allocation = _usages[mintId].max;
IVestMembership.Attributes memory attributes = _attributes[mintId];
return unlocked(start, allocation, attributes);
}
/// @inheritdoc IVestMembershipfunctiongetStartTimestamp() publicviewreturns (uint256) {
return _scheduler.getTgeTimestamp();
}
/// @inheritdoc IVestMembershipfunctionunlocked(uint256 start, uint256 allocation, IVestMembership.Attributes memory attributes)
publicviewreturns (uint256)
{
uint256 timestamp =block.timestamp;
if (timestamp < start) return0;
uint256 duration = attributes.vestingPeriodCount * attributes.vestingPeriodDuration + attributes.cliffDuration;
if (timestamp >= start + duration) return allocation;
uint256 tge = (allocation * attributes.tgeNumerator) / attributes.tgeDenominator;
if (timestamp < start + attributes.cliffDuration) return tge;
uint256 cliffUnlock = (allocation * attributes.cliffNumerator) / attributes.cliffDenominator;
uint256 elapsedTime = timestamp - (start + attributes.cliffDuration);
uint256 elapsedPeriods = elapsedTime / attributes.vestingPeriodDuration;
if (attributes.cliffDuration !=0&& attributes.cliffNumerator ==0) elapsedPeriods = elapsedPeriods +1;
return tge + cliffUnlock + ((allocation - tge - cliffUnlock) * elapsedPeriods) / attributes.vestingPeriodCount;
}
/// @inheritdoc IVestMembershipfunctionmint(address owner_, uint256 roundId, uint256 currentUsage, uint256 maxUsage, Attributes memory attributes)
publicvirtualonlyOwnerreturns (uint256 publicId)
{
uint256 mintId = DynamicIds.createMintId(abi.encodePacked(owner_, roundId, maxUsage, block.timestamp));
Usage memory usage = Usage({ current: currentUsage, max: maxUsage });
_rounds[mintId] = roundId;
_usages[mintId] = usage;
_attributes[mintId] = attributes;
bytesmemory data =abi.encode(usage, roundId, attributes);
publicId = _mintDynamicIdNFT(owner_, mintId, data);
}
/// @inheritdoc IERC721/// @dev Overriding to implement custom `transferFrom` blocking rules.functiontransferFrom(addressfrom, address to, uint256 publicId) publicoverride(ERC721DynamicIds, IERC721) {
if (_msgSender() != ownerOf(publicId)) {
IVestMembership.Attributes memory attributes = getAttributes(publicId);
// Transferring is blocked when the `tradeable` attribute is equal to false.if (attributes.tradeable == Boolean.FALSE) revert TransferNotAllowed(publicId);
// Transferring is blocked before listing timestamp.if (_scheduler.getListingTimestamp() ==0||block.timestamp< _scheduler.getListingTimestamp()) {
revert TransferNotAllowed(publicId);
}
}
super.transferFrom(from, to, publicId);
}
/// @inheritdoc IVestMembershipfunctiongetUsage(uint256 publicId) publicviewreturns (Usage memory) {
uint256 mintId = _requireValidPublicId(publicId);
return _usages[mintId];
}
/// @inheritdoc IVestMembershipfunctiongetAttributes(uint256 publicId) publicviewreturns (Attributes memory) {
uint256 mintId = _requireValidPublicId(publicId);
return _attributes[mintId];
}
/// @inheritdoc IERC721MetadatafunctiontokenURI(uint256 publicId) publicviewoverridereturns (stringmemory) {
uint256 mintId = _requireValidPublicId(publicId);
_requireOwned(mintId);
return _descriptor.tokenURI(getStartTimestamp(), _usages[mintId], _metadata, _attributes[mintId]);
}
/// @inheritdoc IERC2981functionroyaltyInfo(uint256, uint256 salePrice) publicviewvirtualreturns (address, uint256) {
uint256 royaltyAmount = (salePrice * _fees.numerator) / _fees.denominator;
return (_feeCollectorProvider.getFeeCollector(), royaltyAmount);
}
/// @inheritdoc ERC721DynamicIdsfunction_getPayload(uint256 mintId) internalviewoverridereturns (bytesmemory payload) {
returnabi.encode(_usages[mintId]);
}
}
Contract Source Code
File 28 of 29: 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 29 of 29: draft-IERC6093.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)pragmasolidity ^0.8.20;/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/interfaceIERC20Errors{
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/errorERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/errorERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/errorERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/errorERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/errorERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/errorERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/interfaceIERC721Errors{
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/errorERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/errorERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/errorERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/errorERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/errorERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/errorERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/errorERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/errorERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/interfaceIERC1155Errors{
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/errorERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/errorERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/errorERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/errorERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/errorERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/errorERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/errorERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}