// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>0;
}
/**
* @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
// 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(errorMessage);
}
}
}
}
Contract Source Code
File 3 of 37: Array.sol
Contract Source Code
File 4 of 37: Base64.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/Base64.sol)pragmasolidity ^0.8.0;/**
* @dev Provides a set of functions to operate with Base64 strings.
*
* _Available since v4.5._
*/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 5 of 37: BokkyPooBahsDateTimeLibrary.sol
Contract Source Code
File 6 of 37: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @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;
}
}
Contract Source Code
File 7 of 37: DateTime.sol
Contract Source Code
File 8 of 37: DefaultOperatorFilterer.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.13;import {OperatorFilterer} from"./OperatorFilterer.sol";
/**
* @title DefaultOperatorFilterer
* @notice Inherits from OperatorFilterer and automatically subscribes to the default OpenSea subscription.
*/abstractcontractDefaultOperatorFiltererisOperatorFilterer{
addressconstant DEFAULT_SUBSCRIPTION =address(0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6);
constructor() OperatorFilterer(DEFAULT_SUBSCRIPTION, true) {}
}
Contract Source Code
File 9 of 37: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^0.8.0;import"./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);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 10 of 37: ERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)pragmasolidity ^0.8.0;import"./IERC20.sol";
import"./extensions/IERC20Metadata.sol";
import"../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/contractERC20isContext, IERC20, IERC20Metadata{
mapping(address=>uint256) private _balances;
mapping(address=>mapping(address=>uint256)) private _allowances;
uint256private _totalSupply;
stringprivate _name;
stringprivate _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/functiondecimals() publicviewvirtualoverridereturns (uint8) {
return18;
}
/**
* @dev See {IERC20-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/functionbalanceOf(address account) publicviewvirtualoverridereturns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/functiontransfer(address to, uint256 amount) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
returntrue;
}
/**
* @dev See {IERC20-allowance}.
*/functionallowance(address owner, address spender) publicviewvirtualoverridereturns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionapprove(address spender, uint256 amount) publicvirtualoverridereturns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
returntrue;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/functiontransferFrom(addressfrom,
address to,
uint256 amount
) publicvirtualoverridereturns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
returntrue;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/functionincreaseAllowance(address spender, uint256 addedValue) publicvirtualreturns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
returntrue;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/functiondecreaseAllowance(address spender, uint256 subtractedValue) publicvirtualreturns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
returntrue;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/function_transfer(addressfrom,
address to,
uint256 amount
) internalvirtual{
require(from!=address(0), "ERC20: transfer from the zero address");
require(to !=address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/function_mint(address account, uint256 amount) internalvirtual{
require(account !=address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/function_burn(address account, uint256 amount) internalvirtual{
require(account !=address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/function_approve(address owner,
address spender,
uint256 amount
) internalvirtual{
require(owner !=address(0), "ERC20: approve from the zero address");
require(spender !=address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/function_spendAllowance(address owner,
address spender,
uint256 amount
) internalvirtual{
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance !=type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom,
address to,
uint256 amount
) internalvirtual{}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_afterTokenTransfer(addressfrom,
address to,
uint256 amount
) internalvirtual{}
}
Contract Source Code
File 11 of 37: ERC2771Context.sol
Contract Source Code
File 12 of 37: ERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)pragmasolidity ^0.8.0;import"./IERC721.sol";
import"./IERC721Receiver.sol";
import"./extensions/IERC721Metadata.sol";
import"../../utils/Address.sol";
import"../../utils/Context.sol";
import"../../utils/Strings.sol";
import"../../utils/introspection/ERC165.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}.
*/contractERC721isContext, ERC165, IERC721, IERC721Metadata{
usingAddressforaddress;
usingStringsforuint256;
// Token namestringprivate _name;
// Token symbolstringprivate _symbol;
// Mapping from token ID to owner addressmapping(uint256=>address) private _owners;
// Mapping owner address to token countmapping(address=>uint256) private _balances;
// Mapping from token ID to approved addressmapping(uint256=>address) private _tokenApprovals;
// Mapping from owner to operator approvalsmapping(address=>mapping(address=>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) publicviewvirtualoverridereturns (uint256) {
require(owner !=address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId) publicviewvirtualoverridereturns (address) {
address owner = _owners[tokenId];
require(owner !=address(0), "ERC721: invalid token ID");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/functiontokenURI(uint256 tokenId) publicviewvirtualoverridereturns (stringmemory) {
_requireMinted(tokenId);
stringmemory baseURI = _baseURI();
returnbytes(baseURI).length>0 ? string(abi.encodePacked(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) publicvirtualoverride{
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/functiongetApproved(uint256 tokenId) publicviewvirtualoverridereturns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicvirtualoverride{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/functionisApprovedForAll(address owner, address operator) publicviewvirtualoverridereturns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/functiontransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
//solhint-disable-next-line max-line-lengthrequire(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) publicvirtualoverride{
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytesmemory data
) publicvirtualoverride{
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner nor approved");
_safeTransfer(from, to, tokenId, data);
}
/**
* @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.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - 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,
bytesmemory data
) internalvirtual{
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/function_exists(uint256 tokenId) internalviewvirtualreturns (bool) {
return _owners[tokenId] !=address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/function_isApprovedOrOwner(address spender, uint256 tokenId) internalviewvirtualreturns (bool) {
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* 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) internalvirtual{
_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);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @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) internalvirtual{
require(to !=address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] +=1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/function_burn(uint256 tokenId) internalvirtual{
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -=1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), 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
) internalvirtual{
require(ERC721.ownerOf(tokenId) ==from, "ERC721: transfer from incorrect owner");
require(to !=address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -=1;
_balances[to] +=1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/function_approve(address to, uint256 tokenId) internalvirtual{
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/function_setApprovalForAll(address owner,
address operator,
bool approved
) internalvirtual{
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/function_requireMinted(uint256 tokenId) internalviewvirtual{
require(_exists(tokenId), "ERC721: invalid token ID");
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* 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
* @return bool whether the call correctly returned the expected magic value
*/function_checkOnERC721Received(addressfrom,
address to,
uint256 tokenId,
bytesmemory data
) privatereturns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytesmemory reason) {
if (reason.length==0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
/// @solidity memory-safe-assemblyassembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
returntrue;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom,
address to,
uint256 tokenId
) internalvirtual{}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_afterTokenTransfer(addressfrom,
address to,
uint256 tokenId
) internalvirtual{}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @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 amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 amount) 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 `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom,
address to,
uint256 amount
) externalreturns (bool);
}
Contract Source Code
File 18 of 37: IERC20Metadata.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/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 19 of 37: IERC2771.sol
Contract Source Code
File 20 of 37: IERC2981.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)pragmasolidity ^0.8.0;import"../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.
*
* _Available since v4.5._
*/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 21 of 37: IERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)pragmasolidity ^0.8.0;import"../../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: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* 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 caller.
*
* 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);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)pragmasolidity ^0.8.0;/**
* @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: MITpragmasolidity ^0.8.10;/*
\\ // ||||||||||| |\ || A CRYPTOCURRENCY FOR THE MASSES
\\ // || |\\ ||
\\ // || ||\\ || PRINCIPLES OF XEN:
\\// || || \\ || - No pre-mint; starts with zero supply
XX |||||||| || \\ || - No admin keys
//\\ || || \\ || - Immutable contract
// \\ || || \\||
// \\ || || \\|
// \\ ||||||||||| || \| Copyright (C) FairCrypto Foundation 2022-2023
*/libraryMagicNumbers{
uint256constant VERSION =1;
stringpublicconstant AUTHORS ="@MrJackLevin @lbelyaev faircrypto.org";
// There's 370 fibs that fit in uint256 numberuint256constant MAX_UINT256_FIB_IDX =370;
// Max fib number that fits into uint256 sizeuint256constant MAX_UINT256_FIB =94611056096305838013295371573764256526437182762229865607320618320601813254535;
// Max fib index supported by this Libraryuint256constant MAX_FIB_IDX =90;
// Max number that could be safely tested by this Libraryuint256constant MAX_SUPPORTED_FIB_CANDIDATE =2**62-1;
/**
@dev First 60 Fibonacci numbers, which fit into uint64
*/functionfibs64() internalpurereturns (uint64[60] memory) {
return [
uint64(0), 1, 1,
2, 3, 5,
8, 13, 21,
34, 55, 89,
144, 233, 377,
610, 987, 1597,
2584, 4181, 6765,
10946, 17711, 28657,
46368, 75025, 121393,
196418, 317811, 514229,
832040, 1346269, 2178309,
3524578, 5702887, 9227465,
14930352, 24157817, 39088169,
63245986, 102334155, 165580141,
267914296, 433494437, 701408733,
1134903170, 1836311903, 2971215073,
4807526976, 7778742049, 12586269025,
20365011074, 32951280099, 53316291173,
86267571272, 139583862445, 225851433717,
365435296162, 591286729879, 956722026041
];
}
/**
@dev Tests if number is a fib via a linear lookup in the table above
*/functionisFibs64(uint256 n) internalpurereturns (bool) {
for(uint i =0; i <60; i++) if (fibs64()[i] == n) returntrue;
returnfalse;
}
/**
@dev Next 38 Fibonacci numbers, which fit into uint128
*/functionfibs128() internalpurereturns (uint128[39] memory) {
return [
uint128(1548008755920),2504730781961, 4052739537881,
6557470319842, 10610209857723, 17167680177565,
27777890035288, 44945570212853, 72723460248141,
117669030460994, 190392490709135, 308061521170129,
498454011879264, 806515533049393, 1304969544928657,
2111485077978050, 3416454622906707, 5527939700884757,
8944394323791464, 14472334024676221, 23416728348467685,
37889062373143906, 61305790721611591, 99194853094755497,
160500643816367088, 259695496911122585, 420196140727489673,
679891637638612258, 1100087778366101931, 1779979416004714189,
2880067194370816120, 4660046610375530309, 7540113804746346429,
12200160415121876738, 19740274219868223167, 31940434634990099905,
51680708854858323072, 83621143489848422977, 135301852344706746049
];
}
/**
@dev Tests if number is a fib via a linear lookup in the table above
*/functionisFibs128(uint256 n) internalpurereturns (bool) {
for(uint i =0; i <39; i++) if (fibs128()[i] == n) returntrue;
returnfalse;
}
/**
@dev Helper for Miller-Rabin probabilistic primality test
*/// Write (n - 1) as 2^s * dfunctiongetValues(uint256 n) internalpurereturns (uint256[2] memory) {
uint256 s =0;
uint256 d = n -1;
while (d %2==0) {
d = d /2;
s++;
}
uint256[2] memory ret;
ret[0] = s;
ret[1] = d;
return ret;
}
/**
@dev Wrapper around EVM precompiled function for modular exponentiation, deployed at 0x05 address
*/functionmodExp(uint256 base, uint256 e, uint256 m) internalviewreturns (uint o) {
assembly {
// define pointerlet p :=mload(0x40)
// store data assembly-favouring waysmstore(p, 0x20) // Length of Basemstore(add(p, 0x20), 0x20) // Length of Exponentmstore(add(p, 0x40), 0x20) // Length of Modulusmstore(add(p, 0x60), base) // Basemstore(add(p, 0x80), e) // Exponentmstore(add(p, 0xa0), m) // Modulusifiszero(staticcall(sub(gas(), 2000), 0x05, p, 0xc0, p, 0x20)) {
revert(0, 0)
}
// data
o :=mload(p)
}
}
/**
@dev Miller-Rabin test probabilistic primality test
see https://en.wikipedia.org/wiki/Miller–Rabin_primality_test
*/functionprobablyPrime(uint256 n, uint256 prime) internalviewreturns (bool) {
if (n ==2|| n ==3) {
returntrue;
}
if (n %2==0|| n <2) {
returnfalse;
}
uint256[2] memory values = getValues(n);
uint256 s = values[0];
uint256 d = values[1];
uint256 x = modExp(prime, d, n);
if (x ==1|| x == n -1) {
returntrue;
}
for (uint256 i = s -1; i >0; i--) {
x = modExp(x, 2, n);
if (x ==1) {
returnfalse;
}
if (x == n -1) {
returntrue;
}
}
returnfalse;
}
/**
@dev Determines if a number is prime, using Miller-Rabin test probabilistic primality test
plus deterministic checking to sift out pseudo-primes
see https://en.wikipedia.org/wiki/Miller–Rabin_primality_test
*/functionisPrime(uint256 n) publicviewreturns (bool) {
if (n <2_047)
return probablyPrime(n, 2);
elseif (n <1_373_653)
return probablyPrime(n, 2) && probablyPrime(n, 3);
elseif (n <9_080_191)
return probablyPrime(n, 31) && probablyPrime(n, 73);
elseif (n <25_326_001)
return probablyPrime(n, 2) && probablyPrime(n, 3)
&& probablyPrime(n, 5);
elseif (n <3_215_031_751)
return probablyPrime(n, 2) && probablyPrime(n, 3)
&& probablyPrime(n, 5) && probablyPrime(n, 7);
elseif (n <4_759_123_141)
return probablyPrime(n, 2) && probablyPrime(n, 7)
&& probablyPrime(n, 61);
elseif (n <1_122_004_669_633)
return probablyPrime(n, 2) && probablyPrime(n, 13)
&& probablyPrime(n, 23) && probablyPrime(n, 1662803);
elseif (n <2_152_302_898_747)
return probablyPrime(n, 2) && probablyPrime(n, 3)
&& probablyPrime(n, 5) && probablyPrime(n, 7)
&& probablyPrime(n, 11);
elseif (n <3_474_749_660_383)
return probablyPrime(n, 2) && probablyPrime(n, 3)
&& probablyPrime(n, 5) && probablyPrime(n, 7)
&& probablyPrime(n, 11) && probablyPrime(n, 13);
elseif (n <341_550_071_728_321)
return probablyPrime(n, 2) && probablyPrime(n, 3)
&& probablyPrime(n, 5) && probablyPrime(n, 7)
&& probablyPrime(n, 11) && probablyPrime(n, 13)
&& probablyPrime(n, 17);
returnfalse;
// TODO: consider reverting ???// revert('number too big');
}
/**
@dev Count prime numbers occurring between `from` and `to` numbers
*/functionfindPrimes(uint256from, uint256 to) externalviewreturns (uint256 count) {
require(to >0, "findPrimes: to should be natural");
require(to >from, "findPrimes: to should be larger than from");
count =0;
for(uint i =from; i < to; i++) {
if (isPrime(i)) count++;
}
}
/**
@dev Helper to get N-th Fibonacci number (0 returns 0)
*/functiongetFib(uint256 n) internalpurereturns (uint256 a) {
if (n ==0) {
return0;
}
uint256 h = n /2;
uint256 mask =1;
// find highest set bit in nwhile(mask <= h) {
mask <<=1;
}
mask >>=1;
a =1;
uint256 b =1;
uint256 c;
while(mask >0) {
c = a * a+b * b;
if (n & mask >0) {
b = b * (b +2* a);
a = c;
} else {
a = a * (2* b - a);
b = c;
}
mask >>=1;
}
return a;
}
/**
@dev Helper to check if a number is a perfect square
*/functionisPerfectSquare(uint256 n) internalpurereturns (bool) {
uint256 low =0;
uint256 high = n;
while (low <= high) {
uint mid = (low + high) /2;
uint square = mid * mid;
if (square == n) {
returntrue;
} elseif (square > n) {
high = mid -1;
} else {
low = mid +1;
}
}
returnfalse;
}
/**
@dev Test if the number is a fib
note the upper limit of 2 ** 62 - 1, to avoid overflow while preforming tests
*/functionisFib(uint256 n) publicpurereturns (bool) {
if (n ==0) returnfalse;
require(n < MAX_SUPPORTED_FIB_CANDIDATE, 'isFib: number too big');
uint256 base = n * n *5;
uint256 p1 = base +4;
uint256 p2 = base -4;
return (isPerfectSquare(p1) || isPerfectSquare(p2));
}
}
Contract Source Code
File 30 of 37: Math.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.10;import"abdk-libraries-solidity/ABDKMath64x64.sol";
libraryMath{
functionmin(uint256 a, uint256 b) externalpurereturns (uint256) {
if (a > b) return b;
return a;
}
functionmax(uint256 a, uint256 b) externalpurereturns (uint256) {
if (a > b) return a;
return b;
}
functionlogX64(uint256 x) externalpurereturns (int128) {
return ABDKMath64x64.log_2(ABDKMath64x64.fromUInt(x));
}
}
Contract Source Code
File 31 of 37: OperatorFilterer.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.13;import {IOperatorFilterRegistry} from"./IOperatorFilterRegistry.sol";
/**
* @title OperatorFilterer
* @notice Abstract contract whose constructor automatically registers and optionally subscribes to or copies another
* registrant's entries in the OperatorFilterRegistry.
* @dev This smart contract is meant to be inherited by token contracts so they can use the following:
* - `onlyAllowedOperator` modifier for `transferFrom` and `safeTransferFrom` methods.
* - `onlyAllowedOperatorApproval` modifier for `approve` and `setApprovalForAll` methods.
*/abstractcontractOperatorFilterer{
errorOperatorNotAllowed(address operator);
IOperatorFilterRegistry publicconstant OPERATOR_FILTER_REGISTRY =
IOperatorFilterRegistry(0x000000000000AAeB6D7670E522A718067333cd4E);
constructor(address subscriptionOrRegistrantToCopy, bool subscribe) {
// If an inheriting token contract is deployed to a network without the registry deployed, the modifier// will not revert, but the contract will need to be registered with the registry once it is deployed in// order for the modifier to filter addresses.if (address(OPERATOR_FILTER_REGISTRY).code.length>0) {
if (subscribe) {
OPERATOR_FILTER_REGISTRY.registerAndSubscribe(address(this), subscriptionOrRegistrantToCopy);
} else {
if (subscriptionOrRegistrantToCopy !=address(0)) {
OPERATOR_FILTER_REGISTRY.registerAndCopyEntries(address(this), subscriptionOrRegistrantToCopy);
} else {
OPERATOR_FILTER_REGISTRY.register(address(this));
}
}
}
}
modifieronlyAllowedOperator(addressfrom) virtual{
// Allow spending tokens from addresses with balance// Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred// from an EOA.if (from!=msg.sender) {
_checkFilterOperator(msg.sender);
}
_;
}
modifieronlyAllowedOperatorApproval(address operator) virtual{
_checkFilterOperator(operator);
_;
}
function_checkFilterOperator(address operator) internalviewvirtual{
// Check registry code length to facilitate testing in environments without a deployed registry.if (address(OPERATOR_FILTER_REGISTRY).code.length>0) {
if (!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(address(this), operator)) {
revert OperatorNotAllowed(operator);
}
}
}
}
Contract Source Code
File 32 of 37: StakeInfo.sol
Contract Source Code
File 33 of 37: StakeMetadata.sol
Contract Source Code
File 34 of 37: StakeSVG.sol
Contract Source Code
File 35 of 37: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)pragmasolidity ^0.8.0;/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _HEX_SYMBOLS ="0123456789abcdef";
uint8privateconstant _ADDRESS_LENGTH =20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
// Inspired by OraclizeAPI's implementation - MIT licence// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.solif (value ==0) {
return"0";
}
uint256 temp = value;
uint256 digits;
while (temp !=0) {
digits++;
temp /=10;
}
bytesmemory buffer =newbytes(digits);
while (value !=0) {
digits -=1;
buffer[digits] =bytes1(uint8(48+uint256(value %10)));
value /=10;
}
returnstring(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
if (value ==0) {
return"0x00";
}
uint256 temp = value;
uint256 length =0;
while (temp !=0) {
length++;
temp >>=8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = _HEX_SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
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);
}
}
Contract Source Code
File 36 of 37: XENCrypto.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.10;import"./Math.sol";
import"@openzeppelin/contracts/token/ERC20/ERC20.sol";
import"@openzeppelin/contracts/interfaces/IERC165.sol";
import"abdk-libraries-solidity/ABDKMath64x64.sol";
import"./interfaces/IStakingToken.sol";
import"./interfaces/IRankedMintingToken.sol";
import"./interfaces/IBurnableToken.sol";
import"./interfaces/IBurnRedeemable.sol";
contractXENCryptoisContext, IRankedMintingToken, IStakingToken, IBurnableToken, ERC20("XEN Crypto", "XEN") {
usingMathforuint256;
usingABDKMath64x64forint128;
usingABDKMath64x64foruint256;
// INTERNAL TYPE TO DESCRIBE A XEN MINT INFOstructMintInfo {
address user;
uint256 term;
uint256 maturityTs;
uint256 rank;
uint256 amplifier;
uint256 eaaRate;
}
// INTERNAL TYPE TO DESCRIBE A XEN STAKEstructStakeInfo {
uint256 term;
uint256 maturityTs;
uint256 amount;
uint256 apy;
}
// PUBLIC CONSTANTSuint256publicconstant SECONDS_IN_DAY =3_600*24;
uint256publicconstant DAYS_IN_YEAR =365;
uint256publicconstant GENESIS_RANK =1;
uint256publicconstant MIN_TERM =1* SECONDS_IN_DAY -1;
uint256publicconstant MAX_TERM_START =100* SECONDS_IN_DAY;
uint256publicconstant MAX_TERM_END =1_000* SECONDS_IN_DAY;
uint256publicconstant TERM_AMPLIFIER =15;
uint256publicconstant TERM_AMPLIFIER_THRESHOLD =5_000;
uint256publicconstant REWARD_AMPLIFIER_START =3_000;
uint256publicconstant REWARD_AMPLIFIER_END =1;
uint256publicconstant EAA_PM_START =100;
uint256publicconstant EAA_PM_STEP =1;
uint256publicconstant EAA_RANK_STEP =100_000;
uint256publicconstant WITHDRAWAL_WINDOW_DAYS =7;
uint256publicconstant MAX_PENALTY_PCT =99;
uint256publicconstant XEN_MIN_STAKE =0;
uint256publicconstant XEN_MIN_BURN =0;
uint256publicconstant XEN_APY_START =20;
uint256publicconstant XEN_APY_DAYS_STEP =90;
uint256publicconstant XEN_APY_END =2;
stringpublicconstant AUTHORS ="@MrJackLevin @lbelyaev faircrypto.org";
// PUBLIC STATE, READABLE VIA NAMESAKE GETTERSuint256publicimmutable genesisTs;
uint256public globalRank = GENESIS_RANK;
uint256public activeMinters;
uint256public activeStakes;
uint256public totalXenStaked;
// user address => XEN mint infomapping(address=> MintInfo) public userMints;
// user address => XEN stake infomapping(address=> StakeInfo) public userStakes;
// user address => XEN burn amountmapping(address=>uint256) public userBurns;
// CONSTRUCTORconstructor() {
genesisTs =block.timestamp;
}
// PRIVATE METHODS/**
* @dev calculates current MaxTerm based on Global Rank
* (if Global Rank crosses over TERM_AMPLIFIER_THRESHOLD)
*/function_calculateMaxTerm() privateviewreturns (uint256) {
if (globalRank > TERM_AMPLIFIER_THRESHOLD) {
uint256 delta = globalRank.fromUInt().log_2().mul(TERM_AMPLIFIER.fromUInt()).toUInt();
uint256 newMax = MAX_TERM_START + delta * SECONDS_IN_DAY;
return Math.min(newMax, MAX_TERM_END);
}
return MAX_TERM_START;
}
/**
* @dev calculates Withdrawal Penalty depending on lateness
*/function_penalty(uint256 secsLate) privatepurereturns (uint256) {
// =MIN(2^(daysLate+3)/window-1,99)uint256 daysLate = secsLate / SECONDS_IN_DAY;
if (daysLate > WITHDRAWAL_WINDOW_DAYS -1) return MAX_PENALTY_PCT;
uint256 penalty = (uint256(1) << (daysLate +3)) / WITHDRAWAL_WINDOW_DAYS -1;
return Math.min(penalty, MAX_PENALTY_PCT);
}
/**
* @dev calculates net Mint Reward (adjusted for Penalty)
*/function_calculateMintReward(uint256 cRank,
uint256 term,
uint256 maturityTs,
uint256 amplifier,
uint256 eeaRate
) privateviewreturns (uint256) {
uint256 secsLate =block.timestamp- maturityTs;
uint256 penalty = _penalty(secsLate);
uint256 rankDelta = Math.max(globalRank - cRank, 2);
uint256 EAA = (1_000+ eeaRate);
uint256 reward = getGrossReward(rankDelta, amplifier, term, EAA);
return (reward * (100- penalty)) /100;
}
/**
* @dev cleans up User Mint storage (gets some Gas credit;))
*/function_cleanUpUserMint() private{
delete userMints[_msgSender()];
activeMinters--;
}
/**
* @dev calculates XEN Stake Reward
*/function_calculateStakeReward(uint256 amount,
uint256 term,
uint256 maturityTs,
uint256 apy
) privateviewreturns (uint256) {
if (block.timestamp> maturityTs) {
uint256 rate = (apy * term *1_000_000) / DAYS_IN_YEAR;
return (amount * rate) /100_000_000;
}
return0;
}
/**
* @dev calculates Reward Amplifier
*/function_calculateRewardAmplifier() privateviewreturns (uint256) {
uint256 amplifierDecrease = (block.timestamp- genesisTs) / SECONDS_IN_DAY;
if (amplifierDecrease < REWARD_AMPLIFIER_START) {
return Math.max(REWARD_AMPLIFIER_START - amplifierDecrease, REWARD_AMPLIFIER_END);
} else {
return REWARD_AMPLIFIER_END;
}
}
/**
* @dev calculates Early Adopter Amplifier Rate (in 1/000ths)
* actual EAA is (1_000 + EAAR) / 1_000
*/function_calculateEAARate() privateviewreturns (uint256) {
uint256 decrease = (EAA_PM_STEP * globalRank) / EAA_RANK_STEP;
if (decrease > EAA_PM_START) return0;
return EAA_PM_START - decrease;
}
/**
* @dev calculates APY (in %)
*/function_calculateAPY() privateviewreturns (uint256) {
uint256 decrease = (block.timestamp- genesisTs) / (SECONDS_IN_DAY * XEN_APY_DAYS_STEP);
if (XEN_APY_START - XEN_APY_END < decrease) return XEN_APY_END;
return XEN_APY_START - decrease;
}
/**
* @dev creates User Stake
*/function_createStake(uint256 amount, uint256 term) private{
userStakes[_msgSender()] = StakeInfo({
term: term,
maturityTs: block.timestamp+ term * SECONDS_IN_DAY,
amount: amount,
apy: _calculateAPY()
});
activeStakes++;
totalXenStaked += amount;
}
// PUBLIC CONVENIENCE GETTERS/**
* @dev calculates gross Mint Reward
*/functiongetGrossReward(uint256 rankDelta,
uint256 amplifier,
uint256 term,
uint256 eaa
) publicpurereturns (uint256) {
int128 log128 = rankDelta.fromUInt().log_2();
int128 reward128 = log128.mul(amplifier.fromUInt()).mul(term.fromUInt()).mul(eaa.fromUInt());
return reward128.div(uint256(1_000).fromUInt()).toUInt();
}
/**
* @dev returns User Mint object associated with User account address
*/functiongetUserMint() externalviewreturns (MintInfo memory) {
return userMints[_msgSender()];
}
/**
* @dev returns XEN Stake object associated with User account address
*/functiongetUserStake() externalviewreturns (StakeInfo memory) {
return userStakes[_msgSender()];
}
/**
* @dev returns current AMP
*/functiongetCurrentAMP() externalviewreturns (uint256) {
return _calculateRewardAmplifier();
}
/**
* @dev returns current EAA Rate
*/functiongetCurrentEAAR() externalviewreturns (uint256) {
return _calculateEAARate();
}
/**
* @dev returns current APY
*/functiongetCurrentAPY() externalviewreturns (uint256) {
return _calculateAPY();
}
/**
* @dev returns current MaxTerm
*/functiongetCurrentMaxTerm() externalviewreturns (uint256) {
return _calculateMaxTerm();
}
// PUBLIC STATE-CHANGING METHODS/**
* @dev accepts User cRank claim provided all checks pass (incl. no current claim exists)
*/functionclaimRank(uint256 term) external{
uint256 termSec = term * SECONDS_IN_DAY;
require(termSec > MIN_TERM, "CRank: Term less than min");
require(termSec < _calculateMaxTerm() +1, "CRank: Term more than current max term");
require(userMints[_msgSender()].rank ==0, "CRank: Mint already in progress");
// create and store new MintInfo
MintInfo memory mintInfo = MintInfo({
user: _msgSender(),
term: term,
maturityTs: block.timestamp+ termSec,
rank: globalRank,
amplifier: _calculateRewardAmplifier(),
eaaRate: _calculateEAARate()
});
userMints[_msgSender()] = mintInfo;
activeMinters++;
emit RankClaimed(_msgSender(), term, globalRank++);
}
/**
* @dev ends minting upon maturity (and within permitted Withdrawal Time Window), gets minted XEN
*/functionclaimMintReward() external{
MintInfo memory mintInfo = userMints[_msgSender()];
require(mintInfo.rank >0, "CRank: No mint exists");
require(block.timestamp> mintInfo.maturityTs, "CRank: Mint maturity not reached");
// calculate reward and mint tokensuint256 rewardAmount = _calculateMintReward(
mintInfo.rank,
mintInfo.term,
mintInfo.maturityTs,
mintInfo.amplifier,
mintInfo.eaaRate
) *1ether;
_mint(_msgSender(), rewardAmount);
_cleanUpUserMint();
emit MintClaimed(_msgSender(), rewardAmount);
}
/**
* @dev ends minting upon maturity (and within permitted Withdrawal time Window)
* mints XEN coins and splits them between User and designated other address
*/functionclaimMintRewardAndShare(address other, uint256 pct) external{
MintInfo memory mintInfo = userMints[_msgSender()];
require(other !=address(0), "CRank: Cannot share with zero address");
require(pct >0, "CRank: Cannot share zero percent");
require(pct <101, "CRank: Cannot share 100+ percent");
require(mintInfo.rank >0, "CRank: No mint exists");
require(block.timestamp> mintInfo.maturityTs, "CRank: Mint maturity not reached");
// calculate rewarduint256 rewardAmount = _calculateMintReward(
mintInfo.rank,
mintInfo.term,
mintInfo.maturityTs,
mintInfo.amplifier,
mintInfo.eaaRate
) *1ether;
uint256 sharedReward = (rewardAmount * pct) /100;
uint256 ownReward = rewardAmount - sharedReward;
// mint reward tokens
_mint(_msgSender(), ownReward);
_mint(other, sharedReward);
_cleanUpUserMint();
emit MintClaimed(_msgSender(), rewardAmount);
}
/**
* @dev ends minting upon maturity (and within permitted Withdrawal time Window)
* mints XEN coins and stakes 'pct' of it for 'term'
*/functionclaimMintRewardAndStake(uint256 pct, uint256 term) external{
MintInfo memory mintInfo = userMints[_msgSender()];
// require(pct > 0, "CRank: Cannot share zero percent");require(pct <101, "CRank: Cannot share >100 percent");
require(mintInfo.rank >0, "CRank: No mint exists");
require(block.timestamp> mintInfo.maturityTs, "CRank: Mint maturity not reached");
// calculate rewarduint256 rewardAmount = _calculateMintReward(
mintInfo.rank,
mintInfo.term,
mintInfo.maturityTs,
mintInfo.amplifier,
mintInfo.eaaRate
) *1ether;
uint256 stakedReward = (rewardAmount * pct) /100;
uint256 ownReward = rewardAmount - stakedReward;
// mint reward tokens part
_mint(_msgSender(), ownReward);
_cleanUpUserMint();
emit MintClaimed(_msgSender(), rewardAmount);
// nothing to burn since we haven't minted this part yet// stake extra tokens partrequire(stakedReward > XEN_MIN_STAKE, "XEN: Below min stake");
require(term * SECONDS_IN_DAY > MIN_TERM, "XEN: Below min stake term");
require(term * SECONDS_IN_DAY < MAX_TERM_END +1, "XEN: Above max stake term");
require(userStakes[_msgSender()].amount ==0, "XEN: stake exists");
_createStake(stakedReward, term);
emit Staked(_msgSender(), stakedReward, term);
}
/**
* @dev initiates XEN Stake in amount for a term (days)
*/functionstake(uint256 amount, uint256 term) external{
require(balanceOf(_msgSender()) >= amount, "XEN: not enough balance");
require(amount > XEN_MIN_STAKE, "XEN: Below min stake");
require(term * SECONDS_IN_DAY > MIN_TERM, "XEN: Below min stake term");
require(term * SECONDS_IN_DAY < MAX_TERM_END +1, "XEN: Above max stake term");
require(userStakes[_msgSender()].amount ==0, "XEN: stake exists");
// burn staked XEN
_burn(_msgSender(), amount);
// create XEN Stake
_createStake(amount, term);
emit Staked(_msgSender(), amount, term);
}
/**
* @dev ends XEN Stake and gets reward if the Stake is mature
*/functionwithdraw() external{
StakeInfo memory userStake = userStakes[_msgSender()];
require(userStake.amount >0, "XEN: no stake exists");
uint256 xenReward = _calculateStakeReward(
userStake.amount,
userStake.term,
userStake.maturityTs,
userStake.apy
);
activeStakes--;
totalXenStaked -= userStake.amount;
// mint staked XEN (+ reward)
_mint(_msgSender(), userStake.amount + xenReward);
emit Withdrawn(_msgSender(), userStake.amount, xenReward);
delete userStakes[_msgSender()];
}
/**
* @dev burns XEN tokens and creates Proof-Of-Burn record to be used by connected DeFi services
*/functionburn(address user, uint256 amount) public{
require(amount > XEN_MIN_BURN, "Burn: Below min limit");
require(
IERC165(_msgSender()).supportsInterface(type(IBurnRedeemable).interfaceId),
"Burn: not a supported contract"
);
_spendAllowance(user, _msgSender(), amount);
_burn(user, amount);
userBurns[user] += amount;
IBurnRedeemable(_msgSender()).onTokenBurned(user, amount);
}
}