Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
71
// Internal migration id used to specify that a contract has already been initialized. /
string constant private INITIALIZED_ID = "initialized";
string constant private INITIALIZED_ID = "initialized";
7,331
207
// ERC721A 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 264 - 1 (max value of uint64) of supply.- The maximum token ID cannot exceed 2256 - 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(); 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(); 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 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) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; // If not burned. if (packed & _BITMASK_BURNED == 0) { // 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, `curr` will not underflow. // // We can directly compare the packed value. // If the address is zero, packed will be zero. while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } /** * @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. * 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) public payable virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } _tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); } /** * @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(); 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) { return _startTokenId() <= tokenId && tokenId < _currentIndex && // If within bounds, _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned. } /** * @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); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); (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(); if (to == address(0)) revert TransferToZeroAddress(); _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; } } } } emit Transfer(from, to, tokenId); _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(); } } /** * @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(); } else { 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(); _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: // - `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) ); uint256 toMasked; uint256 end = startTokenId + quantity; // Use assembly to loop and emit the `Transfer` event for gas savings. // The duplicated `log4` removes an extra check and reduces stack juggling. // The assembly, together with the surrounding Solidity code, have been // delicately arranged to nudge the compiler into producing optimized opcodes. assembly { // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. toMasked := and(to, _BITMASK_ADDRESS) // 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`. startTokenId // `tokenId`. ) // The `iszero(eq(,))` check ensures that large values of `quantity` // that overflows uint256 will make the loop run out of gas. // The compiler will optimize the `iszero` away for performance. for { let tokenId := add(startTokenId, 1) } iszero(eq(tokenId, end)) { tokenId := add(tokenId, 1) } { // Emit the `Transfer` event. Similar to above. log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); _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(); if (quantity == 0) revert MintZeroQuantity(); if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit(); _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(); } } while (index < end); // Reentrancy protection. if (_currentIndex != end) revert(); } } } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal virtual { _safeMint(to, quantity, ''); } // ============================================================= // 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(); } _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(); 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) } }
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(); 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(); 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 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) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr) if (curr < _currentIndex) { uint256 packed = _packedOwnerships[curr]; // If not burned. if (packed & _BITMASK_BURNED == 0) { // 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, `curr` will not underflow. // // We can directly compare the packed value. // If the address is zero, packed will be zero. while (packed == 0) { packed = _packedOwnerships[--curr]; } return packed; } } } revert OwnerQueryForNonexistentToken(); } /** * @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. * 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) public payable virtual override { address owner = ownerOf(tokenId); if (_msgSenderERC721A() != owner) if (!isApprovedForAll(owner, _msgSenderERC721A())) { revert ApprovalCallerNotOwnerNorApproved(); } _tokenApprovals[tokenId].value = to; emit Approval(owner, to, tokenId); } /** * @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(); 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) { return _startTokenId() <= tokenId && tokenId < _currentIndex && // If within bounds, _packedOwnerships[tokenId] & _BITMASK_BURNED == 0; // and not burned. } /** * @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); if (address(uint160(prevOwnershipPacked)) != from) revert TransferFromIncorrectOwner(); (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(); if (to == address(0)) revert TransferToZeroAddress(); _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; } } } } emit Transfer(from, to, tokenId); _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(); } } /** * @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(); } else { 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(); _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: // - `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) ); uint256 toMasked; uint256 end = startTokenId + quantity; // Use assembly to loop and emit the `Transfer` event for gas savings. // The duplicated `log4` removes an extra check and reduces stack juggling. // The assembly, together with the surrounding Solidity code, have been // delicately arranged to nudge the compiler into producing optimized opcodes. assembly { // Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. toMasked := and(to, _BITMASK_ADDRESS) // 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`. startTokenId // `tokenId`. ) // The `iszero(eq(,))` check ensures that large values of `quantity` // that overflows uint256 will make the loop run out of gas. // The compiler will optimize the `iszero` away for performance. for { let tokenId := add(startTokenId, 1) } iszero(eq(tokenId, end)) { tokenId := add(tokenId, 1) } { // Emit the `Transfer` event. Similar to above. log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } if (toMasked == 0) revert MintToZeroAddress(); _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(); if (quantity == 0) revert MintZeroQuantity(); if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) revert MintERC2309QuantityExceedsLimit(); _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(); } } while (index < end); // Reentrancy protection. if (_currentIndex != end) revert(); } } } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal virtual { _safeMint(to, quantity, ''); } // ============================================================= // 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(); } _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(); 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) } }
3,709
169
// The new owner accept an ownership transfer.The new owner should remove `operator` role from previous owner and add for himself. /
function acceptOwnership() external { require(_msgSender() == newOwner, "IDO: CALLER_NO_NEW_OWNER"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); }
function acceptOwnership() external { require(_msgSender() == newOwner, "IDO: CALLER_NO_NEW_OWNER"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); }
64,316
62
// Burn strategy tokens to withdraw pool tokens. It can be called only when invested./to Recipient for the pool tokens/ return poolTokensObtained Amount of pool tokens obtained/The strategy tokens that the user burns need to have been transferred previously, using a batchable router.
function burn( address to
function burn( address to
23,567
11
// Modifiers to allow any combination of roles
modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED"); _; }
modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED"); _; }
23,011
190
// we have more B than A, sell some B
amount = looseB.sub(debtB); path = _getPath(tokenB, tokenA);
amount = looseB.sub(debtB); path = _getPath(tokenB, tokenA);
38,020
16
// overriding the virtual function in LzReceiver
function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
function _blockingLzReceive(uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload) internal virtual override {
32,751
620
// IBabylonGate Babylon Finance Interface for interacting with the Guestlists /
interface IBabylonGate { /* ============ Functions ============ */ function setGardenAccess( address _user, address _garden, uint8 _permission ) external returns (uint256); function setCreatorPermissions(address _user, bool _canCreate) external returns (uint256); function grantGardenAccessBatch( address _garden, address[] calldata _users, uint8[] calldata _perms ) external returns (bool); function maxNumberOfInvites() external view returns (uint256); function setMaxNumberOfInvites(uint256 _maxNumberOfInvites) external; function grantCreatorsInBatch(address[] calldata _users, bool[] calldata _perms) external returns (bool); function canCreate(address _user) external view returns (bool); function canJoinAGarden(address _garden, address _user) external view returns (bool); function canVoteInAGarden(address _garden, address _user) external view returns (bool); function canAddStrategiesInAGarden(address _garden, address _user) external view returns (bool); }
interface IBabylonGate { /* ============ Functions ============ */ function setGardenAccess( address _user, address _garden, uint8 _permission ) external returns (uint256); function setCreatorPermissions(address _user, bool _canCreate) external returns (uint256); function grantGardenAccessBatch( address _garden, address[] calldata _users, uint8[] calldata _perms ) external returns (bool); function maxNumberOfInvites() external view returns (uint256); function setMaxNumberOfInvites(uint256 _maxNumberOfInvites) external; function grantCreatorsInBatch(address[] calldata _users, bool[] calldata _perms) external returns (bool); function canCreate(address _user) external view returns (bool); function canJoinAGarden(address _garden, address _user) external view returns (bool); function canVoteInAGarden(address _garden, address _user) external view returns (bool); function canAddStrategiesInAGarden(address _garden, address _user) external view returns (bool); }
72,497
34
// If over vesting duration, all tokens vested
if (elapsedDays >= tokenGrant.vestingDuration*(30)) { uint256 remainingGrant = tokenGrant.amount-(tokenGrant.totalClaimed); return (tokenGrant.vestingDuration, remainingGrant); } else {
if (elapsedDays >= tokenGrant.vestingDuration*(30)) { uint256 remainingGrant = tokenGrant.amount-(tokenGrant.totalClaimed); return (tokenGrant.vestingDuration, remainingGrant); } else {
41,854
280
// Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`/params tokenId The ID of the token for which liquidity is being increased,/ amount0Desired The desired amount of token0 to be spent,/ amount1Desired The desired amount of token1 to be spent,/ amount0Min The minimum amount of token0 to spend, which serves as a slippage check,/ amount1Min The minimum amount of token1 to spend, which serves as a slippage check,/ deadline The time by which the transaction must be included to effect the change/ return liquidity The new liquidity amount as a result of the increase/ return amount0
function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 );
function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 );
27,333
160
// Attempts to verify a DS record's hash value against some data. digesttype The digest ID from the DS record. data The data to digest. digest The digest data to check against.return True iff the digest matches. /
function verifyDSHash(uint8 digesttype, bytes data, bytes digest) internal view returns (bool) { if (digests[digesttype] == address(0)) { return false; } return digests[digesttype].verify(data, digest.substring(4, digest.length - 4)); }
function verifyDSHash(uint8 digesttype, bytes data, bytes digest) internal view returns (bool) { if (digests[digesttype] == address(0)) { return false; } return digests[digesttype].verify(data, digest.substring(4, digest.length - 4)); }
8,381
3
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the benefit is lost if 'b' is also tested. See: https:github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) { return 0; }
if (a == 0) { return 0; }
4
28
// If the Presale is active do not accept incoming transactions
if (active) { revert(); }
if (active) { revert(); }
44,369
137
// Set the confirmation period after a vote has concluded. Only the contract owner may call this. The proposed duration must fallwithin sensible bounds (1 day to 2 weeks). /
function setConfirmationPeriod(uint duration) external onlyOwner
function setConfirmationPeriod(uint duration) external onlyOwner
49,888
91
// Description of the clock / solhint-disable-next-line func-name-mixedcase
function CLOCK_MODE() external view returns (string memory);
function CLOCK_MODE() external view returns (string memory);
27,350
37
// exposing the total reward amount for DApp
function reward_total() external constant returns (uint) { return ((coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total)); }
function reward_total() external constant returns (uint) { return ((coinIndex[horses.BTC].total) + (coinIndex[horses.ETH].total) + (coinIndex[horses.LTC].total)); }
8,484
37
// View the state of a given proposal. proposalId The id of the specified proposalreturn The state of the proposal Requirements: - Proposal must exist /
function state(uint256 proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "Invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.timestamp <= proposal.startTime) { return ProposalState.Pending; } else if (block.timestamp <= proposal.endTime) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= proposal.eta + timelock.viewGracePeriod()) { return ProposalState.Expired; } else { return ProposalState.Queued; } }
function state(uint256 proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "Invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.timestamp <= proposal.startTime) { return ProposalState.Pending; } else if (block.timestamp <= proposal.endTime) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= proposal.eta + timelock.viewGracePeriod()) { return ProposalState.Expired; } else { return ProposalState.Queued; } }
42,716
13
// View functions /
function MODULE_TYPE() external view returns(bytes32); function oneTokenCount() external view returns(uint256); function oneTokenAtIndex(uint256 index) external view returns(address); function isOneToken(address oneToken) external view returns(bool);
function MODULE_TYPE() external view returns(bytes32); function oneTokenCount() external view returns(uint256); function oneTokenAtIndex(uint256 index) external view returns(address); function isOneToken(address oneToken) external view returns(bool);
45,200
0
// `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrarycontract-specific code that enables us to report opaque error codes from upgradeable contracts. /
event Failure(uint256 error, uint256 info, uint256 detail);
event Failure(uint256 error, uint256 info, uint256 detail);
17,336
1,083
// Set our length and extra data, save the context.
ctx.length = _index; ctx.extraData = _extraData; _self.setContext(ctx);
ctx.length = _index; ctx.extraData = _extraData; _self.setContext(ctx);
65,853
9
// Modifier to ensure voter has voted
modifier haveVoted(address _to) { require(!voters[_to].voted, "Voter has already voted"); _; }
modifier haveVoted(address _to) { require(!voters[_to].voted, "Voter has already voted"); _; }
21,453
23
// transfer escrowed amount to domain
uint256 escrowAmount = domains[msg.sender].escrowedAmount; if(domain.drp.reactContract != address(0)){
uint256 escrowAmount = domains[msg.sender].escrowedAmount; if(domain.drp.reactContract != address(0)){
15,747
187
// The player is the current winner
_auctionInfo.topBidder = msg.sender; _auctionInfo.topBid = _maxBid;
_auctionInfo.topBidder = msg.sender; _auctionInfo.topBid = _maxBid;
1,393
142
// use if staking warmup is 0
IERC20(ASG).approve(stakingHelper, _amount); IStakingHelper(stakingHelper).stake(_amount, _recipient);
IERC20(ASG).approve(stakingHelper, _amount); IStakingHelper(stakingHelper).stake(_amount, _recipient);
30,201
274
// TODOeventAddress address of event controlling getNFT nftIndex unique index of getNFTorderTimeP timestamp passed on by ticket issuer of order time of database ticket twin (primary market getNFT)pricePaidP price of primary sale as passed on by ticket issuer/
function addNftMetaPrimary(address eventAddress, uint256 nftIndex, uint256 orderTimeP, uint256 pricePaidP) public virtual returns(bool success){ EventStruct storage c = allEventStructs[eventAddress]; c.amountNFTs++; c.ordersprimary[nftIndex] = OrdersPrimary({_nftIndex: nftIndex, _pricePaidP: pricePaidP, _orderTimeP: orderTimeP}); c.grossRevenuePrimary += pricePaidP; emit primaryMarketNFTSold(eventAddress, nftIndex, pricePaidP); return true; }
function addNftMetaPrimary(address eventAddress, uint256 nftIndex, uint256 orderTimeP, uint256 pricePaidP) public virtual returns(bool success){ EventStruct storage c = allEventStructs[eventAddress]; c.amountNFTs++; c.ordersprimary[nftIndex] = OrdersPrimary({_nftIndex: nftIndex, _pricePaidP: pricePaidP, _orderTimeP: orderTimeP}); c.grossRevenuePrimary += pricePaidP; emit primaryMarketNFTSold(eventAddress, nftIndex, pricePaidP); return true; }
20,803
60
// Approve or reject loan. Manager approve or reject loan. _loanId Loan Id. _approve `true` value indicates the approval and `false` indicates rejection. /
function approveOrRejectLoan(uint _loanId, bool _approve) external onlyByManager { address _userAddrs = loanIdToUser[_loanId]; for(uint256 i = 0; i < userInfo[_userAddrs].loanInfo.length ; i++) { if(userInfo[_userAddrs].loanInfo[i].loanId == _loanId){ if(_approve){ userInfo[_userAddrs].loanInfo[i].loanStatus = LnStatus.Approved; payable(_userAddrs).transfer(userInfo[_userAddrs].loanInfo[i].amount); contractBalance = contractBalance.sub(userInfo[_userAddrs].loanInfo[i].amount); } else{ userInfo[_userAddrs].loanInfo[i] = userInfo[_userAddrs].loanInfo[userInfo[_userAddrs].loanInfo.length.sub(1)]; // Copy last element to current element's position. userInfo[loanIdToUser[_loanId]].loanInfo.pop(); // Remove last element } for(uint256 j = 0; j < loanIdsOfPendingRequests.length; j++){ if(loanIdsOfPendingRequests[i] == _loanId){ loanIdsOfPendingRequests[i] = loanIdsOfPendingRequests[loanIdsOfPendingRequests.length.sub(1)]; // Copy last element to current element's position. loanIdsOfPendingRequests.pop(); // Remove last element } } } } emit ApproveOrRejectLoan(_loanId,_userAddrs, _approve); }
function approveOrRejectLoan(uint _loanId, bool _approve) external onlyByManager { address _userAddrs = loanIdToUser[_loanId]; for(uint256 i = 0; i < userInfo[_userAddrs].loanInfo.length ; i++) { if(userInfo[_userAddrs].loanInfo[i].loanId == _loanId){ if(_approve){ userInfo[_userAddrs].loanInfo[i].loanStatus = LnStatus.Approved; payable(_userAddrs).transfer(userInfo[_userAddrs].loanInfo[i].amount); contractBalance = contractBalance.sub(userInfo[_userAddrs].loanInfo[i].amount); } else{ userInfo[_userAddrs].loanInfo[i] = userInfo[_userAddrs].loanInfo[userInfo[_userAddrs].loanInfo.length.sub(1)]; // Copy last element to current element's position. userInfo[loanIdToUser[_loanId]].loanInfo.pop(); // Remove last element } for(uint256 j = 0; j < loanIdsOfPendingRequests.length; j++){ if(loanIdsOfPendingRequests[i] == _loanId){ loanIdsOfPendingRequests[i] = loanIdsOfPendingRequests[loanIdsOfPendingRequests.length.sub(1)]; // Copy last element to current element's position. loanIdsOfPendingRequests.pop(); // Remove last element } } } } emit ApproveOrRejectLoan(_loanId,_userAddrs, _approve); }
36,638
20
// ------------------------------------------------------------------------ Token owner can approve for spender to transferFrom(...) tokens from the token owner's account https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; }
function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; }
1,128
37
// Struct used to initialize WETH -> deposit swaps
struct Weth2Deposit { address router; address[] path; }
struct Weth2Deposit { address router; address[] path; }
82,579
11
// solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // solhint-disable reason-string /
import { IERC721Receiver } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "../utils/BaseRouter.sol"; // $$\ $$\ $$\ $$\ $$\ // $$ | $$ | \__| $$ | $$ | // $$$$$$\ $$$$$$$\ $$\ $$$$$$\ $$$$$$$ |$$\ $$\ $$\ $$$$$$\ $$$$$$$\ // \_$$ _| $$ __$$\ $$ |$$ __$$\ $$ __$$ |$$ | $$ | $$ |$$ __$$\ $$ __$$\ // $$ | $$ | $$ |$$ |$$ | \__|$$ / $$ |$$ | $$ | $$ |$$$$$$$$ |$$ | $$ | // $$ |$$\ $$ | $$ |$$ |$$ | $$ | $$ |$$ | $$ | $$ |$$ ____|$$ | $$ | // \$$$$ |$$ | $$ |$$ |$$ | \$$$$$$$ |\$$$$$\$$$$ |\$$$$$$$\ $$$$$$$ | // \____/ \__| \__|\__|\__| \_______| \_____\____/ \_______|\_______/ contract DynamicAccount is AccountCore, BaseRouter { /*/////////////////////////////////////////////////////////////// Constants //////////////////////////////////////////////////////////////*/ bytes32 public constant EXTENSION_ADMIN_ROLE = keccak256("EXTENSION_ADMIN_ROLE"); address public immutable defaultExtension; /*/////////////////////////////////////////////////////////////// Constructor and Initializer //////////////////////////////////////////////////////////////*/ receive() external payable override(Router, AccountCore) {} constructor(IEntryPoint _entrypoint, address _defaultExtension) AccountCore(_entrypoint) { defaultExtension = _defaultExtension; } function initialize(address _defaultAdmin) public override initializer { _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); _setupRole(EXTENSION_ADMIN_ROLE, _defaultAdmin); } /*/////////////////////////////////////////////////////////////// Public Overrides //////////////////////////////////////////////////////////////*/ /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IBaseRouter).interfaceId || // interfaceId == type(IRouter).interfaceId || interfaceId == type(IERC1155Receiver).interfaceId || interfaceId == type(IERC721Receiver).interfaceId; } /// @dev Returns the extension implementation address stored in router, for the given function. function getImplementationForFunction(bytes4 _functionSelector) public view virtual override returns (address) { address impl = getExtensionForFunction(_functionSelector).implementation; return impl != address(0) ? impl : defaultExtension; } /*/////////////////////////////////////////////////////////////// Internal overrides //////////////////////////////////////////////////////////////*/ /// @dev Returns whether a extension can be set in the given execution context. function _canSetExtension() internal view virtual override returns (bool) { return _hasRole(EXTENSION_ADMIN_ROLE, msg.sender); } }
import { IERC721Receiver } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "../utils/BaseRouter.sol"; // $$\ $$\ $$\ $$\ $$\ // $$ | $$ | \__| $$ | $$ | // $$$$$$\ $$$$$$$\ $$\ $$$$$$\ $$$$$$$ |$$\ $$\ $$\ $$$$$$\ $$$$$$$\ // \_$$ _| $$ __$$\ $$ |$$ __$$\ $$ __$$ |$$ | $$ | $$ |$$ __$$\ $$ __$$\ // $$ | $$ | $$ |$$ |$$ | \__|$$ / $$ |$$ | $$ | $$ |$$$$$$$$ |$$ | $$ | // $$ |$$\ $$ | $$ |$$ |$$ | $$ | $$ |$$ | $$ | $$ |$$ ____|$$ | $$ | // \$$$$ |$$ | $$ |$$ |$$ | \$$$$$$$ |\$$$$$\$$$$ |\$$$$$$$\ $$$$$$$ | // \____/ \__| \__|\__|\__| \_______| \_____\____/ \_______|\_______/ contract DynamicAccount is AccountCore, BaseRouter { /*/////////////////////////////////////////////////////////////// Constants //////////////////////////////////////////////////////////////*/ bytes32 public constant EXTENSION_ADMIN_ROLE = keccak256("EXTENSION_ADMIN_ROLE"); address public immutable defaultExtension; /*/////////////////////////////////////////////////////////////// Constructor and Initializer //////////////////////////////////////////////////////////////*/ receive() external payable override(Router, AccountCore) {} constructor(IEntryPoint _entrypoint, address _defaultExtension) AccountCore(_entrypoint) { defaultExtension = _defaultExtension; } function initialize(address _defaultAdmin) public override initializer { _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); _setupRole(EXTENSION_ADMIN_ROLE, _defaultAdmin); } /*/////////////////////////////////////////////////////////////// Public Overrides //////////////////////////////////////////////////////////////*/ /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IBaseRouter).interfaceId || // interfaceId == type(IRouter).interfaceId || interfaceId == type(IERC1155Receiver).interfaceId || interfaceId == type(IERC721Receiver).interfaceId; } /// @dev Returns the extension implementation address stored in router, for the given function. function getImplementationForFunction(bytes4 _functionSelector) public view virtual override returns (address) { address impl = getExtensionForFunction(_functionSelector).implementation; return impl != address(0) ? impl : defaultExtension; } /*/////////////////////////////////////////////////////////////// Internal overrides //////////////////////////////////////////////////////////////*/ /// @dev Returns whether a extension can be set in the given execution context. function _canSetExtension() internal view virtual override returns (bool) { return _hasRole(EXTENSION_ADMIN_ROLE, msg.sender); } }
27,980
92
// Division precision.
uint256 private precision = 1e18;
uint256 private precision = 1e18;
24,567
19
// 0x31: Retrieval of at least one of the sources timed out.
RetrievalTimeout,
RetrievalTimeout,
12,319
169
// The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. Reverts upon any failure borrower The borrower of this cToken to be liquidated cTokenCollateral The market in which to seize collateral from the borrower /
function liquidateBorrow(address borrower, address cTokenCollateral)
function liquidateBorrow(address borrower, address cTokenCollateral)
27,397
124
// Delete from the mapping
delete frax_pools[pool_address];
delete frax_pools[pool_address];
25,300
20
// Ether Escrow legible as Bill of Sale with arbitration procedure. /
contract BillOfSale { using SafeMath for uint256; address public buyer; address public seller; address public arbiter; string public descr; uint256 public price; uint256 private arbiterFee; uint256 private buyerAward; uint256 private sellerAward; enum State { Created, Confirmed, Disputed, Resolved, Completed } State public state; event Confirmed(address indexed buyer, address indexed this); event Disputed(); event Resolved(address indexed this, address indexed buyer, address indexed seller); event Completed(address indexed this, address indexed seller); /** * @dev Sets the transaction values for `descr`, `price`, `buyer`, `seller`, 'arbiter', 'arbiterFee'. All six of * these values are immutable: they can only be set once during construction and reflect essential deal terms. */ constructor( string memory _descr, uint256 _price, address _buyer, address _seller, address _arbiter, uint256 _arbiterFee) public { descr = _descr; price = _price; seller = _seller; buyer = _buyer; arbiter = _arbiter; arbiterFee = _arbiterFee; } /** * @dev Throws if called by any account other than buyer. */ modifier onlyBuyer() { require(msg.sender == buyer); _; } /** * @dev Throws if called by any account other than buyer or seller. */ modifier onlyBuyerOrSeller() { require( msg.sender == buyer || msg.sender == seller); _; } /** * @dev Throws if called by any account other than arbiter. */ modifier onlyArbiter() { require(msg.sender == arbiter); _; } /** * @dev Throws if contract called in State other than one associated for function. */ modifier inState(State _state) { require(state == _state); _; } /** * @dev Buyer confirms transaction with Ether 'price' as message value; * Ether is then locked for transfer to seller after buyer confirms receipt * or ADR if dispute initiated by buyer or seller. */ function confirmPurchase() public payable onlyBuyer inState(State.Created) { require(price == msg.value); state = State.Confirmed; emit Confirmed(buyer, address(this)); } /** * @dev Buyer confirms receipt from seller; * Ether 'price' is transferred to seller. */ function confirmReceipt() public onlyBuyer inState(State.Confirmed) { state = State.Completed; seller.transfer(address(this).balance); emit Completed(address(this), seller); } /** * @dev Buyer or seller can initiate dispute related to locked Ether 'price' after buyer confirms purchase, * placing 'price' transfer and split of value into arbiter control. * For example, buyer might refuse or unduly delay to confirm receipt after seller transaction, or, on other hand, * despite buyer's disatisfaction with seller transaction, seller might demand buyer confirm receipt and release 'price'. */ function initiateDispute() public onlyBuyerOrSeller inState(State.Confirmed) { state = State.Disputed; emit Disputed(); } /** * @dev Arbiter can resolve dispute and claim reward by entering in split of 'price' value * minus their 'arbiter fee' set at construction. */ function resolveDispute(uint256 _buyerAward, uint256 _sellerAward) public onlyArbiter inState(State.Disputed) { state = State.Resolved; buyerAward = _buyerAward; sellerAward = _sellerAward; buyer.transfer(buyerAward); seller.transfer(sellerAward); arbiter.transfer(arbiterFee); emit Resolved(address(this), buyer, seller); } }
contract BillOfSale { using SafeMath for uint256; address public buyer; address public seller; address public arbiter; string public descr; uint256 public price; uint256 private arbiterFee; uint256 private buyerAward; uint256 private sellerAward; enum State { Created, Confirmed, Disputed, Resolved, Completed } State public state; event Confirmed(address indexed buyer, address indexed this); event Disputed(); event Resolved(address indexed this, address indexed buyer, address indexed seller); event Completed(address indexed this, address indexed seller); /** * @dev Sets the transaction values for `descr`, `price`, `buyer`, `seller`, 'arbiter', 'arbiterFee'. All six of * these values are immutable: they can only be set once during construction and reflect essential deal terms. */ constructor( string memory _descr, uint256 _price, address _buyer, address _seller, address _arbiter, uint256 _arbiterFee) public { descr = _descr; price = _price; seller = _seller; buyer = _buyer; arbiter = _arbiter; arbiterFee = _arbiterFee; } /** * @dev Throws if called by any account other than buyer. */ modifier onlyBuyer() { require(msg.sender == buyer); _; } /** * @dev Throws if called by any account other than buyer or seller. */ modifier onlyBuyerOrSeller() { require( msg.sender == buyer || msg.sender == seller); _; } /** * @dev Throws if called by any account other than arbiter. */ modifier onlyArbiter() { require(msg.sender == arbiter); _; } /** * @dev Throws if contract called in State other than one associated for function. */ modifier inState(State _state) { require(state == _state); _; } /** * @dev Buyer confirms transaction with Ether 'price' as message value; * Ether is then locked for transfer to seller after buyer confirms receipt * or ADR if dispute initiated by buyer or seller. */ function confirmPurchase() public payable onlyBuyer inState(State.Created) { require(price == msg.value); state = State.Confirmed; emit Confirmed(buyer, address(this)); } /** * @dev Buyer confirms receipt from seller; * Ether 'price' is transferred to seller. */ function confirmReceipt() public onlyBuyer inState(State.Confirmed) { state = State.Completed; seller.transfer(address(this).balance); emit Completed(address(this), seller); } /** * @dev Buyer or seller can initiate dispute related to locked Ether 'price' after buyer confirms purchase, * placing 'price' transfer and split of value into arbiter control. * For example, buyer might refuse or unduly delay to confirm receipt after seller transaction, or, on other hand, * despite buyer's disatisfaction with seller transaction, seller might demand buyer confirm receipt and release 'price'. */ function initiateDispute() public onlyBuyerOrSeller inState(State.Confirmed) { state = State.Disputed; emit Disputed(); } /** * @dev Arbiter can resolve dispute and claim reward by entering in split of 'price' value * minus their 'arbiter fee' set at construction. */ function resolveDispute(uint256 _buyerAward, uint256 _sellerAward) public onlyArbiter inState(State.Disputed) { state = State.Resolved; buyerAward = _buyerAward; sellerAward = _sellerAward; buyer.transfer(buyerAward); seller.transfer(sellerAward); arbiter.transfer(arbiterFee); emit Resolved(address(this), buyer, seller); } }
573
11
// Mint function uses OpenZeppelin's mint functions to ensure safety. Requires ensure that minting is 1-10. Does not allow to mint beyond the gift buffer.
function mint(uint256 mintAmount) public payable nonReentrant { require(currentState == ContractState.PUBLIC, "Public sale not started"); require(mintAmount > 0, "Can't mint 0"); require(mintAmount + _tokenIdCounter.current() <= MAX_SUPPLY - giftsRemaining() - SNAPSHOT, "Minting more than max supply"); require(mintAmount < 11, "Max mint is 10"); require(msg.value == PRICE * mintAmount, "Wrong price"); for(uint i = 0; i < mintAmount; i++) { uint256 tokenId = _tokenIdCounter.current() + SNAPSHOT; _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); } }
function mint(uint256 mintAmount) public payable nonReentrant { require(currentState == ContractState.PUBLIC, "Public sale not started"); require(mintAmount > 0, "Can't mint 0"); require(mintAmount + _tokenIdCounter.current() <= MAX_SUPPLY - giftsRemaining() - SNAPSHOT, "Minting more than max supply"); require(mintAmount < 11, "Max mint is 10"); require(msg.value == PRICE * mintAmount, "Wrong price"); for(uint i = 0; i < mintAmount; i++) { uint256 tokenId = _tokenIdCounter.current() + SNAPSHOT; _tokenIdCounter.increment(); _safeMint(msg.sender, tokenId); } }
31,184
259
// Modify minting limit
function change_MAX_Bones(uint new_MAX) public onlyOwner returns(uint)
function change_MAX_Bones(uint new_MAX) public onlyOwner returns(uint)
37,000
63
// Case 5: Unforeseen stuff
else { revert("Fatal Error: Case5 unforeseen."); }
else { revert("Fatal Error: Case5 unforeseen."); }
28,715
95
// Transfers all the LP tokens to the Dev address for Migration process
stakingToken.safeTransfer( msg.sender, stakingToken.balanceOf(address(this)) );
stakingToken.safeTransfer( msg.sender, stakingToken.balanceOf(address(this)) );
11,806
40
// Allocate 32% of all tokens to Foundation
foundationTokens = div(mul(totalSupply, 32), 100); balances[foundationReserve] = foundationTokens;
foundationTokens = div(mul(totalSupply, 32), 100); balances[foundationReserve] = foundationTokens;
44,987
0
// Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { /** * @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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, 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: * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` 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 sender, address recipient, uint256 amount) external returns (bool); /** * @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); }
interface IERC20 { /** * @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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, 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: * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` 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 sender, address recipient, uint256 amount) external returns (bool); /** * @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); }
23,294
272
// IVariety interface/Simon Fremaux (@dievardump)
interface IVariety is IERC721 { /// @notice mint `seeds.length` token(s) to `to` using `seeds` /// @param to token recipient /// @param seeds each token seed function plant(address to, bytes32[] memory seeds) external returns (uint256); /// @notice this function returns the seed associated to a tokenId /// @param tokenId to get the seed of function getTokenSeed(uint256 tokenId) external view returns (bytes32); /// @notice This function allows an owner to ask for a seed update /// this can be needed because although I test the contract as much as possible, /// it might be possible that one token does not render because the seed creates /// error or even "out of gas" computation. That's why this would allow an owner /// in such case, to request for a seed change that will then be triggered by Sower /// @param tokenId id to regenerate seed for function requestSeedChange(uint256 tokenId) external; /// @notice This function allows Sower to answer to a seed change request /// in the event where a seed would produce errors of rendering /// 1) this function can only be called by Sower if the token owner /// asked for a new seed /// 2) this function will only be called if there is a rendering error /// or, Vitalik Buterin forbid, a duplicate /// @param tokenId id to regenerate seed for function changeSeedAfterRequest(uint256 tokenId) external; }
interface IVariety is IERC721 { /// @notice mint `seeds.length` token(s) to `to` using `seeds` /// @param to token recipient /// @param seeds each token seed function plant(address to, bytes32[] memory seeds) external returns (uint256); /// @notice this function returns the seed associated to a tokenId /// @param tokenId to get the seed of function getTokenSeed(uint256 tokenId) external view returns (bytes32); /// @notice This function allows an owner to ask for a seed update /// this can be needed because although I test the contract as much as possible, /// it might be possible that one token does not render because the seed creates /// error or even "out of gas" computation. That's why this would allow an owner /// in such case, to request for a seed change that will then be triggered by Sower /// @param tokenId id to regenerate seed for function requestSeedChange(uint256 tokenId) external; /// @notice This function allows Sower to answer to a seed change request /// in the event where a seed would produce errors of rendering /// 1) this function can only be called by Sower if the token owner /// asked for a new seed /// 2) this function will only be called if there is a rendering error /// or, Vitalik Buterin forbid, a duplicate /// @param tokenId id to regenerate seed for function changeSeedAfterRequest(uint256 tokenId) external; }
23,289
210
// Interface for the NFT Royalty Standard. A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universalsupport for royalty payments across all NFT marketplaces and ecosystem participants./
interface IERC2981 is IERC165 {
interface IERC2981 is IERC165 {
44,403
42
// If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); }
if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); }
3,666
104
// Variables used to parameterize behavior.
uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; address public slasher;
uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; address public slasher;
22,959
23
// ============== Minting ==============
function mintBatch( address[] calldata _to, uint256[][] calldata _ids, uint256[][] calldata _amounts
function mintBatch( address[] calldata _to, uint256[][] calldata _ids, uint256[][] calldata _amounts
1,367
180
// Allow a n token holder to mint a token with one of their n token's id tokenId Id to be minted /
function mintWithN(uint256 tokenId) public payable virtual nonReentrant { require(n.ownerOf(tokenId) == msg.sender, "NPass:INVALID_OWNER"); _safeMint(msg.sender, tokenId); }
function mintWithN(uint256 tokenId) public payable virtual nonReentrant { require(n.ownerOf(tokenId) == msg.sender, "NPass:INVALID_OWNER"); _safeMint(msg.sender, tokenId); }
5,138
28
// See {IERC721-approve}. /
function approve(address to, uint256 tokenId) public virtual override {
function approve(address to, uint256 tokenId) public virtual override {
28,219
5
// Lets trandfer LRC first.
require( lrcAddress.safeTransferFrom(msg.sender, address(this), amount), "TRANSFER_FAILURE" ); Stake storage user = users[msg.sender];
require( lrcAddress.safeTransferFrom(msg.sender, address(this), amount), "TRANSFER_FAILURE" ); Stake storage user = users[msg.sender];
48,746
72
// Batch mint tokens. Assign directly to _to[].
function mint(uint256 _id, address[] calldata _to, uint256[] calldata _quantities) external creatorOnly(_id) { for (uint256 i = 0; i < _to.length; ++i) { address to = _to[i]; uint256 quantity = _quantities[i]; // Grant the items to the caller balances[_id][to] = quantity.add(balances[_id][to]); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. emit TransferSingle(msg.sender, address(0x0), to, _id, quantity); if (to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, to, _id, quantity, ''); } } }
function mint(uint256 _id, address[] calldata _to, uint256[] calldata _quantities) external creatorOnly(_id) { for (uint256 i = 0; i < _to.length; ++i) { address to = _to[i]; uint256 quantity = _quantities[i]; // Grant the items to the caller balances[_id][to] = quantity.add(balances[_id][to]); // Emit the Transfer/Mint event. // the 0x0 source address implies a mint // It will also provide the circulating supply info. emit TransferSingle(msg.sender, address(0x0), to, _id, quantity); if (to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, to, _id, quantity, ''); } } }
23,430
61
// Returns the downcasted int24 from int256, reverting onoverflow (when the input is less than smallest int24 orgreater than largest int24). Counterpart to Solidity's `int24` operator. Requirements: - input must fit into 24 bits _Available since v4.7._ /
function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); }
function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); require(downcasted == value, "SafeCast: value doesn't fit in 24 bits"); }
30,776
177
// The total number of rewards issued.
uint256 count = _rewardMultipliers.length;
uint256 count = _rewardMultipliers.length;
1,100
103
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
EnumerableMap.UintToAddressMap private _tokenOwners;
22,507
49
// Gets a dial's weighted votes for each distribution period. dialIdDial identifier starting from 0.return voteHistoryList of weighted votes with the first distribution at index 0. /
function getDialVoteHistory(uint256 dialId) public view returns (HistoricVotes[] memory voteHistory)
function getDialVoteHistory(uint256 dialId) public view returns (HistoricVotes[] memory voteHistory)
64,135
0
// ERC1155标准的接口合约,实现了EIP1155的功能 /
interface IERC1155 is IERC165 { /** * @dev 单类代币转账事件 * 当`value`个`id`种类的代币被`operator`从`from`转账到`to`时释放. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev 批量代币转账事件 * ids和values为转账的代币种类和数量数组 */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev 批量授权事件 * 当`account`将所有代币授权给`operator`时释放 */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev 当`id`种类的代币的URI发生变化时释放,`value`为新的URI */ event URI(string value, uint256 indexed id); /** * @dev 持仓查询,返回`account`拥有的`id`种类的代币的持仓量 */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev 批量持仓查询,`accounts`和`ids`数组的长度要想等。 */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev 批量授权,将调用者的代币授权给`operator`地址。 * 释放{ApprovalForAll}事件. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev 批量授权查询,如果授权地址`operator`被`account`授权,则返回`true` * 见 {setApprovalForAll}函数. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev 安全转账,将`amount`单位`id`种类的代币从`from`转账给`to`. * 释放{TransferSingle}事件. * 要求: * - 如果调用者不是`from`地址而是授权地址,则需要得到`from`的授权 * - `from`地址必须有足够的持仓 * - 如果接收方是合约,需要实现`IERC1155Receiver`的`onERC1155Received`方法,并返回相应的值 */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev 批量安全转账 * 释放{TransferBatch}事件 * 要求: * - `ids`和`amounts`长度相等 * - 如果接收方是合约,需要实现`IERC1155Receiver`的`onERC1155BatchReceived`方法,并返回相应的值 */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; }
interface IERC1155 is IERC165 { /** * @dev 单类代币转账事件 * 当`value`个`id`种类的代币被`operator`从`from`转账到`to`时释放. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev 批量代币转账事件 * ids和values为转账的代币种类和数量数组 */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev 批量授权事件 * 当`account`将所有代币授权给`operator`时释放 */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev 当`id`种类的代币的URI发生变化时释放,`value`为新的URI */ event URI(string value, uint256 indexed id); /** * @dev 持仓查询,返回`account`拥有的`id`种类的代币的持仓量 */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev 批量持仓查询,`accounts`和`ids`数组的长度要想等。 */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev 批量授权,将调用者的代币授权给`operator`地址。 * 释放{ApprovalForAll}事件. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev 批量授权查询,如果授权地址`operator`被`account`授权,则返回`true` * 见 {setApprovalForAll}函数. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev 安全转账,将`amount`单位`id`种类的代币从`from`转账给`to`. * 释放{TransferSingle}事件. * 要求: * - 如果调用者不是`from`地址而是授权地址,则需要得到`from`的授权 * - `from`地址必须有足够的持仓 * - 如果接收方是合约,需要实现`IERC1155Receiver`的`onERC1155Received`方法,并返回相应的值 */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev 批量安全转账 * 释放{TransferBatch}事件 * 要求: * - `ids`和`amounts`长度相等 * - 如果接收方是合约,需要实现`IERC1155Receiver`的`onERC1155BatchReceived`方法,并返回相应的值 */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; }
24,505
285
// Read oracle prices for borrowed and collateral assets / Use stored value here as it is view function
uint256 _exchangeRateMantissa = IiToken(_iTokenCollateral).exchangeRateStored();
uint256 _exchangeRateMantissa = IiToken(_iTokenCollateral).exchangeRateStored();
40,588
13
// Mint a token with set Id/Set Id determined by owner/_to Address to mint token to Mint a token with sequential id
function _mintTokenId(address _to, uint256 _tokenId) private { _mint(_to, _tokenId, 1, ""); totalSupplyMinted += 1; emit MintEvent(block.timestamp, _tokenId); }
function _mintTokenId(address _to, uint256 _tokenId) private { _mint(_to, _tokenId, 1, ""); totalSupplyMinted += 1; emit MintEvent(block.timestamp, _tokenId); }
34,848
216
// send tokens
if (maxTokensCreated()) { revert("Max tokens created"); }
if (maxTokensCreated()) { revert("Max tokens created"); }
45,865
143
// Internal function that transfer tokens from one address to another./ Update magnifiedDividendCorrections to keep dividends unchanged./from The address to transfer from./to The address to transfer to./value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); }
function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); }
8,631
126
// sell
if (takeFee && recipient == address(uniswapV2Pair)) { uint256 fees = (amount * totalSellFeeBPS) / 10000; amount -= fees; _executeTransfer(sender, address(this), fees); }
if (takeFee && recipient == address(uniswapV2Pair)) { uint256 fees = (amount * totalSellFeeBPS) / 10000; amount -= fees; _executeTransfer(sender, address(this), fees); }
37,272
3
// Returns the multiplication of two unsigned integers, reverting on overflow. Counterpart to Solidity's `` operator. Requirements: - Multiplication cannot overflow./
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
22,285
13
// currentBid.auctionId = auctionId;currentBid.number = bidNumber;
bidsOfAuction[auctionId].push(currentBid); // Add current highestBid to the auction.
bidsOfAuction[auctionId].push(currentBid); // Add current highestBid to the auction.
11,391
7
// Unlocks a token. /
function unlockId(uint256 _id) external;
function unlockId(uint256 _id) external;
8,284
177
// returns the protection level based on the timestamp and protection delays_addTimestamptime at which the liquidity was added _removeTimestamp time at which the liquidity is removedreturn protection level (as a ratio) /
function protectionLevel(uint256 _addTimestamp, uint256 _removeTimestamp) internal view returns (Fraction memory) { uint256 timeElapsed = _removeTimestamp.sub(_addTimestamp); if (timeElapsed < minProtectionDelay) { return Fraction({ n: 0, d: 1 }); } if (timeElapsed >= maxProtectionDelay) { return Fraction({ n: 1, d: 1 }); } return Fraction({ n: timeElapsed, d: maxProtectionDelay }); }
function protectionLevel(uint256 _addTimestamp, uint256 _removeTimestamp) internal view returns (Fraction memory) { uint256 timeElapsed = _removeTimestamp.sub(_addTimestamp); if (timeElapsed < minProtectionDelay) { return Fraction({ n: 0, d: 1 }); } if (timeElapsed >= maxProtectionDelay) { return Fraction({ n: 1, d: 1 }); } return Fraction({ n: timeElapsed, d: maxProtectionDelay }); }
45,536
58
// Guarantees that the msg.sender is allowed to transfer NFT. _tokenId ID of the NFT to transfer. /
modifier canTransfer( uint256 _tokenId
modifier canTransfer( uint256 _tokenId
53,961
72
// Emits {SwapAndLiquify}/
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
43,034
28
// return the name
string memory equbName = pools[poolIndex].name; return equbName;
string memory equbName = pools[poolIndex].name; return equbName;
15,539
60
// 0x00: Unknown error. Something went really bad!
Unknown,
Unknown,
59,749
130
// indexed events are emitted
emit BondCreated( _amount, payout, block.number.add(terms.vestingTerm), priceInUSD ); emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio()); adjust(); // control variable is adjusted return payout;
emit BondCreated( _amount, payout, block.number.add(terms.vestingTerm), priceInUSD ); emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio()); adjust(); // control variable is adjusted return payout;
7,593
57
// if all shares are taken, just modify the owner address in place
holding.owner = _to;
holding.owner = _to;
41,962
189
// return {"success" : "Returns true if successfully called from another contract"} /
function execSwap( Data storage self, address requester, string symbolA, string symbolB, uint valueA, uint valueB, uint8 sigV, bytes32 sigR, bytes32 sigS,
function execSwap( Data storage self, address requester, string symbolA, string symbolB, uint valueA, uint valueB, uint8 sigV, bytes32 sigR, bytes32 sigS,
26,828
47
// isValid a redToken _tokenId the token id /
function isValidRedToken(uint256 _tokenId) public view returns (bool) { return redTokens[_tokenId].isValid; }
function isValidRedToken(uint256 _tokenId) public view returns (bool) { return redTokens[_tokenId].isValid; }
36,701
183
// Increase allowance with a signed authorization owner Token owner's address (Authorizer) spender Spender's address increment Amount of increase in allowance validAfterThe time after which this is valid (unix time) validBefore The time before which this is valid (unix time) nonce Unique nonce v v of the signature r r of the signature s s of the signature /
function increaseAllowanceWithAuthorization( address owner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s
function increaseAllowanceWithAuthorization( address owner, address spender, uint256 increment, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s
10,595
190
// Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. * * Emits a {IGovernor-VoteCast} event. */ function _castVote( uint256 proposalId, address account, uint8 support, string memory reason ) internal virtual returns (uint256) { require( state(proposalId) == ProposalState.Active, "Governor: vote not currently active" ); uint256 weight = _countVote(proposalId, account, support); emit VoteCast(account, proposalId, support, weight, reason); return weight; }
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. * * Emits a {IGovernor-VoteCast} event. */ function _castVote( uint256 proposalId, address account, uint8 support, string memory reason ) internal virtual returns (uint256) { require( state(proposalId) == ProposalState.Active, "Governor: vote not currently active" ); uint256 weight = _countVote(proposalId, account, support); emit VoteCast(account, proposalId, support, weight, reason); return weight; }
7,869
262
// 2
uint16 dailyDataCount; uint72 stakeSharesTotal; uint40 latestStakeId; uint128 claimStats;
uint16 dailyDataCount; uint72 stakeSharesTotal; uint40 latestStakeId; uint128 claimStats;
16,134
1
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) {
bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) {
21,146
23
// can only burn from the deployer address.
function burn (uint256 amount) public { require(msg.sender == owner); require(_balanceOf[msg.sender] >= amount); supply = supply.sub(amount); _transfer(msg.sender, address(0), amount); }
function burn (uint256 amount) public { require(msg.sender == owner); require(_balanceOf[msg.sender] >= amount); supply = supply.sub(amount); _transfer(msg.sender, address(0), amount); }
79,780
23
// Returns the token collection symbol. /
function symbol() external view returns (string memory);
function symbol() external view returns (string memory);
20,365
0
// Curiosity /
contract CuriosityVoting is Curiosity { // voting contract }
contract CuriosityVoting is Curiosity { // voting contract }
22,013
80
// index of the vault that is to be modified (if any)
uint256 vaultId;
uint256 vaultId;
9,436
19
// if the caller is the winner, transfer the NFT image if not refund
if (msg.sender == highestBidder) { recipient = highestBidder; value = bids[highestBidder] - highestBindingBid;
if (msg.sender == highestBidder) { recipient = highestBidder; value = bids[highestBidder] - highestBindingBid;
18,325
214
// Set Free Updates Count /
function setFreeUpdatesCount(uint256 _freeUpdatesCount) public onlyOwner { freeUpdatesCount = _freeUpdatesCount; }
function setFreeUpdatesCount(uint256 _freeUpdatesCount) public onlyOwner { freeUpdatesCount = _freeUpdatesCount; }
53,613
20
// Presale end time (inclusive)
uint256 public endTimePre;
uint256 public endTimePre;
36,949
15
// it calculates how much 'want' this contract holds.
function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); }
function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); }
61,968
93
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
remainder := mulmod(x, y, denominator)
1,323
10
// Forming Proposition
StorageFormingProposition._initStorage(initData.formingPropositionHash);
StorageFormingProposition._initStorage(initData.formingPropositionHash);
18,289
28
// Returns the current status of transaction approvals/This function doesn't modify state and can be freely called./ return The current status of transaction approvals
function isTxnApprovalEnabled() external view returns (bool) { return txnApprovalsEnabled; }
function isTxnApprovalEnabled() external view returns (bool) { return txnApprovalsEnabled; }
15,861
231
// The typehash for the data type specified in the structured data https:github.com/ethereum/EIPs/blob/master/EIPS/eip-712.mdrationale-for-typehash
bytes32 private constant _BUYING_LIFC_TYPEHASH = keccak256("BuyLIFC(address owner,uint256 nonce,uint256 amount,uint256 cost,uint256 deadline,address currencyAddress)");
bytes32 private constant _BUYING_LIFC_TYPEHASH = keccak256("BuyLIFC(address owner,uint256 nonce,uint256 amount,uint256 cost,uint256 deadline,address currencyAddress)");
24,467
108
// susdv2 pool
address public constant curve = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD;
address public constant curve = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD;
7,231
7
// applying check on duplication data..........
require(degrees[byte_id].expiration_date == 0, "Degree with given id already exists");
require(degrees[byte_id].expiration_date == 0, "Degree with given id already exists");
2,186
46
// burnable
event Burn(address indexed burner, uint256 value);
event Burn(address indexed burner, uint256 value);
9,984
98
// Multiplier on the marginRatio for this market
Decimal.D256 marginPremium;
Decimal.D256 marginPremium;
8,392
12
// latest BRR data (reward and rebate in bps)
BRRData internal latestBrrData;
BRRData internal latestBrrData;
33,621
15
// Public variables of the token // Variables of the token // Events /
function () payable { require (crowdsaleIsOpen == true); require(msg.value != 0); mintTRCToken(msg.sender, (msg.value * TRCExchangeRate * 10**decimals) / etherChange); }
function () payable { require (crowdsaleIsOpen == true); require(msg.value != 0); mintTRCToken(msg.sender, (msg.value * TRCExchangeRate * 10**decimals) / etherChange); }
49,694
59
// 32 is the length in bytes of hash, enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
50,896
18
// Check: extension namespace must already exist. Check: provided extension implementation must be non-zero.
require(_canReplaceExtension(_extension), "ExtensionManager: cannot replace extension.");
require(_canReplaceExtension(_extension), "ExtensionManager: cannot replace extension.");
27,380
10
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) }
uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) }
4,482
0
// Error functions /
error AmountZeroOrLess(); error CallerIsNotUser(); error InsufficientBalance(); error MaxMintPerAddressExceeded(); error MaxSupplyExceeded(); error NotAllowedMint(); error NotApproved(); error NotTokenOwner(uint256 tokenId); error OverMintAmountPerTransaction(); error ZeroAddress();
error AmountZeroOrLess(); error CallerIsNotUser(); error InsufficientBalance(); error MaxMintPerAddressExceeded(); error MaxSupplyExceeded(); error NotAllowedMint(); error NotApproved(); error NotTokenOwner(uint256 tokenId); error OverMintAmountPerTransaction(); error ZeroAddress();
26,606
0
// string jrv;
address sender;
address sender;
20,875
93
// - return info about current user's reward_user - user's address/
function getRewards(address _user) public view returns(uint256) { return userInfo[_user].rewardDebt; }
function getRewards(address _user) public view returns(uint256) { return userInfo[_user].rewardDebt; }
31,094
11
// The number of CVX should unlocked at the start of epoch `unlockEpoch`.
uint192 pendingUnlock;
uint192 pendingUnlock;
84,338