// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)pragmasolidity ^0.8.0;import"./IAccessControl.sol";
import"../utils/Context.sol";
import"../utils/Strings.sol";
import"../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/abstractcontractAccessControlisContext, IAccessControl, ERC165{
structRoleData {
mapping(address=>bool) members;
bytes32 adminRole;
}
mapping(bytes32=> RoleData) private _roles;
bytes32publicconstant DEFAULT_ADMIN_ROLE =0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/modifieronlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IAccessControl).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/functionhasRole(bytes32 role, address account) publicviewvirtualoverridereturns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/function_checkRole(bytes32 role) internalviewvirtual{
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/function_checkRole(bytes32 role, address account) internalviewvirtual{
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/functiongetRoleAdmin(bytes32 role) publicviewvirtualoverridereturns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/functiongrantRole(bytes32 role, address account) publicvirtualoverrideonlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/functionrevokeRole(bytes32 role, address account) publicvirtualoverrideonlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/functionrenounceRole(bytes32 role, address account) publicvirtualoverride{
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/function_setupRole(bytes32 role, address account) internalvirtual{
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/function_setRoleAdmin(bytes32 role, bytes32 adminRole) internalvirtual{
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/function_grantRole(bytes32 role, address account) internalvirtual{
if (!hasRole(role, account)) {
_roles[role].members[account] =true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/function_revokeRole(bytes32 role, address account) internalvirtual{
if (hasRole(role, account)) {
_roles[role].members[account] =false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
Contract Source Code
File 2 of 35: Address.sol
// 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 35: Common.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;enumItemType {
Empty, // 0
Mainhand, // 1
Offhand, // 2
Pet // 3
}
/// 288 bytesstructItem {
uint256 itemId;
uint8 powerLevel;
ItemType itemType;
}
/// ownerId is the tokenId of the nft that the item is being equipped to, this/// nft essentially "owns" the item while it's held in the MagicFolk contractfunctionencodeOwnerIdAndItem(uint256 ownerId,
Item memory item
) purereturns (bytesmemory) {
// bytes memory _ownerId = abi.encodePacked(ownerId);// bytes memory _item = abi.encode(item);// return bytes.concat(_ownerId, _item);returnabi.encode(ownerId, item);
}
functiondecodeOwnerIdAndItem(bytescalldata _data
) purereturns (uint256, Item memory) {
uint256 ownerId =abi.decode(_data[:32], (uint256));
// Item memory item = abi.decode(_data[32:], (Item)); // Life is pain...
Item memory item;
item.itemId =abi.decode(_data[32:64], (uint256));
item.powerLevel =abi.decode(_data[64:96], (uint8));
item.itemType =abi.decode(_data[96:], (ItemType));
return (ownerId, item);
}
contractCommonConstants{
bytes4constantinternal ERC1155_RECEIVED_VALUE =0xf23a6e61;
bytes4constantinternal ERC1155_BATCH_RECEIVED_VALUE =0xbc197c81;
}
Contract Source Code
File 4 of 35: 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 5 of 35: Counters.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)pragmasolidity ^0.8.0;/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/libraryCounters{
structCounter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add// this feature: see https://github.com/ethereum/solidity/issues/4637uint256 _value; // default: 0
}
functioncurrent(Counter storage counter) internalviewreturns (uint256) {
return counter._value;
}
functionincrement(Counter storage counter) internal{
unchecked {
counter._value +=1;
}
}
functiondecrement(Counter storage counter) internal{
uint256 value = counter._value;
require(value >0, "Counter: decrement overflow");
unchecked {
counter._value = value -1;
}
}
functionreset(Counter storage counter) internal{
counter._value =0;
}
}
Contract Source Code
File 6 of 35: ECDSA.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/ECDSA.sol)pragmasolidity ^0.8.0;import"../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/libraryECDSA{
enumRecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function_throwError(RecoverError error) privatepure{
if (error == RecoverError.NoError) {
return; // no error: do nothing
} elseif (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} elseif (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} elseif (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} elseif (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash, bytesmemory signature) internalpurereturns (address, RecoverError) {
// Check the signature length// - case 65: r,s,v signature (standard)// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._if (signature.length==65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them// currently is to use assembly./// @solidity memory-safe-assemblyassembly {
r :=mload(add(signature, 0x20))
s :=mload(add(signature, 0x40))
v :=byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} elseif (signature.length==64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them// currently is to use assembly./// @solidity memory-safe-assemblyassembly {
r :=mload(add(signature, 0x20))
vs :=mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/functionrecover(bytes32 hash, bytesmemory signature) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash,
bytes32 r,
bytes32 vs
) internalpurereturns (address, RecoverError) {
bytes32 s = vs &bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v =uint8((uint256(vs) >>255) +27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/functionrecover(bytes32 hash,
bytes32 r,
bytes32 vs
) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/functiontryRecover(bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internalpurereturns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most// signatures from current libraries generate a unique signature with an s-value in the lower half order.//// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept// these malleable signatures as well.if (uint256(s) >0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v !=27&& v !=28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer addressaddress signer =ecrecover(hash, v, r, s);
if (signer ==address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/functionrecover(bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internalpurereturns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/functiontoEthSignedMessageHash(bytes32 hash) internalpurereturns (bytes32) {
// 32 is the length in bytes of hash,// enforced by the type signature abovereturnkeccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/functiontoEthSignedMessageHash(bytesmemory s) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/functiontoTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internalpurereturns (bytes32) {
returnkeccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
Contract Source Code
File 7 of 35: ERC1155.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/ERC1155.sol)pragmasolidity ^0.8.0;import"./IERC1155.sol";
import"./IERC1155Receiver.sol";
import"./extensions/IERC1155MetadataURI.sol";
import"../../utils/Address.sol";
import"../../utils/Context.sol";
import"../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/contractERC1155isContext, ERC165, IERC1155, IERC1155MetadataURI{
usingAddressforaddress;
// Mapping from token ID to account balancesmapping(uint256=>mapping(address=>uint256)) private _balances;
// Mapping from account to operator approvalsmapping(address=>mapping(address=>bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.jsonstringprivate _uri;
/**
* @dev See {_setURI}.
*/constructor(stringmemory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return
interfaceId ==type(IERC1155).interfaceId||
interfaceId ==type(IERC1155MetadataURI).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/functionuri(uint256) publicviewvirtualoverridereturns (stringmemory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/functionbalanceOf(address account, uint256 id) publicviewvirtualoverridereturns (uint256) {
require(account !=address(0), "ERC1155: address zero is not a valid owner");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/functionbalanceOfBatch(address[] memory accounts, uint256[] memory ids)
publicviewvirtualoverridereturns (uint256[] memory)
{
require(accounts.length== ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances =newuint256[](accounts.length);
for (uint256 i =0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicvirtualoverride{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/functionisApprovedForAll(address account, address operator) publicviewvirtualoverridereturns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 id,
uint256 amount,
bytesmemory data
) publicvirtualoverride{
require(
from== _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not token owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/functionsafeBatchTransferFrom(addressfrom,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytesmemory data
) publicvirtualoverride{
require(
from== _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not token owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/function_safeTransferFrom(addressfrom,
address to,
uint256 id,
uint256 amount,
bytesmemory data
) internalvirtual{
require(to !=address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/function_safeBatchTransferFrom(addressfrom,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytesmemory data
) internalvirtual{
require(ids.length== amounts.length, "ERC1155: ids and amounts length mismatch");
require(to !=address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i =0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/function_setURI(stringmemory newuri) internalvirtual{
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/function_mint(address to,
uint256 id,
uint256 amount,
bytesmemory data
) internalvirtual{
require(to !=address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/function_mintBatch(address to,
uint256[] memory ids,
uint256[] memory amounts,
bytesmemory data
) internalvirtual{
require(to !=address(0), "ERC1155: mint to the zero address");
require(ids.length== amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i =0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/function_burn(addressfrom,
uint256 id,
uint256 amount
) internalvirtual{
require(from!=address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/function_burnBatch(addressfrom,
uint256[] memory ids,
uint256[] memory amounts
) internalvirtual{
require(from!=address(0), "ERC1155: burn from the zero address");
require(ids.length== amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i =0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @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, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `ids` and `amounts` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(address operator,
addressfrom,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytesmemory data
) internalvirtual{}
/**
* @dev Hook that is called after any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_afterTokenTransfer(address operator,
addressfrom,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytesmemory data
) internalvirtual{}
function_doSafeTransferAcceptanceCheck(address operator,
addressfrom,
address to,
uint256 id,
uint256 amount,
bytesmemory data
) private{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catchError(stringmemory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function_doSafeBatchTransferAcceptanceCheck(address operator,
addressfrom,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytesmemory data
) private{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catchError(stringmemory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function_asSingletonArray(uint256 element) privatepurereturns (uint256[] memory) {
uint256[] memory array =newuint256[](1);
array[0] = element;
return array;
}
}
Contract Source Code
File 8 of 35: ERC1155Holder.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)pragmasolidity ^0.8.0;import"./ERC1155Receiver.sol";
/**
* Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
*
* IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
* stuck.
*
* @dev _Available since v3.1._
*/contractERC1155HolderisERC1155Receiver{
functiononERC1155Received(address,
address,
uint256,
uint256,
bytesmemory) publicvirtualoverridereturns (bytes4) {
returnthis.onERC1155Received.selector;
}
functiononERC1155BatchReceived(address,
address,
uint256[] memory,
uint256[] memory,
bytesmemory) publicvirtualoverridereturns (bytes4) {
returnthis.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol)pragmasolidity ^0.8.0;import"../ERC1155.sol";
/**
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*/abstractcontractERC1155SupplyisERC1155{
mapping(uint256=>uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/functiontotalSupply(uint256 id) publicviewvirtualreturns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates whether any token exist with a given id, or not.
*/functionexists(uint256 id) publicviewvirtualreturns (bool) {
return ERC1155Supply.totalSupply(id) >0;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/function_beforeTokenTransfer(address operator,
addressfrom,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytesmemory data
) internalvirtualoverride{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from==address(0)) {
for (uint256 i =0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
if (to ==address(0)) {
for (uint256 i =0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 supply = _totalSupply[id];
require(supply >= amount, "ERC1155: burn amount exceeds totalSupply");
unchecked {
_totalSupply[id] = supply - amount;
}
}
}
}
}
Contract Source Code
File 11 of 35: 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 12 of 35: 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 13 of 35: 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{}
}
Contract Source Code
File 14 of 35: ERC721Enumerable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)pragmasolidity ^0.8.0;import"../ERC721.sol";
import"./IERC721Enumerable.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.
*/abstractcontractERC721EnumerableisERC721, IERC721Enumerable{
// Mapping from owner to list of owned token IDsmapping(address=>mapping(uint256=>uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens listmapping(uint256=>uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumerationuint256[] private _allTokens;
// Mapping from token id to position in the allTokens arraymapping(uint256=>uint256) private _allTokensIndex;
/**
* @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) publicviewvirtualoverridereturns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/functiontokenByIndex(uint256 index) publicviewvirtualoverridereturns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @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` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom,
address to,
uint256 tokenId
) internalvirtualoverride{
super._beforeTokenTransfer(from, to, tokenId);
if (from==address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} elseif (from!= to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to ==address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} elseif (to !=from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @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 = ERC721.balanceOf(to);
_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 = ERC721.balanceOf(from) -1;
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();
}
}
Contract Source Code
File 15 of 35: ERC721Holder.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)pragmasolidity ^0.8.0;import"../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/contractERC721HolderisIERC721Receiver{
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/functiononERC721Received(address,
address,
uint256,
bytesmemory) publicvirtualoverridereturns (bytes4) {
returnthis.onERC721Received.selector;
}
}
Contract Source Code
File 16 of 35: IAccessControl.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)pragmasolidity ^0.8.0;/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/interfaceIAccessControl{
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/eventRoleAdminChanged(bytes32indexed role, bytes32indexed previousAdminRole, bytes32indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/eventRoleGranted(bytes32indexed role, addressindexed account, addressindexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/eventRoleRevoked(bytes32indexed role, addressindexed account, addressindexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/functionhasRole(bytes32 role, address account) externalviewreturns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/functiongetRoleAdmin(bytes32 role) externalviewreturns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/functiongrantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/functionrevokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/functionrenounceRole(bytes32 role, address account) external;
}
Contract Source Code
File 17 of 35: IERC1155.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC1155/IERC1155.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/interfaceIERC1155isIERC165{
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/eventTransferSingle(addressindexed operator, addressindexedfrom, addressindexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/eventTransferBatch(addressindexed operator,
addressindexedfrom,
addressindexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/eventApprovalForAll(addressindexed account, addressindexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/eventURI(string value, uint256indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/functionbalanceOf(address account, uint256 id) externalviewreturns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/functionbalanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
externalviewreturns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/functionsetApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/functionisApprovedForAll(address account, address operator) externalviewreturns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 id,
uint256 amount,
bytescalldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/functionsafeBatchTransferFrom(addressfrom,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytescalldata data
) external;
}
Contract Source Code
File 18 of 35: IERC1155MetadataURI.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)pragmasolidity ^0.8.0;import"../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/interfaceIERC1155MetadataURIisIERC1155{
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/functionuri(uint256 id) externalviewreturns (stringmemory);
}
Contract Source Code
File 19 of 35: IERC1155Receiver.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/interfaceIERC1155ReceiverisIERC165{
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/functiononERC1155Received(address operator,
addressfrom,
uint256 id,
uint256 value,
bytescalldata data
) externalreturns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/functiononERC1155BatchReceived(address operator,
addressfrom,
uint256[] calldata ids,
uint256[] calldata values,
bytescalldata data
) externalreturns (bytes4);
}
Contract Source Code
File 20 of 35: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^0.8.0;/**
* @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 21 of 35: IERC20.sol
// 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 22 of 35: 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);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)pragmasolidity ^0.8.0;import"../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 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);
}
Contract Source Code
File 27 of 35: IGovernor.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (governance/IGovernor.sol)pragmasolidity ^0.8.0;import"../utils/introspection/ERC165.sol";
/**
* @dev Interface of the {Governor} core.
*
* _Available since v4.3._
*/abstractcontractIGovernorisIERC165{
enumProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/**
* @dev Emitted when a proposal is created.
*/eventProposalCreated(uint256 proposalId,
address proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/**
* @dev Emitted when a proposal is canceled.
*/eventProposalCanceled(uint256 proposalId);
/**
* @dev Emitted when a proposal is executed.
*/eventProposalExecuted(uint256 proposalId);
/**
* @dev Emitted when a vote is cast without params.
*
* Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.
*/eventVoteCast(addressindexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason);
/**
* @dev Emitted when a vote is cast with params.
*
* Note: `support` values should be seen as buckets. Their interpretation depends on the voting module used.
* `params` are additional encoded parameters. Their intepepretation also depends on the voting module used.
*/eventVoteCastWithParams(addressindexed voter,
uint256 proposalId,
uint8 support,
uint256 weight,
string reason,
bytes params
);
/**
* @notice module:core
* @dev Name of the governor instance (used in building the ERC712 domain separator).
*/functionname() publicviewvirtualreturns (stringmemory);
/**
* @notice module:core
* @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
*/functionversion() publicviewvirtualreturns (stringmemory);
/**
* @notice module:voting
* @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to
* be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of
* key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
*
* There are 2 standard keys: `support` and `quorum`.
*
* - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`.
* - `quorum=bravo` means that only For votes are counted towards quorum.
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
*
* If a counting module makes use of encoded `params`, it should include this under a `params` key with a unique
* name that describes the behavior. For example:
*
* - `params=fractional` might refer to a scheme where votes are divided fractionally between for/against/abstain.
* - `params=erc721` might refer to a scheme where specific NFTs are delegated to vote.
*
* NOTE: The string can be decoded by the standard
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
* JavaScript class.
*/// solhint-disable-next-line func-name-mixedcasefunctionCOUNTING_MODE() publicpurevirtualreturns (stringmemory);
/**
* @notice module:core
* @dev Hashing function used to (re)build the proposal id from the proposal details..
*/functionhashProposal(address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) publicpurevirtualreturns (uint256);
/**
* @notice module:core
* @dev Current state of a proposal, following Compound's convention
*/functionstate(uint256 proposalId) publicviewvirtualreturns (ProposalState);
/**
* @notice module:core
* @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's
* ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the
* beginning of the following block.
*/functionproposalSnapshot(uint256 proposalId) publicviewvirtualreturns (uint256);
/**
* @notice module:core
* @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote
* during this block.
*/functionproposalDeadline(uint256 proposalId) publicviewvirtualreturns (uint256);
/**
* @notice module:user-config
* @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to
* leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
*/functionvotingDelay() publicviewvirtualreturns (uint256);
/**
* @notice module:user-config
* @dev Delay, in number of blocks, between the vote start and vote ends.
*
* NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting
* duration compared to the voting delay.
*/functionvotingPeriod() publicviewvirtualreturns (uint256);
/**
* @notice module:user-config
* @dev Minimum number of cast voted required for a proposal to be successful.
*
* Note: The `blockNumber` parameter corresponds to the snapshot used for counting vote. This allows to scale the
* quorum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).
*/functionquorum(uint256 blockNumber) publicviewvirtualreturns (uint256);
/**
* @notice module:reputation
* @dev Voting power of an `account` at a specific `blockNumber`.
*
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
* multiple), {ERC20Votes} tokens.
*/functiongetVotes(address account, uint256 blockNumber) publicviewvirtualreturns (uint256);
/**
* @notice module:reputation
* @dev Voting power of an `account` at a specific `blockNumber` given additional encoded parameters.
*/functiongetVotesWithParams(address account,
uint256 blockNumber,
bytesmemory params
) publicviewvirtualreturns (uint256);
/**
* @notice module:voting
* @dev Returns weither `account` has cast a vote on `proposalId`.
*/functionhasVoted(uint256 proposalId, address account) publicviewvirtualreturns (bool);
/**
* @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends
* {IGovernor-votingPeriod} blocks after the voting starts.
*
* Emits a {ProposalCreated} event.
*/functionpropose(address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
stringmemory description
) publicvirtualreturns (uint256 proposalId);
/**
* @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the
* deadline to be reached.
*
* Emits a {ProposalExecuted} event.
*
* Note: some module can modify the requirements for execution, for example by adding an additional timelock.
*/functionexecute(address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) publicpayablevirtualreturns (uint256 proposalId);
/**
* @dev Cast a vote
*
* Emits a {VoteCast} event.
*/functioncastVote(uint256 proposalId, uint8 support) publicvirtualreturns (uint256 balance);
/**
* @dev Cast a vote with a reason
*
* Emits a {VoteCast} event.
*/functioncastVoteWithReason(uint256 proposalId,
uint8 support,
stringcalldata reason
) publicvirtualreturns (uint256 balance);
/**
* @dev Cast a vote with a reason and additional encoded parameters
*
* Emits a {VoteCast} or {VoteCastWithParams} event depending on the length of params.
*/functioncastVoteWithReasonAndParams(uint256 proposalId,
uint8 support,
stringcalldata reason,
bytesmemory params
) publicvirtualreturns (uint256 balance);
/**
* @dev Cast a vote using the user's cryptographic signature.
*
* Emits a {VoteCast} event.
*/functioncastVoteBySig(uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) publicvirtualreturns (uint256 balance);
/**
* @dev Cast a vote with a reason and additional encoded parameters using the user's cryptographic signature.
*
* Emits a {VoteCast} or {VoteCastWithParams} event depending on the length of params.
*/functioncastVoteWithReasonAndParamsBySig(uint256 proposalId,
uint8 support,
stringcalldata reason,
bytesmemory params,
uint8 v,
bytes32 r,
bytes32 s
) publicvirtualreturns (uint256 balance);
}
Contract Source Code
File 28 of 35: MagicFolk.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../utils/Common.sol";
import"../utils/SigVer.sol";
import"./MagicFolkGems.sol";
import"./MagicFolkItems.sol";
import"@openzeppelin/contracts/access/Ownable.sol";
import"@openzeppelin/contracts/interfaces/IERC721.sol";
import"@openzeppelin/contracts/interfaces/IERC1155.sol";
import"@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import"@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import"@openzeppelin/contracts/security/ReentrancyGuard.sol";
import"@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import"@openzeppelin/contracts/utils/Counters.sol";
import"@openzeppelin/contracts/utils/introspection/ERC165.sol";
import"@openzeppelin/contracts/access/AccessControl.sol";
contractMagicFolkisERC165,
ERC721,
ERC721Enumerable,
ERC721Holder,
CommonConstants,
IERC1155Receiver,
ReentrancyGuard,
SigVer,
AccessControl,
Ownable{
usingCountersforCounters.Counter;
structStats {
uint8 powerLevel;
Item mainHand;
Item offHand;
Item pet;
}
structPayee {
address wallet;
uint16 percentagePoints;
bytes24 payeeId;
}
// Setup payees// Hardcoded here instead of being added by an external function// for the sake of immutability and transparency.
Payee[11] public _payees;
eventEquipped(uint256indexed _tokenId,
uint256indexed _itemId,
ItemType _itemType
);
eventUnequipped(uint256indexed _tokenId,
uint256indexed _itemId,
ItemType _itemType
);
eventStaked(uint256indexed _tokenId, address owner);
eventUnstaked(uint256indexed _tokenId, address owner);
eventpublicSaleToggled(bool state);
eventprivateSaleToggled(bool state);
eventstakingToggled(bool state);
// token id => statsmapping(uint256=> Stats) private _tokenStats;
// Private salemapping(address=>uint256) private _totalMintsPerAddress;
// Public salemapping(address=>uint256) public _mintNonce;
// Stakingmapping(uint256=>uint256) private _lastClaims;
mapping(uint256=>address) public _tokenOwners;
mapping(address=>uint256[]) public _stakedTokens;
Counters.Counter private _tokenIdCounter;
MagicFolkItems MAGIC_FOLK_MAINHAND;
MagicFolkItems MAGIC_FOLK_OFFHAND;
MagicFolkItems MAGIC_FOLK_PET;
MagicFolkGems MAGIC_FOLK_GEMS;
// MINT CONSTANTSuint256publicconstant PUBLIC_ALLOWANCE =10;
uint256publicconstant MAX_MINT =9500;
uint256publicconstant TEAM_MINT =500;
uint256publicconstant PRIVATE_PRICE =0.1ether;
uint256publicconstant PUBLIC_PRICE =0.125ether;
addresspublicconstant FEE_ADDRESS =0x670326f4470d4D2F5347377Ff187717a81aB1318;
uint256public _fees =60.0ether;
uint256public _teamMinted =0;
addresspublic _signer;
// Gems per day per power leveluint256 _gemRate =10;
uint256constant SECONDS_PER_DAY =86400;
stringpublic _URI ="https://cdn-stg.magicfolk.io/api/genesis/";
uint8[MAX_MINT + TEAM_MINT] private _basePowerLevels; // token id => base power levelboolprivate _publicSale =false;
boolprivate _privateSale =false;
boolprivate _powerLevelsSet =false;
boolpublic _publicSaleSignatureRequired =true;
boolpublic _stakingEnabled =false;
boolpublic _listable =false;
boolpublic _initialFeesWithdrawn =false;
constructor(address signer,
address magicFolkMainhand,
address magicFolkOffhand,
address magicFolkPet
) ERC721("Magic Folk", "MF") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_signer = signer;
MAGIC_FOLK_MAINHAND = MagicFolkItems(magicFolkMainhand);
MAGIC_FOLK_OFFHAND = MagicFolkItems(magicFolkOffhand);
MAGIC_FOLK_PET = MagicFolkItems(magicFolkPet);
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
// Setup payees
_payees[0] = Payee(
0x586a6c03DA4959C6341845C210b4CdBec930Af37,
265,
"ELON_MUSK"
);
_payees[1] = Payee(
0xa8fD19cb5F949677504DD90f8B6efe044286e6B2,
80,
"DONALD_TRUMP"
);
_payees[2] = Payee(
0xD85aA7341a63B413972c8e8D63Ae7a7bC08A5aFD,
25,
"WARREN_BUFFET"
);
_payees[3] = Payee(
0x4fB91f8b17702aFf47BE977A226dDdabf5475661,
25,
"JEFF_BEZOS"
);
_payees[4] = Payee(
0x7913FEDA30503465EDAdc674a66fbDcB581f6840,
120,
"BILL_GATES"
);
_payees[5] = Payee(
0x2E8a3F14feDA7FA7690260a06A1656BFe20bE1aC,
60,
"LEBRON_JAMES"
);
_payees[6] = Payee(
0x60d1082D0fdaB22990f56A70B68AdDC049F75EC8,
100,
"NICOLAS_CAGE"
);
_payees[7] = Payee(
0x71dcB19A6D322C9D826aA6b61442828436Aa6fb2,
50,
"KENDRICK_LAMAR"
);
_payees[8] = Payee(
0x996107A817f0fbaF389F1DCC1A48Dfb2eDb78D33,
25,
"R_KELLY"
);
_payees[9] = Payee(
0xAB1ca28b50EdC107023d81e71640da3ee26F93A0,
150,
"LIL_DICKY"
);
_payees[10] = Payee(
0x3750737d7fbF284705a329AB674D9309485B5bE2,
100,
"JIMMY_CARR"
);
uint256 percentagePointSum =0;
for (uint256 i =0; i < _payees.length; i++) {
percentagePointSum += _payees[i].percentagePoints;
}
require(percentagePointSum ==1000, "INVALID_PERCENTAGES");
}
functionsetMagicFolkGemsContract(address magicFolkGems)
publiconlyRole(DEFAULT_ADMIN_ROLE)
{
MAGIC_FOLK_GEMS = MagicFolkGems(magicFolkGems);
}
functionsetMagicFolkItemsContract(address magicFolkItems,
ItemType itemType
) publiconlyRole(DEFAULT_ADMIN_ROLE) {
if (itemType == ItemType.Mainhand) {
MAGIC_FOLK_MAINHAND = MagicFolkItems(magicFolkItems);
} elseif (itemType == ItemType.Offhand) {
MAGIC_FOLK_OFFHAND = MagicFolkItems(magicFolkItems);
} elseif (itemType == ItemType.Pet) {
MAGIC_FOLK_PET = MagicFolkItems(magicFolkItems);
} else {
revert();
}
}
functionsetSignerAddress(address signer)
externalonlyRole(DEFAULT_ADMIN_ROLE)
{
_signer = signer;
}
functionsetBaseURI(stringcalldata URI)
externalonlyRole(DEFAULT_ADMIN_ROLE)
{
_URI = URI;
}
/**
@dev Once enabled, listing on OpenSea cannot be disabled again.
*/functionenableListings() externalonlyRole(DEFAULT_ADMIN_ROLE) {
_listable =true;
}
/**
@dev To prevent buyers listing on OpenSea before public and private sales
have ended, we override this function to return false unless listings
have been enabled.
*/functionisApprovedForAll(address owner, address operator)
publicviewoverridereturns (bool)
{
if (!_listable) {
returnfalse;
} else {
returnsuper.isApprovedForAll(owner, operator);
}
}
function_baseURI() internalviewoverridereturns (stringmemory) {
return _URI;
}
functionpublicSaleActive() publicviewreturns (bool) {
return _publicSaleActive();
}
functiontogglePublicSale() publiconlyRole(DEFAULT_ADMIN_ROLE) {
require(!_privateSaleActive());
_publicSale =!_publicSale;
emit publicSaleToggled(_publicSale);
}
functiontoggleStaking() externalonlyRole(DEFAULT_ADMIN_ROLE) {
_stakingEnabled =!_stakingEnabled;
emit stakingToggled(_stakingEnabled);
}
functiontogglePublicSaleSigRequired() publiconlyRole(DEFAULT_ADMIN_ROLE) {
_publicSaleSignatureRequired =!_publicSaleSignatureRequired;
}
functionprivateSaleActive() publicviewreturns (bool) {
return _privateSaleActive();
}
functiontogglePrivateSale() publiconlyRole(DEFAULT_ADMIN_ROLE) {
require(!_publicSaleActive());
_privateSale =!_privateSale;
emit privateSaleToggled(_privateSale);
}
// Power levels for legendary NFTs will be set after revealfunctionsetPowerLevels(uint8[] calldata powerLevels,
uint256[] calldata tokenIds
) externalonlyRole(DEFAULT_ADMIN_ROLE) {
require(!_powerLevelsSet);
require(powerLevels.length== tokenIds.length);
for (uint256 i =0; i < powerLevels.length; i++) {
_basePowerLevels[tokenIds[i]] = powerLevels[i];
}
}
functionlockPowerLevels() externalonlyRole(DEFAULT_ADMIN_ROLE) {
require(!_powerLevelsSet);
_powerLevelsSet =true;
}
/**
@dev Mints an NFT for the public sale. Uses a nonce, msgHash and signature
to ensure minting is only possible through our website.
@param qty Amount to be minted
@param mintNonce Nonce value that's incremented after each mint, used to
ensure signature + msgHash are unique. Can be retrieved
via ._mintNonce(address) before being hashed + signed and
passed into function.
@param msgHash hashed message, should match the message that's been signed
by our keypair on frontend.
(['address', 'uint256'], [buyerAddress, mintNonce])
@param signature signed version of msgHash
*/functionsafeMintPublic(uint256 qty,
uint256 mintNonce,
bytes32 msgHash,
bytescalldata signature
) externalpayablenonReentrant{
address to = _msgSender();
require(_publicSaleActive(), "Public sale not active");
require(msg.value>= qty * PUBLIC_PRICE, "Insufficient funds");
require(qty <= PUBLIC_ALLOWANCE, "EXCEED_ALLOWANCE");
require(
_tokenIdCounter.current() + qty - _teamMinted <= MAX_MINT,
"SOLD_OUT"
);
require(mintNonce == _mintNonce[to], "INVALID_NONCE");
require(
_verifyMsg(to, mintNonce, msgHash, signature, _signer) ||!_publicSaleSignatureRequired,
"INVALID_SIG"
);
for (uint256 i =0; i < qty; i++) {
_safeMint(to);
}
_mintNonce[to]++;
}
/**
@dev Mints an NFT for the private sale. Eligibility and allowance for
private sale are verified, hashed, and signed to ensure only those
eligible can mint.
@param qty Amount to be minted
@param privateSaleAllowance Total number of NFTs this account can mint
in the private sale.
@param msgHash hashed message, should match the message that's been signed
by our keypair on frontend.
(['address', 'uint256'], [buyerAddress, privateSaleAllowance])
@param signature signed version of msgHash
*/functionsafeMintPrivate(uint256 qty,
uint256 privateSaleAllowance,
bytes32 msgHash,
bytescalldata signature
) externalpayablenonReentrant{
address to = _msgSender();
require(_privateSaleActive(), "Private sale not active");
require(msg.value>= qty * PRIVATE_PRICE, "Insufficient funds");
require(
qty + _totalMintsPerAddress[to] <= privateSaleAllowance,
"Exceeded allowance"
);
require(
_verifyMsg(to, privateSaleAllowance, msgHash, signature, _signer),
"INVALID_SIG"
);
require(
_tokenIdCounter.current() + qty - _teamMinted <= MAX_MINT,
"SOLD_OUT"
);
for (uint256 i =0; i < qty; i++) {
_safeMint(to);
}
_totalMintsPerAddress[to] += qty;
}
functionteamMint(uint256 qty) externalonlyRole(DEFAULT_ADMIN_ROLE) {
require(_publicSaleActive() || _privateSaleActive());
address to =msg.sender;
require(qty + _teamMinted <= TEAM_MINT, "TEAM_MINT_LIMIT_REACHED");
for (uint256 i =0; i < qty; i++) {
_safeMint(to);
}
_teamMinted += qty;
}
functionisTokenStaked(uint256 tokenId) publicviewreturns (bool) {
return _isTokenStaked(tokenId);
}
functionstakeToken(uint256 tokenId) externalnonReentrant{
_stakeToken(msg.sender, tokenId);
}
functionstakeTokens(uint256[] calldata tokenIds) externalnonReentrant{
for (uint256 i =0; i < tokenIds.length; i++) {
_stakeToken(msg.sender, tokenIds[i]);
}
}
functiongetQuantityStaked(address owner) publicviewreturns (uint256) {
return _stakedTokens[owner].length;
}
functiongetStakedTokens(address owner)
publicviewreturns (uint256[] memory)
{
return _stakedTokens[owner];
}
functiontokensOfOwner(address owner)
publicviewreturns (uint256[] memory)
{
uint256 totalOwned = balanceOf(owner);
uint256[] memory ret =newuint256[](totalOwned);
for (uint256 i =0; i < totalOwned; i++) {
ret[i] = ERC721Enumerable.tokenOfOwnerByIndex(owner, i);
}
return ret;
}
functionsetGemRate(uint256 newGemRate)
publiconlyRole(DEFAULT_ADMIN_ROLE)
{
_setGemRate(newGemRate);
}
function_stakeToken(address user, uint256 tokenId) internal{
require(_isApprovedOrOwner(user, tokenId), "NOT_AUTHORISED");
require(!_isTokenStaked(tokenId), "ALREADY_STAKED");
_setLastClaim(tokenId);
_tokenOwners[tokenId] = user;
_stakedTokens[user].push(tokenId);
safeTransferFrom(user, address(this), tokenId);
}
functionunstakeToken(uint256 tokenId) externalnonReentrant{
_unstakeToken(msg.sender, tokenId);
}
functionunstakeTokens(uint256[] calldata tokenIds) externalnonReentrant{
for (uint256 i =0; i < tokenIds.length; i++) {
_unstakeToken(msg.sender, tokenIds[i]);
}
}
functionclaimGems(uint256 tokenId) publicnonReentrant{
require(_isTokenStaked(tokenId), "NOT_STAKED");
require(_tokenOwners[tokenId] == _msgSender(), "NOT_AUTHORISED");
uint256 allocation = _calcAllocation(tokenId);
require(allocation >0, "NO_GEMS");
MAGIC_FOLK_GEMS.mint(_msgSender(), allocation);
_setLastClaim(tokenId);
}
functionclaimAllGems() external{
uint256[] memory stakedTokens = _stakedTokens[_msgSender()];
for (uint256 i =0; i < stakedTokens.length; i++) {
if (_calcAllocation(stakedTokens[i]) >0) {
claimGems(stakedTokens[i]);
}
}
}
functiongetAllocation(uint256 tokenId) publicviewreturns (uint256) {
return _calcAllocation(tokenId);
}
functiongetTotalUnclaimed(address owner) publicviewreturns (uint256) {
uint256 sum =0;
uint256[] memory stakedTokens = _stakedTokens[owner];
for (uint256 i =0; i < stakedTokens.length; i++) {
sum += _calcAllocation(stakedTokens[i]);
}
return sum;
}
function_safeMint(address to) internal{
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_rollStats(tokenId);
}
// Was originally going to use Chainlink VRF, but we decided to base// power levels on rarity so they'll be written after reveal.// Defaults to 5, legendary NFTs will have a higher power level.function_rollStats(uint256 tokenId) internal{
_setBasePowerLevel(tokenId, 5);
}
modifiertokenExists(uint256 tokenId) {
require(_exists(tokenId), "Token does not exist.");
_;
}
functiongetStats(uint256 tokenId)
publicviewtokenExists(tokenId)
returns (Stats memory)
{
Stats memory stats = _getStats(tokenId);
require(
_basePowerLevels[tokenId] >0,
"Token traits have not been initialized."
);
return stats;
}
functiongetGemRate() publicviewreturns (uint256) {
return _getGemRate();
}
functiongetBasePowerLevel(uint256 tokenId)
publicviewtokenExists(tokenId)
returns (uint8)
{
return _getBasePowerLevel(tokenId);
}
functiononERC1155Received(address _operator,
address _from,
uint256 _id,
uint256 _value,
bytescalldata _data
) externaloverridereturns (bytes4) {
require(_operator == _from, "NOT_AUTHORISED");
require(
msg.sender==address(MAGIC_FOLK_MAINHAND) ||msg.sender==address(MAGIC_FOLK_OFFHAND) ||msg.sender==address(MAGIC_FOLK_PET),
"INVALID_TOKEN_TYPE"
);
(uint256 _nftTokenId, Item memory _item) = decodeOwnerIdAndItem(_data);
require(
ownerOf(_nftTokenId) == _from || _tokenOwners[_nftTokenId] == _from,
"NOT_YOUR_NFT"
);
require(_item.itemId == _id, "INVALID_DECODED_ID");
require(_value ==1, "CAN_ONLY_EQUIP_ONE");
require(
_item.itemType == MagicFolkItems(msg.sender)._itemType(),
"INVALID_ITEMTYPE"
);
_equip(_item, _nftTokenId);
return ERC1155_RECEIVED_VALUE;
}
functionunequip(addressfrom, bytescalldata data) external{
require(
msg.sender==address(MAGIC_FOLK_MAINHAND) ||msg.sender==address(MAGIC_FOLK_OFFHAND) ||msg.sender==address(MAGIC_FOLK_PET),
"Invalid caller"
);
(uint256 nftTokenId, Item memory item) = decodeOwnerIdAndItem(data);
require(
ownerOf(nftTokenId) ==from|| _tokenOwners[nftTokenId] ==from,
"NOT_YOUR_NFT"
);
_unequip(item, nftTokenId);
IERC1155(msg.sender).safeTransferFrom(
address(this),
from,
item.itemId,
1,
""
);
emit Unequipped(nftTokenId, item.itemId, item.itemType);
}
functiononERC1155BatchReceived(address,
address,
uint256[] memory,
uint256[] memory,
bytescalldata) externalpureoverridereturns (bytes4) {
revert();
}
functionwithdraw() publiconlyRole(DEFAULT_ADMIN_ROLE) {
uint256 amount;
uint256 balance =address(this).balance;
bool success =false;
if (!_initialFeesWithdrawn) {
if (balance <= _fees) {
amount = balance;
} else {
amount = _fees;
}
(success, ) =payable(FEE_ADDRESS).call{ value: amount }("");
require(success, "NOPE");
_initialFeesWithdrawn =true;
} else {
for (uint256 i =0; i < _payees.length; i++) {
(success, ) =payable(_payees[i].wallet).call{
value: (balance * _payees[i].percentagePoints) /1000
}("");
require(success);
}
}
}
functionsetFees(uint256 newFees) publiconlyRole(DEFAULT_ADMIN_ROLE) {
_fees = newFees;
}
function_beforeTokenTransfer(addressfrom,
address to,
uint256 tokenId
) internaloverride(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
functionsupportsInterface(bytes4 interfaceID)
publicviewvirtualoverride(ERC721, ERC721Enumerable, IERC165, ERC165, AccessControl)
returns (bool)
{
returnsuper.supportsInterface(interfaceID) ||
interfaceID ==type(IERC1155Receiver).interfaceId||
interfaceID ==0x01ffc9a7||// ERC165
interfaceID ==0x4e2312e0; // ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;;
}
function_isTokenStaked(uint256 tokenId) internalviewreturns (bool) {
return ownerOf(tokenId) ==address(this);
}
function_unstakeToken(address user, uint256 tokenId) internal{
require(_isTokenStaked(tokenId), "NOT_STAKED");
require(_tokenOwners[tokenId] == user, "NOT_AUTHORISED");
uint256 allocation = _calcAllocation(tokenId);
// require(allocation > 0, "CANT_UNSTAKE_YET");if (allocation >0) {
MAGIC_FOLK_GEMS.mint(_msgSender(), allocation);
}
uint256 i =0;
uint256 lastTokenIndex = _stakedTokens[user].length-1;
while (_stakedTokens[user][i] != tokenId) {
i++;
}
_stakedTokens[user][i] = _stakedTokens[user][lastTokenIndex];
_stakedTokens[user].pop();
_lastClaims[tokenId] =0;
delete _tokenOwners[tokenId];
_safeTransfer(address(this), user, tokenId, "");
}
function_publicSaleActive() internalviewreturns (bool) {
return _publicSale;
}
function_privateSaleActive() internalviewreturns (bool) {
return _privateSale;
}
function_equip(Item memory _item, uint256 _nftTokenId) internal{
require(
!(_isEquipped(_nftTokenId, _item.itemType)),
"Slot is not empty"
);
Stats memory stats = _getItemStats(_nftTokenId);
if (_item.itemType == ItemType.Mainhand) {
stats.mainHand = _item;
} elseif (_item.itemType == ItemType.Offhand) {
stats.offHand = _item;
} elseif (_item.itemType == ItemType.Pet) {
stats.pet = _item;
} else {
revert();
}
stats.powerLevel += _item.powerLevel;
_setStats(_nftTokenId, stats);
emit Equipped(_nftTokenId, _item.itemId, _item.itemType);
}
function_unequip(Item memory _item, uint256 _nftTokenId) internal{
require(_isEquipped(_nftTokenId, _item.itemType), "Slot is empty");
Stats memory stats = _getItemStats(_nftTokenId);
if (_item.itemType == ItemType.Mainhand) {
require(stats.mainHand.itemId == _item.itemId, "Incorrect item");
stats.mainHand = _emptyItem();
} elseif (_item.itemType == ItemType.Offhand) {
require(stats.offHand.itemId == _item.itemId, "Incorrect item");
stats.offHand = _emptyItem();
} elseif (_item.itemType == ItemType.Pet) {
require(stats.pet.itemId == _item.itemId, "Incorrect item");
stats.pet = _emptyItem();
} else {
revert();
}
stats.powerLevel -= _item.powerLevel;
_setStats(_nftTokenId, stats);
}
function_isEquipped(uint256 nftTokenId, ItemType slot)
internalviewtokenExists(nftTokenId)
returns (bool)
{
Stats memory stats = _getItemStats(nftTokenId);
if (slot == ItemType.Mainhand) {
return stats.mainHand.itemType == ItemType.Mainhand;
} elseif (slot == ItemType.Offhand) {
return stats.offHand.itemType == ItemType.Offhand;
} else {
return stats.pet.itemType == ItemType.Pet;
}
}
function_getItemStats(uint256 tokenId)
internalviewtokenExists(tokenId)
returns (Stats memory)
{
Stats memory stats = _tokenStats[tokenId];
return stats;
}
function_getStats(uint256 tokenId)
internalviewtokenExists(tokenId)
returns (Stats memory)
{
Stats memory stats = _getItemStats(tokenId);
stats.powerLevel = stats.powerLevel + _getBasePowerLevel(tokenId);
return stats;
}
function_setStats(uint256 tokenId, Stats memory stats)
internaltokenExists(tokenId)
{
_tokenStats[tokenId] = stats;
}
function_setBasePowerLevel(uint256 tokenId, uint8 _powerLevel)
internaltokenExists(tokenId)
{
_basePowerLevels[tokenId] = _powerLevel;
}
function_getBasePowerLevel(uint256 tokenId)
internalviewtokenExists(tokenId)
returns (uint8)
{
return _basePowerLevels[tokenId];
}
function_calcAllocation(uint256 tokenId) internalviewreturns (uint256) {
Stats memory stats = _getStats(tokenId);
uint256 timeDeltaDays = (block.timestamp- _getLastClaim(tokenId)) /
SECONDS_PER_DAY;
return timeDeltaDays * stats.powerLevel * _gemRate;
}
function_getLastClaim(uint256 tokenId)
internalviewtokenExists(tokenId)
returns (uint256)
{
return _lastClaims[tokenId];
}
function_setLastClaim(uint256 tokenId) internaltokenExists(tokenId) {
_lastClaims[tokenId] =block.timestamp;
}
function_setGemRate(uint256 newGemRate) internal{
_gemRate = newGemRate;
}
function_getGemRate() internalviewreturns (uint256) {
return _gemRate;
}
function_emptyItem() internalpurereturns (Item memory) {
return Item(0, 0, ItemType.Empty);
}
}
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../utils/Common.sol";
import"../utils/SigVer.sol";
import"@openzeppelin/contracts/access/Ownable.sol";
import"@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import"@openzeppelin/contracts/access/AccessControl.sol";
import"@openzeppelin/contracts/security/Pausable.sol";
import"@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import"@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import"@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import"@openzeppelin/contracts/security/ReentrancyGuard.sol";
import"@openzeppelin/contracts/utils/Counters.sol";
import"./MagicFolk.sol";
import"./MagicFolkGems.sol";
contractMagicFolkItemsisERC1155,
ERC1155Holder,
SigVer,
Ownable,
AccessControl,
Pausable,
ERC1155Supply,
ReentrancyGuard{
usingECDSAforbytes32;
usingCountersforCounters.Counter;
MagicFolk _magicFolk;
MagicFolkGems _magicFolkGems;
address _signer;
Counters.Counter private _itemCount;
ItemType publicimmutable _itemType;
stringpublic _contractURI;
mapping(uint256=> Item) public _items;
mapping(uint256=>uint256) public _prices;
mapping(uint256=>address) public _collabs;
mapping(uint256=>uint256) public _collabAllowancePerNFT;
// NFT Address => (tokenID => Amount Redeemed)mapping(address=>mapping(uint256=>uint256)) public _collabItemsRedeemed;
constructor(address signer, ItemType itemType)
ERC1155("https://api.magicfolk.com/")
{
_grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
_itemType = itemType;
_pause();
_signer = signer;
}
functionsetMagicFolkGemsAddress(address magicFolkGems)
publiconlyRole(DEFAULT_ADMIN_ROLE)
{
_magicFolkGems = MagicFolkGems(magicFolkGems);
}
functionsetMagicFolkContractAddress(address magicFolk)
publiconlyRole(DEFAULT_ADMIN_ROLE)
{
_magicFolk = MagicFolk(magicFolk);
}
functionsetSignerAddress(address newSigner)
externalonlyRole(DEFAULT_ADMIN_ROLE)
{
_signer = newSigner;
}
functionsetURI(stringmemory newuri) publiconlyRole(DEFAULT_ADMIN_ROLE) {
_setURI(newuri);
}
functionsetContractURI(stringmemory newuri)
publiconlyRole(DEFAULT_ADMIN_ROLE)
{
_contractURI = newuri;
}
functioncontractURI() publicviewreturns (stringmemory) {
return _contractURI;
}
functionpause() publiconlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
functionunpause() publiconlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
/**
@dev function for equipping items to ERC721 NFT
@param from address of NFT holder (must be sender also)
@param itemId id of item they wish to equip
@param magicFolkId tokenId of NFT they wish to equip the item to
*/functionequip(addressfrom,
uint256 itemId,
uint256 magicFolkId
) publicwhenNotPaused{
require(
from== _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
Item memory item = _getItem(itemId);
bytesmemory ownerIdAndItem = encodeOwnerIdAndItem(magicFolkId, item);
_safeTransferFrom(from, address(_magicFolk), itemId, 1, ownerIdAndItem);
}
/**
@dev function for unequipping items from ERC721 NFT
@param from address of holder (must be sender)
@param itemId id of item they wish to unequip
@param magicFolkId tokenId of NFT they wish to unequip the item from
*/functionunequip(addressfrom,
uint256 itemId,
uint256 magicFolkId
) publicwhenNotPaused{
require(
from== _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
Item memory item = _getItem(itemId);
bytesmemory ownerIdAndItem = encodeOwnerIdAndItem(magicFolkId, item);
_magicFolk.unequip(from, ownerIdAndItem);
}
/**
@return total number of items in this contract
*/functionitemCount() publicviewreturns (uint256) {
return _itemCount.current();
}
functiongetItem(uint256 itemId) publicviewreturns (Item memory) {
require(_isInitialised(itemId), "Item not initalised");
return _getItem(itemId);
}
function_getItem(uint256 itemId) internalviewreturns (Item memory) {
return _items[itemId];
}
function_setPrice(uint256 itemId, uint256 price) internal{
_prices[itemId] = price;
}
functionsetPrice(uint256 itemId, uint256 price)
publiconlyRole(DEFAULT_ADMIN_ROLE)
{
_setPrice(itemId, price);
}
function_getPrice(uint256 itemId) internalviewreturns (uint256) {
return _prices[itemId];
}
functiongetPrice(uint256 itemId) publicviewreturns (uint256) {
return _getPrice(itemId);
}
functiongetStockLeft(uint256 itemId) publicviewreturns (uint256) {
return balanceOf(address(this), itemId);
}
/**
@dev Returns an array, A, in which A[id] is the balance of item with
itemId of id.
e.g. If there are 10 items that have been created, and I own
2 of the item with an itemId of 4, but zero of all other items,
the array would look like:
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
*/functiongetOwnedItems(address owner)
publicviewreturns (uint256[] memory)
{
uint256[] memory tokens =newuint256[](_itemCount.current());
for (uint256 i =0; i < tokens.length; i++) {
tokens[i] = balanceOf(owner, i);
}
return tokens;
}
/**
@dev a bit like the mint function on our ERC721 contract, this is when
the buyer actually pays for and receives an item that we've already
minted a supply of in our store.
@param to buyer's address
@param itemId id of item they wish to buy
@param amount amount they wish to buy
*/functionbuyItem(address to,
uint256 itemId,
uint256 amount
) externalnonReentrant{
require(!_isCollabItem(itemId), "COLLAB_ITEM");
uint256 totalPrice = amount * _getPrice(itemId);
uint256 gemBalance = _magicFolkGems.balanceOf(to);
require(gemBalance >= totalPrice, "Insufficient funds");
require(_isInitialised(itemId), "Item not initialised");
_safeTransferFrom(address(this), to, itemId, amount, "");
_magicFolkGems.burn(to, totalPrice);
}
/**
@dev A "whitelist" version of buyItem() for collab items
@param itemId id of the collab item
@param amount qty they wish to buy
@param tokenId tokenId of collab NFT they're using to "redeem" this item,
this is so we can check ownership and track how many items
have been "redeemed" for each token in a collection we've
collab'd with
@param msgHash hashed message, should match the message that's been signed
by our keypair on frontend.
(['address', 'uint256'], [buyerAddress, tokenId])
@param signature signed version of msgHash
*/functionbuyCollabItem(uint256 itemId,
uint256 amount,
uint256 tokenId,
bytes32 msgHash,
bytescalldata signature
) externalnonReentrant{
address to =msg.sender;
require(_isCollabItem(itemId), "NOT_COLLAB_ITEM");
require(_ownsToken(to, _collabs[itemId], tokenId), "NOT_YOUR_TOKEN");
uint256 totalPrice = amount * _getPrice(itemId);
uint256 gemBalance = _magicFolkGems.balanceOf(to);
require(gemBalance >= totalPrice, "INSUFFICIENT_FUNDS");
require(_isInitialised(itemId), "Item not initialised");
require(
amount + _getRedeemed(itemId, tokenId) <=
_collabAllowancePerNFT[itemId],
"TX_WILL_EXCEED_ALLOWANCE"
);
require(
_verifyMsg(to, tokenId, msgHash, signature, _signer),
"INVALID_SIG"
);
_safeTransferFrom(address(this), to, itemId, amount, "");
_magicFolkGems.burn(to, totalPrice);
_redeemCollabItem(itemId, tokenId, amount);
}
/**
@dev Once an item has been 'created' with the mint function, this function
can be used to change the stats for the item.
@param itemId the id assigned to this item in the mint function
@param powerLevel the power level to be assigned to this item
@param itemType ItemType.Mainhand || ItemType.offhand || ItemType.pet,
should be the same as the contracts _itemType value
@param price price in gems that buyers will have to pay, can be altered
later with setPrice() also.
*/functionsetItem(uint256 itemId,
uint8 powerLevel,
ItemType itemType,
uint256 price
) publiconlyRole(DEFAULT_ADMIN_ROLE) {
_setItem(itemId, powerLevel, itemType, price);
}
function_setItem(uint256 itemId,
uint8 powerLevel,
ItemType itemType,
uint256 price
) internal{
require(itemType == _itemType);
Item memory item;
item.itemId = itemId;
item.powerLevel = powerLevel;
item.itemType = itemType;
_items[itemId] = item;
_setPrice(itemId, price);
}
/**
@dev Mint more tokens for an item that has been created
@param itemId The id for the item you're minting
@param amount The quantity to be minted
*/functionmint(uint256 itemId, uint256 amount)
publicwhenNotPausedonlyRole(DEFAULT_ADMIN_ROLE)
{
require(itemId < _itemCount.current(), "ITEM_NOT_EXIST");
_mint(address(this), itemId, amount, "");
}
/**
@dev Create a new *non*-collab item with stats provided. Stats can be
updated later with setItem() if a mistake has been made.
@param initialSupply The initial token supply for this item. More can
be minted in future if needed. But in most situations
this will be the only stock we create for an item.
@param powerLevel Power level stat for item.
@param itemType ItemType enum for this item, simply ensures the correct
contract is being used. Tx will revert if incorrect
itemType is provided.
@param price Initial price for item in $GEMZ
*/functioncreateItem(uint256 initialSupply,
uint8 powerLevel,
ItemType itemType,
uint256 price
) publiconlyRole(DEFAULT_ADMIN_ROLE) {
uint256 itemId = _itemCount.current();
_setItem(itemId, powerLevel, itemType, price);
_mint(address(this), itemId, initialSupply, "");
_itemCount.increment();
}
/**
@dev Overload of standard createItem function with 2 extra parameters,
creates a collab item. Apart from this, it's exactly the same.
First 4 params are the same.
@param initialSupply The initial token supply for this item. More can
be minted in future if needed. But in most situations
this will be the only stock we create for an item.
@param powerLevel Power level stat for item.
@param itemType ItemType enum for this item, simply ensures the correct
contract is being used. Tx will revert if incorrect
itemType is provided.
@param price Initial price for item in $GEMZ. For collab items this will
sometimes be zero.
@param nftContract Address of contract for the Collab NFT. For example,
if the collab is with BAYC the address would be:
0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D (mainnet)
@param allowancePerNFT The amount of items someone can mint for every
eligible NFT they hold. In 99% of cases, this will
be 1, but there may be some situations where we
want a higher number.
*/functioncreateItem(uint256 initialSupply,
uint8 powerLevel,
ItemType itemType,
uint256 price,
address nftContract,
uint256 allowancePerNFT
) publiconlyRole(DEFAULT_ADMIN_ROLE) {
uint256 itemId = _itemCount.current();
_addCollabItem(itemId, nftContract, allowancePerNFT);
_setItem(itemId, powerLevel, itemType, price);
_mint(address(this), itemId, initialSupply, "");
_itemCount.increment();
}
functionmintBatch(address,
uint256[] memory ids,
uint256[] memory amounts,
bytesmemory data
) publiconlyRole(DEFAULT_ADMIN_ROLE) {
_mintBatch(address(this), ids, amounts, data);
}
function_ownsToken(address to,
address nftContract,
uint256 tokenId
) internalviewreturns (bool) {
return IERC721(nftContract).ownerOf(tokenId) == to;
}
function_addCollabItem(uint256 itemId,
address nftContract,
uint256 allowance
) internal{
_collabs[itemId] = nftContract;
_collabAllowancePerNFT[itemId] = allowance;
}
function_redeemCollabItem(uint256 itemId,
uint256 tokenId,
uint256 qty
) internal{
_collabItemsRedeemed[_collabs[itemId]][tokenId] += qty;
}
function_getRedeemed(uint256 itemId, uint256 tokenId)
internalviewreturns (uint256)
{
return _collabItemsRedeemed[_collabs[itemId]][tokenId];
}
functionisCollabItem(uint256 itemId) externalviewreturns (bool) {
return _isCollabItem(itemId);
}
function_isCollabItem(uint256 itemId) internalviewreturns (bool) {
return _collabs[itemId] !=address(0);
}
function_isInitialised(uint256 itemId) internalviewreturns (bool) {
Item memory item = _getItem(itemId);
return (item.itemType != ItemType.Empty);
}
function_beforeTokenTransfer(address operator,
addressfrom,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytesmemory data
) internaloverride(ERC1155, ERC1155Supply) whenNotPaused{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
functionsupportsInterface(bytes4 interfaceID)
publicviewvirtualoverride(ERC1155, ERC1155Receiver, AccessControl)
returns (bool)
{
returnsuper.supportsInterface(interfaceID) ||
interfaceID ==type(IERC1155Receiver).interfaceId||// ERC165
interfaceID ==0x01ffc9a7||// ERC1155_ACCEPTED ^ ERC1155_BATCH_ACCEPTED;
interfaceID ==0x4e2312e0;
}
/// TEST FUNCTIONS /// TODO: remove before mainnetfunctionencodeItem(uint256 itemId) publicviewreturns (bytesmemory) {
return encodeOwnerIdAndItem(0, _items[itemId]);
}
functiondecodeItem(bytescalldata encodedOwnerIdAndItem)
publicpurereturns (uint256, Item memory)
{
require(encodedOwnerIdAndItem.length==128, "wronglen");
return decodeOwnerIdAndItem(encodedOwnerIdAndItem);
}
}
Contract Source Code
File 31 of 35: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)pragmasolidity ^0.8.0;import"../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.
*
* By default, the owner account will be the one that deploys the contract. 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;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @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{
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing 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{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_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 32 of 35: Pausable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/abstractcontractPausableisContext{
/**
* @dev Emitted when the pause is triggered by `account`.
*/eventPaused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/eventUnpaused(address account);
boolprivate _paused;
/**
* @dev Initializes the contract in unpaused state.
*/constructor() {
_paused =false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/modifierwhenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/modifierwhenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/functionpaused() publicviewvirtualreturns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/function_requireNotPaused() internalviewvirtual{
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/function_requirePaused() internalviewvirtual{
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/function_pause() internalvirtualwhenNotPaused{
_paused =true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/function_unpause() internalvirtualwhenPaused{
_paused =false;
emit Unpaused(_msgSender());
}
}
Contract Source Code
File 33 of 35: ReentrancyGuard.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)pragmasolidity ^0.8.0;/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/abstractcontractReentrancyGuard{
// Booleans are more expensive than uint256 or any type that takes up a full// word because each write operation emits an extra SLOAD to first read the// slot's contents, replace the bits taken up by the boolean, and then write// back. This is the compiler's defense against contract upgrades and// pointer aliasing, and it cannot be disabled.// The values being non-zero value makes deployment a bit more expensive,// but in exchange the refund on every call to nonReentrant will be lower in// amount. Since refunds are capped to a percentage of the total// transaction's gas, it is best to keep them low in cases like this one, to// increase the likelihood of the full refund coming into effect.uint256privateconstant _NOT_ENTERED =1;
uint256privateconstant _ENTERED =2;
uint256private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/modifiernonReentrant() {
// On the first call to nonReentrant, _notEntered will be truerequire(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}