Contract is not verified. However, we found a verified contract with the same bytecode in Blockscout DB 0x64dc7518fd3f43f2542e38135ce94d4d0ba55e2a.
All metadata displayed below is from that contract. In order to verify current contract, click Verify & Publish button
Verify & Publish
All metadata displayed below is from that contract. In order to verify current contract, click Verify & Publish button
- Contract name:
- DraftCollection
- Optimization enabled
- true
- Compiler version
- v0.8.19+commit.7dd6d404
- Optimization runs
- 200
- Verified at
- 2023-12-05T11:48:40.257743Z
DraftCollection.sol
/* _____ _____ ___ _____ _____ | _ \ | _ \ / | | ___| |_ _| | | | | | |_| | / /| | | |__ | | | | | | | _ / / / | | | __| | | | |_| | | | \ \ / / | | | | | | |_____/ |_| \_\ /_/ |_| |_| |_| _____ _____ _ _ _____ _____ _____ _ _____ __ _ / ___| / _ \ | | | | | ____| / ___| |_ _| | | / _ \ | \ | | | | | | | | | | | | | |__ | | | | | | | | | | | \| | | | | | | | | | | | | __| | | | | | | | | | | | |\ | | |___ | |_| | | |___ | |___ | |___ | |___ | | | | | |_| | | | \ | \_____| \_____/ |_____| |_____| |_____| \_____| |_| |_| \_____/ |_| \_| _____ /___ \ ___| | / ___/ | |___ |_____| */ // SPDX-License-Identifier: MIT pragma solidity 0.8.19; import { MagnetErc721aBase } from "./MagnetErc721aBase.sol"; import { MagnetErc721aCsrRecipientIsContract } from "./extensions/MagnetErc721aCsrRecipientIsContract.sol"; contract DraftCollection is MagnetErc721aCsrRecipientIsContract { address private constant EVENTHUB_ADDR = 0x922dd7055bD69Fc6df35e1A8BBaB674112B9660c; address private constant TURNSTILE_ADDR = 0xEcf044C5B4b867CFda001101c617eCd347095B44; constructor( address[] memory _team, uint256[] memory _teamShares, Royalty memory _royalty, PublicSale memory _publicSale, Metadata memory _metadata, string memory _provenanceHash, uint256 _revealStrategy, uint256 _maxSupply ) MagnetErc721aBase( "DraftCollection", "DC2", _team, _teamShares, _royalty, _publicSale, _metadata, _provenanceHash, _revealStrategy, _maxSupply, EVENTHUB_ADDR ) MagnetErc721aCsrRecipientIsContract(TURNSTILE_ADDR){} }
/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^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. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @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 * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [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. * ==== */ function isContract(address account) internal view returns (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://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable 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._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "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._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { 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._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { 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._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { 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._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { 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._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); } /** * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to * 0 before setting it to a non-zero value. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } } /** * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. * Revert on invalid signature. */ function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token)); } }
/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/Math.sol"; import "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant _SYMBOLS = "0123456789abcdef"; uint8 private constant _ADDRESS_LENGTH = 20; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toString(int256 value) internal pure returns (string memory) { return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value)))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } }
/ERC721A/contracts/extensions/IERC721AQueryable.sol
// SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.3 // Creator: Chiru Labs pragma solidity ^0.8.4; import '../IERC721A.sol'; /** * @dev Interface of ERC721AQueryable. */ interface IERC721AQueryable is IERC721A { /** * Invalid query range (`start` >= `stop`). */ error InvalidQueryRange(); /** * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting. * * If the `tokenId` is out of bounds: * * - `addr = address(0)` * - `startTimestamp = 0` * - `burned = false` * - `extraData = 0` * * If the `tokenId` is burned: * * - `addr = <Address of owner before token was burned>` * - `startTimestamp = <Timestamp when token was burned>` * - `burned = true` * - `extraData = <Extra data when token was burned>` * * Otherwise: * * - `addr = <Address of owner>` * - `startTimestamp = <Timestamp of start of ownership>` * - `burned = false` * - `extraData = <Extra data at start of ownership>` */ function explicitOwnershipOf(uint256 tokenId) external view returns (TokenOwnership memory); /** * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order. * See {ERC721AQueryable-explicitOwnershipOf} */ function explicitOwnershipsOf(uint256[] memory tokenIds) external view returns (TokenOwnership[] memory); /** * @dev Returns an array of token IDs owned by `owner`, * in the range [`start`, `stop`) * (i.e. `start <= tokenId < stop`). * * This function allows for tokens to be queried if the collection * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}. * * Requirements: * * - `start < stop` */ function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) external view returns (uint256[] memory); /** * @dev Returns an array of token IDs owned by `owner`. * * This function scans the ownership mapping and is O(`totalSupply`) in complexity. * It is meant to be called off-chain. * * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into * multiple smaller scans if the collection is large enough to cause * an out-of-gas error (10K collections should be fine). */ function tokensOfOwner(address owner) external view returns (uint256[] memory); }
/ERC721A/contracts/extensions/ERC721AQueryable.sol
// SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.3 // Creator: Chiru Labs pragma solidity ^0.8.4; import './IERC721AQueryable.sol'; import '../ERC721A.sol'; /** * @title ERC721AQueryable. * * @dev ERC721A subclass with convenience query functions. */ abstract contract ERC721AQueryable is ERC721A, IERC721AQueryable { /** * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting. * * If the `tokenId` is out of bounds: * * - `addr = address(0)` * - `startTimestamp = 0` * - `burned = false` * - `extraData = 0` * * If the `tokenId` is burned: * * - `addr = <Address of owner before token was burned>` * - `startTimestamp = <Timestamp when token was burned>` * - `burned = true` * - `extraData = <Extra data when token was burned>` * * Otherwise: * * - `addr = <Address of owner>` * - `startTimestamp = <Timestamp of start of ownership>` * - `burned = false` * - `extraData = <Extra data at start of ownership>` */ function explicitOwnershipOf(uint256 tokenId) public view virtual override returns (TokenOwnership memory ownership) { unchecked { if (tokenId >= _startTokenId()) { if (tokenId < _nextTokenId()) { // If the `tokenId` is within bounds, // scan backwards for the initialized ownership slot. while (!_ownershipIsInitialized(tokenId)) --tokenId; return _ownershipAt(tokenId); } } } } /** * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order. * See {ERC721AQueryable-explicitOwnershipOf} */ function explicitOwnershipsOf(uint256[] calldata tokenIds) external view virtual override returns (TokenOwnership[] memory) { TokenOwnership[] memory ownerships; uint256 i = tokenIds.length; assembly { // Grab the free memory pointer. ownerships := mload(0x40) // Store the length. mstore(ownerships, i) // Allocate one word for the length, // `tokenIds.length` words for the pointers. i := shl(5, i) // Multiply `i` by 32. mstore(0x40, add(add(ownerships, 0x20), i)) } while (i != 0) { uint256 tokenId; assembly { i := sub(i, 0x20) tokenId := calldataload(add(tokenIds.offset, i)) } TokenOwnership memory ownership = explicitOwnershipOf(tokenId); assembly { // Store the pointer of `ownership` in the `ownerships` array. mstore(add(add(ownerships, 0x20), i), ownership) } } return ownerships; } /** * @dev Returns an array of token IDs owned by `owner`, * in the range [`start`, `stop`) * (i.e. `start <= tokenId < stop`). * * This function allows for tokens to be queried if the collection * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}. * * Requirements: * * - `start < stop` */ function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) external view virtual override returns (uint256[] memory) { return _tokensOfOwnerIn(owner, start, stop); } /** * @dev Returns an array of token IDs owned by `owner`. * * This function scans the ownership mapping and is O(`totalSupply`) in complexity. * It is meant to be called off-chain. * * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into * multiple smaller scans if the collection is large enough to cause * an out-of-gas error (10K collections should be fine). */ function tokensOfOwner(address owner) external view virtual override returns (uint256[] memory) { uint256 start = _startTokenId(); uint256 stop = _nextTokenId(); uint256[] memory tokenIds; if (start != stop) tokenIds = _tokensOfOwnerIn(owner, start, stop); return tokenIds; } /** * @dev Helper function for returning an array of token IDs owned by `owner`. * * Note that this function is optimized for smaller bytecode size over runtime gas, * since it is meant to be called off-chain. */ function _tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) private view returns (uint256[] memory) { unchecked { if (start >= stop) _revert(InvalidQueryRange.selector); // Set `start = max(start, _startTokenId())`. if (start < _startTokenId()) { start = _startTokenId(); } uint256 stopLimit = _nextTokenId(); // Set `stop = min(stop, stopLimit)`. if (stop >= stopLimit) { stop = stopLimit; } uint256[] memory tokenIds; uint256 tokenIdsMaxLength = balanceOf(owner); bool startLtStop = start < stop; assembly { // Set `tokenIdsMaxLength` to zero if `start` is less than `stop`. tokenIdsMaxLength := mul(tokenIdsMaxLength, startLtStop) } if (tokenIdsMaxLength != 0) { // Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`, // to cater for cases where `balanceOf(owner)` is too big. if (stop - start <= tokenIdsMaxLength) { tokenIdsMaxLength = stop - start; } assembly { // Grab the free memory pointer. tokenIds := mload(0x40) // Allocate one word for the length, and `tokenIdsMaxLength` words // for the data. `shl(5, x)` is equivalent to `mul(32, x)`. mstore(0x40, add(tokenIds, shl(5, add(tokenIdsMaxLength, 1)))) } // We need to call `explicitOwnershipOf(start)`, // because the slot at `start` may not be initialized. TokenOwnership memory ownership = explicitOwnershipOf(start); address currOwnershipAddr; // If the starting slot exists (i.e. not burned), // initialize `currOwnershipAddr`. // `ownership.address` will not be zero, // as `start` is clamped to the valid token ID range. if (!ownership.burned) { currOwnershipAddr = ownership.addr; } uint256 tokenIdsIdx; // Use a do-while, which is slightly more efficient for this case, // as the array will at least contain one element. do { ownership = _ownershipAt(start); assembly { switch mload(add(ownership, 0x40)) // if `ownership.burned == false`. case 0 { // if `ownership.addr != address(0)`. // The `addr` already has it's upper 96 bits clearned, // since it is written to memory with regular Solidity. if mload(ownership) { currOwnershipAddr := mload(ownership) } // if `currOwnershipAddr == owner`. // The `shl(96, x)` is to make the comparison agnostic to any // dirty upper 96 bits in `owner`. if iszero(shl(96, xor(currOwnershipAddr, owner))) { tokenIdsIdx := add(tokenIdsIdx, 1) mstore(add(tokenIds, shl(5, tokenIdsIdx)), start) } } // Otherwise, reset `currOwnershipAddr`. // This handles the case of batch burned tokens // (burned bit of first slot set, remaining slots left uninitialized). default { currOwnershipAddr := 0 } start := add(start, 1) } } while (!(start == stop || tokenIdsIdx == tokenIdsMaxLength)); // Store the length of the array. assembly { mstore(tokenIds, tokenIdsIdx) } } return tokenIds; } } }
/ERC721A/contracts/IERC721A.sol
// SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.3 // Creator: Chiru Labs pragma solidity ^0.8.4; /** * @dev Interface of ERC721A. */ interface IERC721A { /** * The caller must own the token or be an approved operator. */ error ApprovalCallerNotOwnerNorApproved(); /** * The token does not exist. */ error ApprovalQueryForNonexistentToken(); /** * Cannot query the balance for the zero address. */ error BalanceQueryForZeroAddress(); /** * Cannot mint to the zero address. */ error MintToZeroAddress(); /** * The quantity of tokens minted must be more than zero. */ error MintZeroQuantity(); /** * The token does not exist. */ error OwnerQueryForNonexistentToken(); /** * The caller must own the token or be an approved operator. */ error TransferCallerNotOwnerNorApproved(); /** * The token must be owned by `from`. */ error TransferFromIncorrectOwner(); /** * Cannot safely transfer to a contract that does not implement the * ERC721Receiver interface. */ error TransferToNonERC721ReceiverImplementer(); /** * Cannot transfer to the zero address. */ error TransferToZeroAddress(); /** * The token does not exist. */ error URIQueryForNonexistentToken(); /** * The `quantity` minted with ERC2309 exceeds the safety limit. */ error MintERC2309QuantityExceedsLimit(); /** * The `extraData` cannot be set on an unintialized ownership slot. */ error OwnershipNotInitializedForExtraData(); // ============================================================= // STRUCTS // ============================================================= struct TokenOwnership { // The address of the owner. address addr; // Stores the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; // Arbitrary data similar to `startTimestamp` that can be set via {_extraData}. uint24 extraData; } // ============================================================= // TOKEN COUNTERS // ============================================================= /** * @dev Returns the total number of tokens in existence. * Burned tokens will reduce the count. * To get the total number of tokens minted, please see {_totalMinted}. */ function totalSupply() external view returns (uint256); // ============================================================= // IERC165 // ============================================================= /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); // ============================================================= // IERC721 // ============================================================= /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables * (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in `owner`'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, * checking first that contract recipients are aware of the ERC721 protocol * to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move * this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external payable; /** * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external payable; /** * @dev Transfers `tokenId` from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} * whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token * by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external payable; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the * zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external payable; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} * for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll}. */ function isApprovedForAll(address owner, address operator) external view returns (bool); // ============================================================= // IERC721Metadata // ============================================================= /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); // ============================================================= // IERC2309 // ============================================================= /** * @dev Emitted when tokens in `fromTokenId` to `toTokenId` * (inclusive) is transferred from `from` to `to`, as defined in the * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309) standard. * * See {_mintERC2309} for more details. */ event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to); }
/ERC721A/contracts/ERC721A.sol
// SPDX-License-Identifier: MIT // ERC721A Contracts v4.2.3 // Creator: Chiru Labs pragma solidity ^0.8.4; import './IERC721A.sol'; /** * @dev Interface of ERC721 token receiver. */ interface ERC721A__IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC721A * * @dev Implementation of the [ERC721](https://eips.ethereum.org/EIPS/eip-721) * Non-Fungible Token Standard, including the Metadata extension. * Optimized for lower gas during batch mints. * * Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...) * starting from `_startTokenId()`. * * Assumptions: * * - An owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * - The maximum token ID cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is IERC721A { // Bypass for a `--via-ir` bug (https://github.com/chiru-labs/ERC721A/pull/364). struct TokenApprovalRef { address value; } // ============================================================= // CONSTANTS // ============================================================= // Mask of an entry in packed address data. uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1; // The bit position of `numberMinted` in packed address data. uint256 private constant _BITPOS_NUMBER_MINTED = 64; // The bit position of `numberBurned` in packed address data. uint256 private constant _BITPOS_NUMBER_BURNED = 128; // The bit position of `aux` in packed address data. uint256 private constant _BITPOS_AUX = 192; // Mask of all 256 bits in packed address data except the 64 bits for `aux`. uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1; // The bit position of `startTimestamp` in packed ownership. uint256 private constant _BITPOS_START_TIMESTAMP = 160; // The bit mask of the `burned` bit in packed ownership. uint256 private constant _BITMASK_BURNED = 1 << 224; // The bit position of the `nextInitialized` bit in packed ownership. uint256 private constant _BITPOS_NEXT_INITIALIZED = 225; // The bit mask of the `nextInitialized` bit in packed ownership. uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225; // The bit position of `extraData` in packed ownership. uint256 private constant _BITPOS_EXTRA_DATA = 232; // Mask of all 256 bits in a packed ownership except the 24 bits for `extraData`. uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1; // The mask of the lower 160 bits for addresses. uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1; // The maximum `quantity` that can be minted with {_mintERC2309}. // This limit is to prevent overflows on the address data entries. // For a limit of 5000, a total of 3.689e15 calls to {_mintERC2309} // is required to cause an overflow, which is unrealistic. uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000; // The `Transfer` event signature is given by: // `keccak256(bytes("Transfer(address,address,uint256)"))`. bytes32 private constant _TRANSFER_EVENT_SIGNATURE = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; // ============================================================= // STORAGE // ============================================================= // The next token ID to be minted. uint256 private _currentIndex; // The number of tokens burned. uint256 private _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. // See {_packedOwnershipOf} implementation for details. // // Bits Layout: // - [0..159] `addr` // - [160..223] `startTimestamp` // - [224] `burned` // - [225] `nextInitialized` // - [232..255] `extraData` mapping(uint256 => uint256) private _packedOwnerships; // Mapping owner address to address data. // // Bits Layout: // - [0..63] `balance` // - [64..127] `numberMinted` // - [128..191] `numberBurned` // - [192..255] `aux` mapping(address => uint256) private _packedAddressData; // Mapping from token ID to approved address. mapping(uint256 => TokenApprovalRef) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // ============================================================= // CONSTRUCTOR // ============================================================= constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } // ============================================================= // TOKEN COUNTING OPERATIONS // ============================================================= /** * @dev Returns the starting token ID. * To change the starting token ID, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Returns the next token ID to be minted. */ function _nextTokenId() internal view virtual returns (uint256) { return _currentIndex; } /** * @dev Returns the total number of tokens in existence. * Burned tokens will reduce the count. * To get the total number of tokens minted, please see {_totalMinted}. */ function totalSupply() public view virtual override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than `_currentIndex - _startTokenId()` times. unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * @dev Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view virtual returns (uint256) { // Counter underflow is impossible as `_currentIndex` does not decrement, // and it is initialized to `_startTokenId()`. unchecked { return _currentIndex - _startTokenId(); } } /** * @dev Returns the total number of tokens burned. */ function _totalBurned() internal view virtual returns (uint256) { return _burnCounter; } // ============================================================= // ADDRESS DATA OPERATIONS // ============================================================= /** * @dev Returns the number of tokens in `owner`'s account. */ function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) _revert(BalanceQueryForZeroAddress.selector); return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY; } /** * Returns the auxiliary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return uint64(_packedAddressData[owner] >> _BITPOS_AUX); } /** * Sets the auxiliary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal virtual { uint256 packed = _packedAddressData[owner]; uint256 auxCasted; // Cast `aux` with assembly to avoid redundant masking. assembly { auxCasted := aux } packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX); _packedAddressData[owner] = packed; } // ============================================================= // IERC165 // ============================================================= /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { // The interface IDs are constants representing the first 4 bytes // of the XOR of all function selectors in the interface. // See: [ERC165](https://eips.ethereum.org/EIPS/eip-165) // (e.g. `bytes4(i.functionA.selector ^ i.functionB.selector ^ ...)`) return interfaceId == 0x01ffc9a7 || // ERC165 interface ID for ERC165. interfaceId == 0x80ac58cd || // ERC165 interface ID for ERC721. interfaceId == 0x5b5e139f; // ERC165 interface ID for ERC721Metadata. } // ============================================================= // IERC721Metadata // ============================================================= /** * @dev Returns the token collection name. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the token collection symbol. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) _revert(URIQueryForNonexistentToken.selector); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : ''; } /** * @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, it can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } // ============================================================= // OWNERSHIPS OPERATIONS // ============================================================= /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return address(uint160(_packedOwnershipOf(tokenId))); } /** * @dev Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around over time. */ function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnershipOf(tokenId)); } /** * @dev Returns the unpacked `TokenOwnership` struct at `index`. */ function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) { return _unpackedOwnership(_packedOwnerships[index]); } /** * @dev Returns whether the ownership slot at `index` is initialized. * An uninitialized slot does not necessarily mean that the slot has no owner. */ function _ownershipIsInitialized(uint256 index) internal view virtual returns (bool) { return _packedOwnerships[index] != 0; } /** * @dev Initializes the ownership slot minted at `index` for efficiency purposes. */ function _initializeOwnershipAt(uint256 index) internal virtual { if (_packedOwnerships[index] == 0) { _packedOwnerships[index] = _packedOwnershipOf(index); } } /** * Returns the packed ownership data of `tokenId`. */ function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) { if (_startTokenId() <= tokenId) { packed = _packedOwnerships[tokenId]; // If the data at the starting slot does not exist, start the scan. if (packed == 0) { if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector); // Invariant: // There will always be an initialized ownership slot // (i.e. `ownership.addr != address(0) && ownership.burned == false`) // before an unintialized ownership slot // (i.e. `ownership.addr == address(0) && ownership.burned == false`) // Hence, `tokenId` will not underflow. // // We can directly compare the packed value. // If the address is zero, packed will be zero. for (;;) { unchecked { packed = _packedOwnerships[--tokenId]; } if (packed == 0) continue; if (packed & _BITMASK_BURNED == 0) return packed; // Otherwise, the token is burned, and we must revert. // This handles the case of batch burned tokens, where only the burned bit // of the starting slot is set, and remaining slots are left uninitialized. _revert(OwnerQueryForNonexistentToken.selector); } } // Otherwise, the data exists and we can skip the scan. // This is possible because we have already achieved the target condition. // This saves 2143 gas on transfers of initialized tokens. // If the token is not burned, return `packed`. Otherwise, revert. if (packed & _BITMASK_BURNED == 0) return packed; } _revert(OwnerQueryForNonexistentToken.selector); } /** * @dev Returns the unpacked `TokenOwnership` struct from `packed`. */ function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) { ownership.addr = address(uint160(packed)); ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP); ownership.burned = packed & _BITMASK_BURNED != 0; ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA); } /** * @dev Packs ownership data into a single uint256. */ function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) { assembly { // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean. owner := and(owner, _BITMASK_ADDRESS) // `owner | (block.timestamp << _BITPOS_START_TIMESTAMP) | flags`. result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags)) } } /** * @dev Returns the `nextInitialized` flag set if `quantity` equals 1. */ function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) { // For branchless setting of the `nextInitialized` flag. assembly { // `(quantity == 1) << _BITPOS_NEXT_INITIALIZED`. result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1)) } } // ============================================================= // APPROVAL OPERATIONS // ============================================================= /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. See {ERC721A-_approve}. * * Requirements: * * - The caller must own the token or be an approved operator. */ function approve(address to, uint256 tokenId) public payable virtual override { _approve(to, tokenId, true); } /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) _revert(ApprovalQueryForNonexistentToken.selector); return _tokenApprovals[tokenId].value; } /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} * for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool approved) public virtual override { _operatorApprovals[_msgSenderERC721A()][operator] = approved; emit ApprovalForAll(_msgSenderERC721A(), operator, approved); } /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @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. See {_mint}. */ function _exists(uint256 tokenId) internal view virtual returns (bool result) { if (_startTokenId() <= tokenId) { if (tokenId < _currentIndex) { uint256 packed; while ((packed = _packedOwnerships[tokenId]) == 0) --tokenId; result = packed & _BITMASK_BURNED == 0; } } } /** * @dev Returns whether `msgSender` is equal to `approvedAddress` or `owner`. */ function _isSenderApprovedOrOwner( address approvedAddress, address owner, address msgSender ) private pure returns (bool result) { assembly { // Mask `owner` to the lower 160 bits, in case the upper bits somehow aren't clean. owner := and(owner, _BITMASK_ADDRESS) // Mask `msgSender` to the lower 160 bits, in case the upper bits somehow aren't clean. msgSender := and(msgSender, _BITMASK_ADDRESS) // `msgSender == owner || msgSender == approvedAddress`. result := or(eq(msgSender, owner), eq(msgSender, approvedAddress)) } } /** * @dev Returns the storage slot and value for the approved address of `tokenId`. */ function _getApprovedSlotAndAddress(uint256 tokenId) private view returns (uint256 approvedAddressSlot, address approvedAddress) { TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId]; // The following is equivalent to `approvedAddress = _tokenApprovals[tokenId].value`. assembly { approvedAddressSlot := tokenApproval.slot approvedAddress := sload(approvedAddressSlot) } } // ============================================================= // TRANSFER OPERATIONS // ============================================================= /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token * by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) public payable virtual override { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); // Mask `from` to the lower 160 bits, in case the upper bits somehow aren't clean. from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS)); if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector); (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId); // The nested ifs save around 20+ gas over a compound boolean condition. if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner. assembly { if approvedAddress { // This is equivalent to `delete _tokenApprovals[tokenId]`. sstore(approvedAddressSlot, 0) } } // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256. unchecked { // We can directly increment and decrement the balances. --_packedAddressData[from]; // Updates: `balance -= 1`. ++_packedAddressData[to]; // Updates: `balance += 1`. // Updates: // - `address` to the next owner. // - `startTimestamp` to the timestamp of transfering. // - `burned` to `false`. // - `nextInitialized` to `true`. _packedOwnerships[tokenId] = _packOwnershipData( to, _BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked) ); // If the next slot may not have been initialized (i.e. `nextInitialized == false`) . if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; // If the next slot's address is zero and not burned (i.e. packed value is zero). if (_packedOwnerships[nextTokenId] == 0) { // If the next slot is within bounds. if (nextTokenId != _currentIndex) { // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS; assembly { // Emit the `Transfer` event. log4( 0, // Start of data (0, since no data). 0, // End of data (0, since no data). _TRANSFER_EVENT_SIGNATURE, // Signature. from, // `from`. toMasked, // `to`. tokenId // `tokenId`. ) } if (toMasked == 0) _revert(TransferToZeroAddress.selector); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `safeTransferFrom(from, to, tokenId, '')`. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public payable virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token * by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public payable virtual override { transferFrom(from, to, tokenId); if (to.code.length != 0) if (!_checkContractOnERC721Received(from, to, tokenId, _data)) { _revert(TransferToNonERC721ReceiverImplementer.selector); } } /** * @dev Hook that is called before a set of serially-ordered token IDs * are about to be transferred. This includes minting. * And also called before burning one token. * * `startTokenId` - the first token ID to be transferred. * `quantity` - the amount to be transferred. * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token IDs * have been transferred. This includes minting. * And also called after one token has been burned. * * `startTokenId` - the first token ID to be transferred. * `quantity` - the amount to be transferred. * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * `from` - Previous owner of the given token ID. * `to` - Target address that will receive the token. * `tokenId` - Token ID to be transferred. * `_data` - Optional data to send along with the call. * * Returns whether the call correctly returned the expected magic value. */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns ( bytes4 retval ) { return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { _revert(TransferToNonERC721ReceiverImplementer.selector); } assembly { revert(add(32, reason), mload(reason)) } } } // ============================================================= // MINT OPERATIONS // ============================================================= /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event for each mint. */ function _mint(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (quantity == 0) _revert(MintZeroQuantity.selector); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // `balance` and `numberMinted` have a maximum limit of 2**64. // `tokenId` has a maximum limit of 2**256. unchecked { // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS; if (toMasked == 0) _revert(MintToZeroAddress.selector); uint256 end = startTokenId + quantity; uint256 tokenId = startTokenId; do { assembly { // Emit the `Transfer` event. log4( 0, // Start of data (0, since no data). 0, // End of data (0, since no data). _TRANSFER_EVENT_SIGNATURE, // Signature. 0, // `address(0)`. toMasked, // `to`. tokenId // `tokenId`. ) } // The `!=` check ensures that large values of `quantity` // that overflows uint256 will make the loop run out of gas. } while (++tokenId != end); _currentIndex = end; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * This function is intended for efficient minting only during contract creation. * * It emits only one {ConsecutiveTransfer} as defined in * [ERC2309](https://eips.ethereum.org/EIPS/eip-2309), * instead of a sequence of {Transfer} event(s). * * Calling this function outside of contract creation WILL make your contract * non-compliant with the ERC721 standard. * For full ERC721 compliance, substituting ERC721 {Transfer} event(s) with the ERC2309 * {ConsecutiveTransfer} event is only permissible during contract creation. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {ConsecutiveTransfer} event. */ function _mintERC2309(address to, uint256 quantity) internal virtual { uint256 startTokenId = _currentIndex; if (to == address(0)) _revert(MintToZeroAddress.selector); if (quantity == 0) _revert(MintZeroQuantity.selector); if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) _revert(MintERC2309QuantityExceedsLimit.selector); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are unrealistic due to the above check for `quantity` to be below the limit. unchecked { // Updates: // - `balance += quantity`. // - `numberMinted += quantity`. // // We can directly add to the `balance` and `numberMinted`. _packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1); // Updates: // - `address` to the owner. // - `startTimestamp` to the timestamp of minting. // - `burned` to `false`. // - `nextInitialized` to `quantity == 1`. _packedOwnerships[startTokenId] = _packOwnershipData( to, _nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0) ); emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to); _currentIndex = startTokenId + quantity; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * See {_mint}. * * Emits a {Transfer} event for each mint. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { _mint(to, quantity); unchecked { if (to.code.length != 0) { uint256 end = _currentIndex; uint256 index = end - quantity; do { if (!_checkContractOnERC721Received(address(0), to, index++, _data)) { _revert(TransferToNonERC721ReceiverImplementer.selector); } } while (index < end); // Reentrancy protection. if (_currentIndex != end) _revert(bytes4(0)); } } } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal virtual { _safeMint(to, quantity, ''); } // ============================================================= // APPROVAL OPERATIONS // ============================================================= /** * @dev Equivalent to `_approve(to, tokenId, false)`. */ function _approve(address to, uint256 tokenId) internal virtual { _approve(to, tokenId, false); } /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the * zero address clears previous approvals. * * Requirements: * * - `tokenId` must exist. * * Emits an {Approval} event. */ function _approve( address to, uint256 tokenId, bool approvalCheck ) internal virtual { address owner = ownerOf(tokenId); if (approvalCheck && _msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { _revert(ApprovalCallerNotOwnerNorApproved.selector); } _tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); } // ============================================================= // BURN OPERATIONS // ============================================================= /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId); address from = address(uint160(prevOwnershipPacked)); (uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId); if (approvalCheck) { // The nested ifs save around 20+ gas over a compound boolean condition. if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A())) if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner. assembly { if approvedAddress { // This is equivalent to `delete _tokenApprovals[tokenId]`. sstore(approvedAddressSlot, 0) } } // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as `tokenId` would have to be 2**256. unchecked { // Updates: // - `balance -= 1`. // - `numberBurned += 1`. // // We can directly decrement the balance, and increment the number burned. // This is equivalent to `packed -= 1; packed += 1 << _BITPOS_NUMBER_BURNED;`. _packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1; // Updates: // - `address` to the last owner. // - `startTimestamp` to the timestamp of burning. // - `burned` to `true`. // - `nextInitialized` to `true`. _packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) ); // If the next slot may not have been initialized (i.e. `nextInitialized == false`) . if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) { uint256 nextTokenId = tokenId + 1; // If the next slot's address is zero and not burned (i.e. packed value is zero). if (_packedOwnerships[nextTokenId] == 0) { // If the next slot is within bounds. if (nextTokenId != _currentIndex) { // Initialize the next slot to maintain correctness for `ownerOf(tokenId + 1)`. _packedOwnerships[nextTokenId] = prevOwnershipPacked; } } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } // ============================================================= // EXTRA DATA OPERATIONS // ============================================================= /** * @dev Directly sets the extra data for the ownership data `index`. */ function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual { uint256 packed = _packedOwnerships[index]; if (packed == 0) _revert(OwnershipNotInitializedForExtraData.selector); uint256 extraDataCasted; // Cast `extraData` with assembly to avoid redundant masking. assembly { extraDataCasted := extraData } packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA); _packedOwnerships[index] = packed; } /** * @dev Called during each token transfer to set the 24bit `extraData` field. * Intended to be overridden by the cosumer contract. * * `previousExtraData` - the value of `extraData` before transfer. * * 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, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _extraData( address from, address to, uint24 previousExtraData ) internal view virtual returns (uint24) {} /** * @dev Returns the next extra data for the packed ownership data. * The returned result is shifted into position. */ function _nextExtraData( address from, address to, uint256 prevOwnershipPacked ) private view returns (uint256) { uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA); return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA; } // ============================================================= // OTHER OPERATIONS // ============================================================= /** * @dev Returns the message sender (defaults to `msg.sender`). * * If you are writing GSN compatible contracts, you need to override this function. */ function _msgSenderERC721A() internal view virtual returns (address) { return msg.sender; } /** * @dev Converts a uint256 to its ASCII string decimal representation. */ function _toString(uint256 value) internal pure virtual returns (string memory str) { assembly { // The maximum value of a uint256 contains 78 digits (1 byte per digit), but // we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned. // We will need 1 word for the trailing zeros padding, 1 word for the length, // and 3 words for a maximum of 78 digits. Total: 5 * 0x20 = 0xa0. let m := add(mload(0x40), 0xa0) // Update the free memory pointer to allocate. mstore(0x40, m) // Assign the `str` to the end. str := sub(m, 0x20) // Zeroize the slot after the string. mstore(str, 0) // Cache the end of the memory to calculate the length later. let end := str // We write the string from rightmost digit to leftmost digit. // The following is essentially a do-while loop that also handles the zero case. // prettier-ignore for { let temp := value } 1 {} { str := sub(str, 1) // Write the character to the pointer. // The ASCII index of the '0' character is 48. mstore8(str, add(48, mod(temp, 10))) // Keep dividing `temp` until zero. temp := div(temp, 10) // prettier-ignore if iszero(temp) { break } } let length := sub(end, str) // Move the pointer 32 bytes leftwards to make room for the length. str := sub(str, 0x20) // Store the length. mstore(str, length) } } /** * @dev For more efficient reverts. */ function _revert(bytes4 errorSelector) internal pure { assembly { mstore(0x00, errorSelector) revert(0x00, 0x04) } } }
/MagnetErc721aCsrRecipientIsContract.sol
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import { MagnetErc721aBase } from "../MagnetErc721aBase.sol"; /// @title MagnetErc721aCsrRecipientIsContract /// @dev register magnet erc721a contract as csr recipient interface ITurnstile { function register(address _recipient) external returns(uint256); function withdraw(uint256 _tokenId, address payable _recipient, uint256 _amount) external returns (uint256); function getTokenId(address _smartContract) external view returns (uint256); function balances(uint256 _tokenId) external view returns (uint256); } abstract contract MagnetErc721aCsrRecipientIsContract is MagnetErc721aBase { ITurnstile private immutable _turnstile; constructor(address _turnstileAddr) { _turnstile = ITurnstile(_turnstileAddr); _turnstile.register(address(this)); } function _releaseCsrFees() private { uint256 tokenId_ = _turnstile.getTokenId(address(this)); uint256 amount_ = _turnstile.balances(tokenId_); if(amount_ > 0) { address payable recipient_ = payable(address(this)); _turnstile.withdraw(tokenId_, recipient_, amount_); } } /// @notice to be called to release all csr fees accrued by this contract, fees will be added to contract balance function releaseCsrFees() external { _releaseCsrFees(); } /// @notice to be called to ditribute contract revenues to all payees - only callable by owner function releaseAll() public virtual override onlyOwner { _releaseCsrFees(); super.releaseAll(); } }
/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.0; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1, "Math: mulDiv overflow"); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // ā `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // ā `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } }
/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^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}. */ interface IERC165 { /** * @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. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
/contracts/token/ERC20/extensions/IERC20Permit.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (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. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `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. */ function approve(address spender, uint256 amount) external returns (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. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
/contracts/interfaces/IERC2981.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC2981.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard. * * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal * support for royalty payments across all NFT marketplaces and ecosystem participants. * * _Available since v4.5._ */ interface IERC2981 is IERC165 { /** * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of * exchange. The royalty amount is denominated and should be paid in that same unit of exchange. */ function royaltyInfo( uint256 tokenId, uint256 salePrice ) external view returns (address receiver, uint256 royaltyAmount); }
/contracts/finance/PaymentSplitter.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. The distribution of shares is set at the * time of contract deployment and can't be updated thereafter. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Getter for the amount of payee's releasable Ether. */ function releasable(address account) public view returns (uint256) { uint256 totalReceived = address(this).balance + totalReleased(); return _pendingPayment(account, totalReceived, released(account)); } /** * @dev Getter for the amount of payee's releasable `token` tokens. `token` should be the address of an * IERC20 contract. */ function releasable(IERC20 token, address account) public view returns (uint256) { uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); return _pendingPayment(account, totalReceived, released(token, account)); } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 payment = releasable(account); require(payment != 0, "PaymentSplitter: account is not due payment"); // _totalReleased is the sum of all values in _released. // If "_totalReleased += payment" does not overflow, then "_released[account] += payment" cannot overflow. _totalReleased += payment; unchecked { _released[account] += payment; } Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 payment = releasable(token, account); require(payment != 0, "PaymentSplitter: account is not due payment"); // _erc20TotalReleased[token] is the sum of all values in _erc20Released[token]. // If "_erc20TotalReleased[token] += payment" does not overflow, then "_erc20Released[token][account] += payment" // cannot overflow. _erc20TotalReleased[token] += payment; unchecked { _erc20Released[token][account] += payment; } SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } }
/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) pragma solidity ^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. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed 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. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { 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) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
/
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import { PaymentSplitter } from "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import { IERC2981, IERC165 } from "@openzeppelin/contracts/interfaces/IERC2981.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Strings } from "@openzeppelin/contracts/utils/Strings.sol"; import { ERC721AQueryable, IERC721A, ERC721A } from "../../lib/ERC721A/contracts/extensions/ERC721AQueryable.sol"; interface IEventhub { function emitMintedEvent() external; function emitStartingIndexSetEvent() external; function emitSetActionEvent() external; } interface IERC4906 { event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId); } contract MagnetErc721aBase is Ownable, ERC721AQueryable, IERC4906, IERC2981, PaymentSplitter { using Strings for uint256; struct Metadata { string baseURI; string previewURI; string cid; } struct PublicSale { uint256 price; uint256 start; } struct Royalty { uint256 feeBps; address recipient; } uint256 public immutable MAX_SUPPLY; string public PROVENANCE_HASH = ""; uint256 public startingIndexBlock; uint256 public startingIndex; Metadata public metadata; PublicSale public publicSale; Royalty public royalty; bool public paused; uint256 private immutable _teamLength; /// revealStrategy has 3 states: (1: auto reveal) _ (2: restricted manual reveal) _ (3: unrestricted manual reveal) uint256 public revealStrategy; uint256 private constant AUTO_REVEAL_STRATEGY = 1; /// owner will trigger reveal process uint256 private constant RESTRICTED_MANUAL_REVEAL_STRATEGY = 2; /// community will trigger reveal process uint256 private constant UNRESTRICTED_MANUAL_REVEAL_STRATEGY = 3; IEventhub internal immutable eventhub; error NotAllowed(); error SalesPaused(); error SaleHasNotStarted(); error MaxSupplyExceeded(); error InsufficientFunds(); error PublicSaleHasStarted(); error StartingIndexSet(); error StartingIndexBlockNotSet(); error TokenNotFound(); error InvalidParameter(); constructor( string memory _name, string memory _symbol, address[] memory _team, uint256[] memory _teamShares, Royalty memory _royalty, PublicSale memory _publicSale, Metadata memory _metadata, string memory _provenanceHash, uint256 _revealStrategy, uint256 _maxSupply, address _eventhubAddr ) ERC721A(_name, _symbol) PaymentSplitter(_team, _teamShares) { royalty = _royalty; // if royalty.recipient is null address, // creator has opted in to send royalties to this contract if(royalty.recipient == address(0)) { royalty.recipient = address(this); } publicSale = _publicSale; metadata = _metadata; _teamLength = _team.length; revealStrategy = _revealStrategy; PROVENANCE_HASH = _provenanceHash; MAX_SUPPLY = _maxSupply; eventhub = IEventhub(_eventhubAddr); } modifier onlyEoa() { if (tx.origin != msg.sender) revert NotAllowed(); _; } modifier live() { if (paused) revert SalesPaused(); _; } /// @notice public sale mint function /// @param _quantity number of nfts to mint function mintPublicSale(uint256 _quantity) external payable onlyEoa live { if(publicSale.start > block.timestamp) revert SaleHasNotStarted(); uint256 mintedSupply_ = _mintedSalableSupply(); uint256 maxSalableSupply_ = _maxSalableSupply(); if(mintedSupply_ + _quantity > maxSalableSupply_) revert MaxSupplyExceeded(); if(publicSale.price * _quantity > msg.value) revert InsufficientFunds(); _mint(msg.sender, _quantity); _postPublicMint(); } /// @notice update public sale start time before public sale starts - only callable by owner /// @param _saleStartTime new timestamp function setPublicSaleStartTime(uint256 _saleStartTime) public virtual onlyOwner { if(publicSale.start < block.timestamp) revert PublicSaleHasStarted(); publicSale.start = _saleStartTime; eventhub.emitSetActionEvent(); } /// @notice update public sale price before public sale starts - only callable by owner /// @param _salePrice new sale price function setPublicSalePrice(uint256 _salePrice) external onlyOwner { if(publicSale.start < block.timestamp) revert PublicSaleHasStarted(); publicSale.price = _salePrice; eventhub.emitSetActionEvent(); } /// @notice update reveal strategy before starting index is set - only callable by owner /// @param _revealStrategy new state of revealStrategy - possible values: (1: auto reveal) - (2: restricted manual reveal) - (3: unrestricted manual reveal) function setRevealStrategy(uint256 _revealStrategy) external onlyOwner { if(startingIndex != 0) revert StartingIndexSet(); if(_revealStrategy < AUTO_REVEAL_STRATEGY || _revealStrategy > UNRESTRICTED_MANUAL_REVEAL_STRATEGY) revert InvalidParameter(); revealStrategy = _revealStrategy; eventhub.emitSetActionEvent(); } /// @notice pause/resume sales - only callable by owner /// @param _paused new state of sales function setPaused(bool _paused) external onlyOwner { paused = _paused; eventhub.emitSetActionEvent(); } /// @notice update base uri - only callable by owner /// @param _newBaseURI new base uri function setBaseUri(string memory _newBaseURI) external onlyOwner { metadata.baseURI = _newBaseURI; if(startingIndex != 0) { emit BatchMetadataUpdate(_startTokenId(), MAX_SUPPLY); } eventhub.emitSetActionEvent(); } /// @notice set the starting index of the nft collection after startingIndexBlock has been set - only callable by owner if revealStrategy is set to 2 function setStartingIndex() public { if(startingIndex != 0) revert StartingIndexSet(); if(startingIndexBlock == 0) revert StartingIndexBlockNotSet(); if(revealStrategy == RESTRICTED_MANUAL_REVEAL_STRATEGY && msg.sender != owner()) revert NotAllowed(); _setStartingIndex(); } /// @notice set starting index block - to be used in emergency situation - only callable by owner function emergencySetStartingIndexBlock() public onlyOwner { if(startingIndex != 0) revert StartingIndexSet(); // set the startingIndexBlock with the previous block number startingIndexBlock = block.number - 1; // if revealStrategy is set to 1 (auto reveal), set the starting index right away if(revealStrategy == AUTO_REVEAL_STRATEGY) { _setStartingIndex(); } } /// @dev set the startingIndex using a pseudo random number between 1 & MAX_SUPPLY (weak entropy combined with offchain hidden metadata before reveal) function _setStartingIndex() private { startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number - startingIndexBlock > 255) { startingIndex = uint256(blockhash(block.number - 1)) % MAX_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex + 1; } eventhub.emitStartingIndexSetEvent(); emit BatchMetadataUpdate(_startTokenId(), MAX_SUPPLY); } /// @dev hook called afer public mint, if last token is minted, set starting index block, if reveal is automated, trigger reveal process function _postPublicMint() private { uint256 maxSalableSupply_ = _maxSalableSupply(); uint256 mintedSalableSupply_ = _mintedSalableSupply(); if(startingIndexBlock == 0 && (maxSalableSupply_ == mintedSalableSupply_)) { // set the startingIndexBlock with the previous block number startingIndexBlock = block.number - 1; // if revealStrategy is set to 1 (auto reveal), set the starting index right away if(revealStrategy == AUTO_REVEAL_STRATEGY) { _setStartingIndex(); } } _postMint(); } /// @dev hook called after mint, used for emiting event through event hub function _postMint() internal { eventhub.emitMintedEvent(); } /// @dev return max salable supply function _maxSalableSupply() internal view virtual returns(uint256) { return MAX_SUPPLY; } /// @dev return minted salable supply function _mintedSalableSupply() internal view virtual returns(uint256) { return super._totalMinted(); } /// @notice returns a token uri for the given initial id /// @param _initialId tokenId function tokenURI(uint256 _initialId) public view virtual override(IERC721A, ERC721A) returns (string memory) { if(_exists(_initialId) == false) revert TokenNotFound(); if(startingIndex == 0) { return metadata.previewURI; } //compute the final token id using the starting index string memory finalId_ = ( (_initialId + startingIndex) % MAX_SUPPLY ).toString(); return string(abi.encodePacked(metadata.baseURI, metadata.cid, "/final_id_", finalId_, ".json")); } /// @notice returns total minted nfts function totalMinted() external view returns (uint256) { return super._totalMinted(); } function supportsInterface(bytes4 _interfaceId) public view virtual override(IERC721A, ERC721A, IERC165) returns (bool) { return ( _interfaceId == 0x49064906 || // ERC165 interface ID for ERC4906 _interfaceId == type(IERC2981).interfaceId || ERC721A.supportsInterface(_interfaceId) || super.supportsInterface(_interfaceId) ); } function royaltyInfo(uint256, uint256 _salePrice) external view virtual override returns (address receiver, uint256 royaltyAmount) { return (royalty.recipient, (_salePrice * royalty.feeBps) / 10_000); } /// @notice update royalty recipient - only callable by owner /// @param _recipient new recipient function setRoyaltyRecipient(address _recipient) external onlyOwner { if(_recipient == address(0)) revert InvalidParameter(); royalty.recipient = _recipient; eventhub.emitSetActionEvent(); } /// @notice update royalty bps - only callable by owner /// @param _royaltyBps new royalty bps function setRoyaltyBps(uint256 _royaltyBps) external onlyOwner { royalty.feeBps = _royaltyBps; eventhub.emitSetActionEvent(); } /// @notice to be called to ditribute contract revenues to all payees - only callable by owner function releaseAll() public virtual onlyOwner { for(uint256 i = 0 ; i < _teamLength ; i++) { address account_ = payee(i); uint256 payment_ = releasable(account_); if(payment_ > 0) { super.release(payable(account_)); } } } /// @notice release funds for a payee - only callable by payee or owner function release(address payable _account) public virtual override { if(msg.sender != owner() && msg.sender != _account) revert NotAllowed(); uint256 payment_ = releasable(_account); if(payment_ > 0) { super.release(_account); } } /// @dev overrides the `_startTokenId` function from ERC721A to start mint at token id 1 instead of 0 function _startTokenId() internal view virtual override returns (uint256) { return 1; } }
Compiler Settings
{"remappings":[],"optimizer":{"runs":200,"enabled":true},"metadata":{"bytecodeHash":"ipfs"},"libraries":{},"evmVersion":"paris","compilationTarget":{"DraftCollection.sol":"DraftCollection"}}
Contract ABI
[{"type":"constructor","stateMutability":"nonpayable","inputs":[{"type":"address[]","name":"_team","internalType":"address[]"},{"type":"uint256[]","name":"_teamShares","internalType":"uint256[]"},{"type":"tuple","name":"_royalty","internalType":"struct MagnetErc721aBase.Royalty","components":[{"type":"uint256","name":"feeBps","internalType":"uint256"},{"type":"address","name":"recipient","internalType":"address"}]},{"type":"tuple","name":"_publicSale","internalType":"struct MagnetErc721aBase.PublicSale","components":[{"type":"uint256","name":"price","internalType":"uint256"},{"type":"uint256","name":"start","internalType":"uint256"}]},{"type":"tuple","name":"_metadata","internalType":"struct MagnetErc721aBase.Metadata","components":[{"type":"string","name":"baseURI","internalType":"string"},{"type":"string","name":"previewURI","internalType":"string"},{"type":"string","name":"cid","internalType":"string"}]},{"type":"string","name":"_provenanceHash","internalType":"string"},{"type":"uint256","name":"_revealStrategy","internalType":"uint256"},{"type":"uint256","name":"_maxSupply","internalType":"uint256"}]},{"type":"error","name":"ApprovalCallerNotOwnerNorApproved","inputs":[]},{"type":"error","name":"ApprovalQueryForNonexistentToken","inputs":[]},{"type":"error","name":"BalanceQueryForZeroAddress","inputs":[]},{"type":"error","name":"InsufficientFunds","inputs":[]},{"type":"error","name":"InvalidParameter","inputs":[]},{"type":"error","name":"InvalidQueryRange","inputs":[]},{"type":"error","name":"MaxSupplyExceeded","inputs":[]},{"type":"error","name":"MintERC2309QuantityExceedsLimit","inputs":[]},{"type":"error","name":"MintToZeroAddress","inputs":[]},{"type":"error","name":"MintZeroQuantity","inputs":[]},{"type":"error","name":"NotAllowed","inputs":[]},{"type":"error","name":"OwnerQueryForNonexistentToken","inputs":[]},{"type":"error","name":"OwnershipNotInitializedForExtraData","inputs":[]},{"type":"error","name":"PublicSaleHasStarted","inputs":[]},{"type":"error","name":"SaleHasNotStarted","inputs":[]},{"type":"error","name":"SalesPaused","inputs":[]},{"type":"error","name":"StartingIndexBlockNotSet","inputs":[]},{"type":"error","name":"StartingIndexSet","inputs":[]},{"type":"error","name":"TokenNotFound","inputs":[]},{"type":"error","name":"TransferCallerNotOwnerNorApproved","inputs":[]},{"type":"error","name":"TransferFromIncorrectOwner","inputs":[]},{"type":"error","name":"TransferToNonERC721ReceiverImplementer","inputs":[]},{"type":"error","name":"TransferToZeroAddress","inputs":[]},{"type":"error","name":"URIQueryForNonexistentToken","inputs":[]},{"type":"event","name":"Approval","inputs":[{"type":"address","name":"owner","internalType":"address","indexed":true},{"type":"address","name":"approved","internalType":"address","indexed":true},{"type":"uint256","name":"tokenId","internalType":"uint256","indexed":true}],"anonymous":false},{"type":"event","name":"ApprovalForAll","inputs":[{"type":"address","name":"owner","internalType":"address","indexed":true},{"type":"address","name":"operator","internalType":"address","indexed":true},{"type":"bool","name":"approved","internalType":"bool","indexed":false}],"anonymous":false},{"type":"event","name":"BatchMetadataUpdate","inputs":[{"type":"uint256","name":"_fromTokenId","internalType":"uint256","indexed":false},{"type":"uint256","name":"_toTokenId","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"ConsecutiveTransfer","inputs":[{"type":"uint256","name":"fromTokenId","internalType":"uint256","indexed":true},{"type":"uint256","name":"toTokenId","internalType":"uint256","indexed":false},{"type":"address","name":"from","internalType":"address","indexed":true},{"type":"address","name":"to","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"ERC20PaymentReleased","inputs":[{"type":"address","name":"token","internalType":"contract IERC20","indexed":true},{"type":"address","name":"to","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"OwnershipTransferred","inputs":[{"type":"address","name":"previousOwner","internalType":"address","indexed":true},{"type":"address","name":"newOwner","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"PayeeAdded","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false},{"type":"uint256","name":"shares","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"PaymentReceived","inputs":[{"type":"address","name":"from","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"PaymentReleased","inputs":[{"type":"address","name":"to","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Transfer","inputs":[{"type":"address","name":"from","internalType":"address","indexed":true},{"type":"address","name":"to","internalType":"address","indexed":true},{"type":"uint256","name":"tokenId","internalType":"uint256","indexed":true}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"MAX_SUPPLY","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"PROVENANCE_HASH","inputs":[]},{"type":"function","stateMutability":"payable","outputs":[],"name":"approve","inputs":[{"type":"address","name":"to","internalType":"address"},{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"balanceOf","inputs":[{"type":"address","name":"owner","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"emergencySetStartingIndexBlock","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"tuple","name":"ownership","internalType":"struct IERC721A.TokenOwnership","components":[{"type":"address","name":"addr","internalType":"address"},{"type":"uint64","name":"startTimestamp","internalType":"uint64"},{"type":"bool","name":"burned","internalType":"bool"},{"type":"uint24","name":"extraData","internalType":"uint24"}]}],"name":"explicitOwnershipOf","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"tuple[]","name":"","internalType":"struct IERC721A.TokenOwnership[]","components":[{"type":"address","name":"addr","internalType":"address"},{"type":"uint64","name":"startTimestamp","internalType":"uint64"},{"type":"bool","name":"burned","internalType":"bool"},{"type":"uint24","name":"extraData","internalType":"uint24"}]}],"name":"explicitOwnershipsOf","inputs":[{"type":"uint256[]","name":"tokenIds","internalType":"uint256[]"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"getApproved","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"isApprovedForAll","inputs":[{"type":"address","name":"owner","internalType":"address"},{"type":"address","name":"operator","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"baseURI","internalType":"string"},{"type":"string","name":"previewURI","internalType":"string"},{"type":"string","name":"cid","internalType":"string"}],"name":"metadata","inputs":[]},{"type":"function","stateMutability":"payable","outputs":[],"name":"mintPublicSale","inputs":[{"type":"uint256","name":"_quantity","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"name","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"owner","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"ownerOf","inputs":[{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"paused","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"payee","inputs":[{"type":"uint256","name":"index","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"price","internalType":"uint256"},{"type":"uint256","name":"start","internalType":"uint256"}],"name":"publicSale","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"releasable","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"releasable","inputs":[{"type":"address","name":"token","internalType":"contract IERC20"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"release","inputs":[{"type":"address","name":"_account","internalType":"address payable"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"release","inputs":[{"type":"address","name":"token","internalType":"contract IERC20"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"releaseAll","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"releaseCsrFees","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"released","inputs":[{"type":"address","name":"token","internalType":"contract IERC20"},{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"released","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceOwnership","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"revealStrategy","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"feeBps","internalType":"uint256"},{"type":"address","name":"recipient","internalType":"address"}],"name":"royalty","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"receiver","internalType":"address"},{"type":"uint256","name":"royaltyAmount","internalType":"uint256"}],"name":"royaltyInfo","inputs":[{"type":"uint256","name":"","internalType":"uint256"},{"type":"uint256","name":"_salePrice","internalType":"uint256"}]},{"type":"function","stateMutability":"payable","outputs":[],"name":"safeTransferFrom","inputs":[{"type":"address","name":"from","internalType":"address"},{"type":"address","name":"to","internalType":"address"},{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"payable","outputs":[],"name":"safeTransferFrom","inputs":[{"type":"address","name":"from","internalType":"address"},{"type":"address","name":"to","internalType":"address"},{"type":"uint256","name":"tokenId","internalType":"uint256"},{"type":"bytes","name":"_data","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setApprovalForAll","inputs":[{"type":"address","name":"operator","internalType":"address"},{"type":"bool","name":"approved","internalType":"bool"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setBaseUri","inputs":[{"type":"string","name":"_newBaseURI","internalType":"string"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setPaused","inputs":[{"type":"bool","name":"_paused","internalType":"bool"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setPublicSalePrice","inputs":[{"type":"uint256","name":"_salePrice","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setPublicSaleStartTime","inputs":[{"type":"uint256","name":"_saleStartTime","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setRevealStrategy","inputs":[{"type":"uint256","name":"_revealStrategy","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setRoyaltyBps","inputs":[{"type":"uint256","name":"_royaltyBps","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setRoyaltyRecipient","inputs":[{"type":"address","name":"_recipient","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setStartingIndex","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"shares","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"startingIndex","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"startingIndexBlock","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"supportsInterface","inputs":[{"type":"bytes4","name":"_interfaceId","internalType":"bytes4"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"symbol","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"string","name":"","internalType":"string"}],"name":"tokenURI","inputs":[{"type":"uint256","name":"_initialId","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256[]","name":"","internalType":"uint256[]"}],"name":"tokensOfOwner","inputs":[{"type":"address","name":"owner","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256[]","name":"","internalType":"uint256[]"}],"name":"tokensOfOwnerIn","inputs":[{"type":"address","name":"owner","internalType":"address"},{"type":"uint256","name":"start","internalType":"uint256"},{"type":"uint256","name":"stop","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalMinted","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalReleased","inputs":[{"type":"address","name":"token","internalType":"contract IERC20"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalReleased","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalShares","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalSupply","inputs":[]},{"type":"function","stateMutability":"payable","outputs":[],"name":"transferFrom","inputs":[{"type":"address","name":"from","internalType":"address"},{"type":"address","name":"to","internalType":"address"},{"type":"uint256","name":"tokenId","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"transferOwnership","inputs":[{"type":"address","name":"newOwner","internalType":"address"}]},{"type":"receive","stateMutability":"payable"}]
Contract Creation Code
0x608060405234801561001057600080fd5b50600080546001600160a01b03191633179055612cd4806100326000396000f3fe6080604052600436106101ac5760003560e01c8063a21a23e4116100ec578063ca0affb61161008a578063daf484e011610064578063daf484e0146104d3578063dc311dd314610500578063e30c397814610530578063e5ce16821461054e57600080fd5b8063ca0affb61461046b578063cb6317971461048b578063cd508f90146104ab57600080fd5b8063be8a0eaf116100c6578063be8a0eaf146103d9578063be999705146103f9578063bec4c08c1461040c578063c3f909d41461042c57600080fd5b8063a21a23e41461038f578063b0c793a5146103a4578063b590c362146103b957600080fd5b806340d6bb821161015957806367d0b6171161013357806367d0b617146102fb57806379ba509714610328578063882f2f271461033d5780638da5cb5b1461035d57600080fd5b806340d6bb821461029157806355e146e5146102bb5780636775dad5146102db57600080fd5b806329c938881161018a57806329c938881461023c5780633e9aeeb9146102515780633fa952251461027157600080fd5b80630ae09540146101b15780630f9b4ccd146101d35780631885c74b14610206575b600080fd5b3480156101bd57600080fd5b506101d16101cc366004612789565b61057e565b005b3480156101df57600080fd5b506101f36101ee3660046127c9565b610937565b6040519081526020015b60405180910390f35b34801561021257600080fd5b506101f36102213660046127fe565b6001600160a01b03166000908152600c602052604090205490565b34801561024857600080fd5b506005546101f3565b34801561025d57600080fd5b506101d161026c3660046127fe565b610b84565b34801561027d57600080fd5b506101d161028c366004612819565b610c59565b34801561029d57600080fd5b506102a6606481565b60405163ffffffff90911681526020016101fd565b3480156102c757600080fd5b506101d16102d6366004612904565b610d63565b3480156102e757600080fd5b506101d16102f6366004612789565b610ee6565b34801561030757600080fd5b5061031b6103163660046127fe565b610fff565b6040516101fd919061295b565b34801561033457600080fd5b506101d161106b565b34801561034957600080fd5b506101d161035836600461296e565b6110f6565b34801561036957600080fd5b506000546001600160a01b03165b6040516001600160a01b0390911681526020016101fd565b34801561039b57600080fd5b506101f3611472565b3480156103b057600080fd5b506006546101f3565b3480156103c557600080fd5b506101d16103d43660046127fe565b6115a6565b3480156103e557600080fd5b506101d16103f4366004612a1d565b6116e0565b6101d1610407366004612819565b61177c565b34801561041857600080fd5b506101d1610427366004612789565b61185f565b34801561043857600080fd5b506003546002546040805192835263ffffffff8083166020850152640100000000909204909116908201526060016101fd565b34801561047757600080fd5b506101d1610486366004612a50565b611a27565b34801561049757600080fd5b506101d16104a6366004612789565b611b54565b3480156104b757600080fd5b506104c0606481565b60405161ffff90911681526020016101fd565b3480156104df57600080fd5b506101f36104ee366004612819565b6000908152600a602052604090205490565b34801561050c57600080fd5b5061052061051b366004612819565b611e64565b6040516101fd9493929190612a7b565b34801561053c57600080fd5b506001546001600160a01b0316610377565b34801561055a57600080fd5b5061056e610569366004612819565b611f38565b60405190151581526020016101fd565b60008281526007602052604090205482906001600160a01b0316806105be5760405163c5171ee960e01b8152600481018390526024015b60405180910390fd5b6001600160a01b03811633146105e95760405163ba8ddccb60e01b81523360048201526024016105b5565b60045460ff161561060d5760405163769dd35360e11b815260040160405180910390fd5b61061684611f38565b1561063757604051630fc3c22760e01b8152600481018590526024016105b5565b600084815260076020526040812060020154905b6000868152600760205260409020600401548110156106ce576000868152600760205260408120600401805460089291908490811061068c5761068c612ae4565b60009182526020808320909101546001600160a01b031683528281019390935260409182018120898252909252812055806106c681612b10565b91505061064b565b50600085815260076020526040812080546001600160a01b03199081168255600182018054909116905560028101829055600381018290559061071460048301826126d2565b505060005b336000908152600d602052604090205481101561082b57336000908152600d60205260408120805461074d90600190612b29565b8154811061075d5761075d612ae4565b9060005260206000200154905086600d6000336001600160a01b03166001600160a01b0316815260200190815260200160002083815481106107a1576107a1612ae4565b90600052602060002001540361081857336000908152600d602052604090208054829190849081106107d5576107d5612ae4565b6000918252602080832090910192909255338152600d9091526040902080548061080157610801612b3c565b600190038181906000526020600020016000905590555b508061082381612b10565b915050610719565b5061085381604051806080016040528060498152602001612c566049913960055491906120ef565b6005556040516000906001600160a01b0386169083908381818185875af1925050503d80600081146108a1576040519150601f19603f3d011682016040523d82523d6000602084013e6108a6565b606091505b50509050806108ec576040517f83a8db300000000000000000000000000000000000000000000000000000000081526001600160a01b03861660048201526024016105b5565b604080518381526001600160a01b038716602082015287917f30713f049b61cac5dbace7470a6dd8a7b946b0e30cecbc7862ad545a455746f4910160405180910390a2505050505050565b60045460009060ff161561095e5760405163769dd35360e11b815260040160405180910390fd5b6000838152600760205260409020546001600160a01b03166109965760405163c5171ee960e01b8152600481018490526024016105b5565b336000908152600860209081526040808320868452909152812054908190036109f4576040517f79bfd401000000000000000000000000000000000000000000000000000000008152600481018590523360248201526044016105b5565b6003546000858152600760205260409020600201541015610a44576040517f4fac3f92000000000000000000000000000000000000000000000000000000008152600481018590526024016105b5565b606463ffffffff84161115610a94576040517fe060d06a00000000000000000000000000000000000000000000000000000000815263ffffffff84166004820152606460248201526044016105b5565b6000610aa1826001612b52565b9050600080610ab28833898661211b565b6040805160208082018590524382840152336060830152608082018c905263ffffffff8b1660a0808401919091528351808403909101815260c0909201909252805191012091935091506000838152600a602090815260408083209390935533808352600882528383208b8452825291839020869055825185815290810184905263ffffffff8916818401524360608201529151909189918b917f65769084608bbbde03705b08957a4ae0ed2d43beebccdc40efc44e04572d54e2919081900360800190a450925050505b9392505050565b610b8c61219b565b6001600160a01b038116610c085760405162461bcd60e51b815260206004820152602e60248201527f56657269666961626c654f776e65723a206e6577206f776e657220697320746860448201527f65207a65726f206164647265737300000000000000000000000000000000000060648201526084016105b5565b600180546001600160a01b0319166001600160a01b0383811691821790925560008054604051929316917f30d9bb2ab9975cb23485b35ce7c78c9de53418dd40dee93649eede5334d785199190a350565b6000818152600760205260409020546001600160a01b031680610c925760405163c5171ee960e01b8152600481018390526024016105b5565b6000828152600760205260409020600101546001600160a01b03163314610cee576040517fe642e27c000000000000000000000000000000000000000000000000000000008152600481018390523360248201526044016105b5565b6000828152600760209081526040918290208054336001600160a01b03199182168117835560019092018054909116905582516001600160a01b03851681529182015283917f0ad91d4f1dad6617777c51e1896f809535f7418ee84a281ee8985379adc03c0491015b60405180910390a25050565b610d6b61219b565b6000610d768261221b565b6000818152600b60205260409020549091506001600160a01b031680610dc8576040517f4dca4f7d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6000828152600b6020526040812080546001600160a01b03191690555b600954811015610e9f578260098281548110610e0357610e03612ae4565b906000526020600020015403610e8d576009805460009190610e2790600190612b29565b81548110610e3757610e37612ae4565b906000526020600020015490508060098381548110610e5857610e58612ae4565b6000918252602090912001556009805480610e7557610e75612b3c565b60019003818190600052602060002001600090559055505b80610e9781612b10565b915050610de5565b50806001600160a01b03167f9cac1d03510eca9570740f4f89693a80f06c95e6a82c11d811d8718909734e2584604051610ed99190612b88565b60405180910390a2505050565b60008281526007602052604090205482906001600160a01b031680610f215760405163c5171ee960e01b8152600481018390526024016105b5565b6001600160a01b0381163314610f4c5760405163ba8ddccb60e01b81523360048201526024016105b5565b60045460ff1615610f705760405163769dd35360e11b815260040160405180910390fd5b6000848152600760205260409020600101546001600160a01b03848116911614610ff95760008481526007602090815260409182902060010180546001600160a01b0319166001600160a01b038716908117909155915191825285917f2635544a5a006e95198d03920107347eba61748b097bf5b43294b105eb6496eb91015b60405180910390a25b50505050565b6001600160a01b0381166000908152600d602090815260409182902080548351818402810184019094528084526060939283018282801561105f57602002820191906000526020600020905b81548152602001906001019080831161104b575b50505050509050919050565b6001546001600160a01b031633146110eb5760405162461bcd60e51b815260206004820152602760248201527f56657269666961626c654f776e65723a206d757374206265207375676765737460448201527f64206f776e65720000000000000000000000000000000000000000000000000060648201526084016105b5565b6110f43361224b565b565b60045460ff161561111a5760405163769dd35360e11b815260040160405180910390fd5b60005a9050600080600061112e86866122a5565b9250925092506000856040015163ffffffff1667ffffffffffffffff81111561115957611159612832565b604051908082528060200260200182016040528015611182578160200160208202803683370190505b50905060005b866040015163ffffffff168110156111f65760408051602081018590529081018290526060016040516020818303038152906040528051906020012060001c8282815181106111d9576111d9612ae4565b6020908102919091010152806111ee81612b10565b915050611188565b506000838152600a60209081526040808320839055908801516060890151915190929081907f1fe543e3000000000000000000000000000000000000000000000000000000009061124d9089908890602401612b96565b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff00000000000000000000000000000000000000000000000000000000909416939093179092526004805460ff1916600117905590519091506000906001600160a01b038516906112d7908490612bdb565b6000604051808303816000865af19150503d8060008114611314576040519150601f19603f3d011682016040523d82523d6000602084013e611319565b606091505b50506004805460ff191690556000868152600760205260408120600301805492935060019290919061134c908490612b52565b909155506000905061135e8b3a612470565b60008781526007602052604090206002015490915081111561139357604051631e9acf1760e31b815260040160405180910390fd5b600086815260076020526040812060020180548392906113b4908490612b29565b909155505060008a8152600b60209081526040808320546001600160a01b03168352600c909152812080548392906113ed908490612b52565b90915550506000868152600760209081526040918290206002015482518c81529182018b90529181018390526060810182905283151560808201526001600160a01b0387169088907f194edce908d11e0681e7dcd7e923d8650aef0ff3a940728b9564fa715ce159439060a00160405180910390a35050505050505050505050505050565b60045460009060ff16156114995760405163769dd35360e11b815260040160405180910390fd5b600680549060006114a983612b10565b90915550506006546040805160a081018252338152600060208083018281528385018381526060850184815286518581528085018852608087019081528886526007855296909420855181546001600160a01b03199081166001600160a01b03928316178355935160018301805490951691161790925551600282015591516003830155925180519293919261154592600485019201906126f3565b5050336000818152600d6020908152604080832080546001810182559084529282902090920185905590519182528392507f1d3015d7ba850fa198dc7b1a3f5d42779313a681035f77c8c03764c61005518d910160405180910390a2905090565b60045460ff16156115ca5760405163769dd35360e11b815260040160405180910390fd5b336000908152600c60205260409020548015806115e8575060055481115b1561160657604051631e9acf1760e31b815260040160405180910390fd5b336000908152600c602052604081205560055461162390826124d9565b6005556040516000906001600160a01b0384169083908381818185875af1925050503d8060008114611671576040519150601f19603f3d011682016040523d82523d6000602084013e611676565b606091505b505090508061169857604051631e9acf1760e31b815260040160405180910390fd5b604080516001600160a01b0385168152602081018490527fd17a3527d6c16addb6519a2d4590393947f89c70456327e6d5f9ff1f914836f791015b60405180910390a1505050565b6116e861219b565b6040805160808101825263ffffffff848116808352908416602080840182905283850188905260006060948501526002805467ffffffffffffffff19168417640100000000840217905560038890556004805460ff19169055845188815290810192909252928101929092527fc988e672d04bd0c75eec462a50636443cd6d831f254ee1bda3f01962458734b991016116d3565b60045460ff16156117a05760405163769dd35360e11b815260040160405180910390fd5b6000818152600760205260409020546001600160a01b03166117d85760405163c5171ee960e01b8152600481018290526024016105b5565b6000818152600760205260409020600201546117f481346124e5565b60008381526007602052604090206002015560055461181390346124e5565b6005556000828152600760209081526040918290206002015482518481529182015283917f1ced9348ff549fceab2ac57cd3a9de38edaaab274b725ee82c23e8fc8c4eec7a9101610d57565b60008281526007602052604090205482906001600160a01b03168061189a5760405163c5171ee960e01b8152600481018390526024016105b5565b6001600160a01b03811633146118c55760405163ba8ddccb60e01b81523360048201526024016105b5565b60045460ff16156118e95760405163769dd35360e11b815260040160405180910390fd5b60008481526007602052604090206004015460631901611938576040517f5e994139000000000000000000000000000000000000000000000000000000008152600481018590526024016105b5565b6001600160a01b0383166000908152600860209081526040808320878452909152902054156119a5576040517ffe4a59b8000000000000000000000000000000000000000000000000000000008152600481018590526001600160a01b03841660248201526044016105b5565b60008481526007602090815260408083206004018054600180820183559185528385200180546001600160a01b0319166001600160a01b03891690811790915580855260088452828520898652845293829020555191825285917f4e5aab67fb6878a7c5437d638d002992f2b503107c053f38483f6b29494874939101610ff0565b611a2f61219b565b6000611a3a8261221b565b6000818152600b60205260409020549091506001600160a01b031615611a97576040517f7780d1b80000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024016105b5565b60008190526001600160a01b0380841690821614611ac857604051637a85635f60e11b815260040160405180910390fd5b6000818152600b602052604080822080546001600160a01b0319166001600160a01b0387169081179091556009805460018101825593527f6e1540171b6c0c960b71a7020d9f60077f6af931a8bbf590da0223dacf75c7af909201839055517f9ae6a2bd93db569a1ff9229041b434b3516879070a7446fb6ecf2ec2f101b96e90610ed9908590612b88565b60008281526007602052604090205482906001600160a01b031680611b8f5760405163c5171ee960e01b8152600481018390526024016105b5565b6001600160a01b0381163314611bba5760405163ba8ddccb60e01b81523360048201526024016105b5565b60045460ff1615611bde5760405163769dd35360e11b815260040160405180910390fd5b611be784611f38565b15611c0857604051630fc3c22760e01b8152600481018590526024016105b5565b6001600160a01b03831660009081526008602090815260408083208784529091528120549003611c6f576040517fa2cdd6c00000000000000000000000000000000000000000000000000000000081526001600160a01b03841660048201526024016105b5565b6001600160a01b038316600090815260086020908152604080832087845282528083208390556007825280832060040180548251818502810185019093528083529192909190830182828015611cee57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311611cd0575b5050505050905060005b8151811015611e1e57600086815260076020526040902060040180546001600160a01b038716919083908110611d3057611d30612ae4565b6000918252602090912001546001600160a01b031603611e0c5760008260018451611d5b9190612b29565b81518110611d6b57611d6b612ae4565b6020026020010151905080600760008981526020019081526020016000206004018381548110611d9d57611d9d612ae4565b600091825260208083209190910180546001600160a01b0319166001600160a01b039490941693909317909255888152600790915260409020600401805480611de857611de8612b3c565b600082815260209020810160001990810180546001600160a01b0319169055019055505b80611e1681612b10565b915050611cf8565b506040516001600160a01b038516815285907f5274c432b5877b38569ae9babd361f86e4b34d0f36aef7f6c61cbba5f185cee19060200160405180910390a25050505050565b600081815260076020526040812054819081906060906001600160a01b0316611ea35760405163c5171ee960e01b8152600481018690526024016105b5565b600085815260076020908152604091829020805460028201546003830154600490930180548651818702810187019097528087526001600160a01b0390931695919490928391830182828015611f2257602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311611f04575b5050505050905093509350935093509193509193565b6000818152600760209081526040808320815160a08101835281546001600160a01b039081168252600183015416818501526002820154818401526003820154606082015260048201805484518187028101870190955280855286959294608086019390929190830182828015611fd857602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311611fba575b505050505081525050905060005b8160800151518110156120e55760005b6009548110156120d257600061209b6009838154811061201857612018612ae4565b90600052602060002001548560800151858151811061203957612039612ae4565b602002602001015188600860008960800151898151811061205c5761205c612ae4565b60200260200101516001600160a01b03166001600160a01b0316815260200190815260200160002060008b81526020019081526020016000205461211b565b506000818152600a6020526040902054909150156120bf5750600195945050505050565b50806120ca81612b10565b915050611ff6565b50806120dd81612b10565b915050611fe6565b5060009392505050565b600081848411156121135760405162461bcd60e51b81526004016105b59190612bf7565b505050900390565b60008060008686868660405160200161215694939291909384526001600160a01b039290921660208401526040830152606082015260800190565b60408051601f1981840301815282825280516020918201208184019a909a528282018a9052815180840383018152606090930190915281519101209795505050505050565b6000546001600160a01b031633146110f45760405162461bcd60e51b815260206004820152602860248201527f56657269666961626c654f776e65723a2073656e646572206973206e6f74207460448201527f6865206f776e657200000000000000000000000000000000000000000000000060648201526084016105b5565b60008160405160200161222e9190612b88565b604051602081830303815290604052805190602001209050919050565b600180546001600160a01b0319908116909155600080546001600160a01b03848116938216841783556040519116929183917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60008060006122b7856000015161221b565b6000818152600b60205260409020549093506001600160a01b0390811690841681146122f657604051637a85635f60e11b815260040160405180910390fd5b6001600160a01b038116612339576040517f69b906d0000000000000000000000000000000000000000000000000000000008152600481018590526024016105b5565b6040808701518151602081018790529182015260600160408051601f1981840301815291815281516020928301206000818152600a90935290822054909450908190036123b2576040517f58a396ff00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b612424848760200151886000015189606001518a6040015160408051602081018790529081018490526001600160a01b03831660608201526080810185905263ffffffff821660a082015260009060c00160405160208183030381529060405280519060200120905095945050505050565b811461245c576040517f7ef0d66200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b612465876124f1565b925050509250925092565b6000805a60025461248890869063ffffffff16612b52565b6124929190612b29565b61249c9084612c2a565b6002549091506000906124c290640100000000900463ffffffff1664e8d4a51000612c2a565b90506124ce8183612b52565b925050505b92915050565b6000610b7d8284612b29565b6000610b7d8284612b52565b600061250082600001516125db565b61254c5760405162461bcd60e51b815260206004820152601a60248201527f7075626c6963206b6579206973206e6f74206f6e20637572766500000000000060448201526064016105b5565b61255982602001516125db565b6125a55760405162461bcd60e51b815260206004820152601560248201527f67616d6d61206973206e6f74206f6e206375727665000000000000000000000060448201526064016105b5565b600382602001516040516020016125bd929190612c41565b60408051601f19818403018152919052805160209091012092915050565b80516000906401000003d019116126345760405162461bcd60e51b815260206004820152601260248201527f696e76616c696420782d6f7264696e617465000000000000000000000000000060448201526064016105b5565b60208201516401000003d0191161268d5760405162461bcd60e51b815260206004820152601260248201527f696e76616c696420792d6f7264696e617465000000000000000000000000000060448201526064016105b5565b60208201516401000003d01990800982516126a7906126ae565b1492915050565b6000806401000003d01980848509840990506401000003d019600782089392505050565b50805460008255906000526020600020908101906126f09190612758565b50565b828054828255906000526020600020908101928215612748579160200282015b8281111561274857825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190612713565b50612754929150612758565b5090565b5b808211156127545760008155600101612759565b80356001600160a01b038116811461278457600080fd5b919050565b6000806040838503121561279c57600080fd5b823591506127ac6020840161276d565b90509250929050565b803563ffffffff8116811461278457600080fd5b6000806000606084860312156127de57600080fd5b83359250602084013591506127f5604085016127b5565b90509250925092565b60006020828403121561281057600080fd5b610b7d8261276d565b60006020828403121561282b57600080fd5b5035919050565b634e487b7160e01b600052604160045260246000fd5b6040516060810167ffffffffffffffff8111828210171561286b5761286b612832565b60405290565b6040516080810167ffffffffffffffff8111828210171561286b5761286b612832565b600082601f8301126128a557600080fd5b6040516040810181811067ffffffffffffffff821117156128c8576128c8612832565b80604052508060408401858111156128df57600080fd5b845b818110156128f95780358352602092830192016128e1565b509195945050505050565b60006040828403121561291657600080fd5b610b7d8383612894565b600081518084526020808501945080840160005b8381101561295057815187529582019590820190600101612934565b509495945050505050565b602081526000610b7d6020830184612920565b60008082840361012081121561298357600080fd5b60a081121561299157600080fd5b612999612848565b6129a38686612894565b81526129b28660408701612894565b60208201526080858101356040830152909350609f19820112156129d557600080fd5b506129de612871565b60a0840135815260c084013560208201526129fb60e085016127b5565b6040820152612a0d610100850161276d565b6060820152809150509250929050565b600080600060608486031215612a3257600080fd5b83359250612a42602085016127b5565b91506127f5604085016127b5565b60008060608385031215612a6357600080fd5b612a6c8361276d565b91506127ac8460208501612894565b6000608082016001600160a01b038088168452602087818601528660408601526080606086015282865180855260a087019150828801945060005b81811015612ad4578551851683529483019491830191600101612ab6565b50909a9950505050505050505050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b600060018201612b2257612b22612afa565b5060010190565b818103818111156124d3576124d3612afa565b634e487b7160e01b600052603160045260246000fd5b808201808211156124d3576124d3612afa565b8060005b6002811015610ff9578151845260209384019390910190600101612b69565b604081016124d38284612b65565b828152604060208201526000612baf6040830184612920565b949350505050565b60005b83811015612bd2578181015183820152602001612bba565b50506000910152565b60008251612bed818460208701612bb7565b9190910192915050565b6020815260008251806020840152612c16816040850160208701612bb7565b601f01601f19169190910160400192915050565b80820281158282048414176124d3576124d3612afa565b82815260608101610b7d6020830184612b6556fe496e656666696369656e742062616c616e636520616d6f756e742c205265717565737465642076616c75652069732067726174686572207468616e20746f74616c2062616c616e6365a2646970667358221220f460e1a7757bcfef8ba90869283fba934346508f2ecf3e6d2fa4d174a8b1235664736f6c63430008120033
Deployed ByteCode
0x