Verified contractExactMIT
SHPSHFTRAuction
Address0xa859e7afb0d7bc73cb2a60b128ff2f697d55d74e
- Balance
0 ETH
- Transactions
4
- Compiler
solc 0.8.20
- Same code
3 more contracts
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,153,503
- Creation transaction
- 0x268cd9b6c1…a61f4bf1ec
- Main copy (most transactions)
- 0x948e1bbb…ee111881
9 files
- contracts/SHPSHFTRAuction.solmain41.24 KB
- @openzeppelin/contracts/access/Ownable.sol3.1 KB
- @openzeppelin/contracts/token/ERC721/IERC721.sol4.93 KB
- @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol997 B
- @openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol795 B
- @openzeppelin/contracts/utils/Context.sol963 B
- @openzeppelin/contracts/utils/Pausable.sol2.71 KB
- @openzeppelin/contracts/utils/ReentrancyGuard.sol3.38 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
contracts/SHPSHFTRAuction.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
/**
* @dev The parts of ShpshftrNFT this contract reads to decide WHO may open a
* primary auction and WHICH tokens are still primary inventory.
*
* The NFT contract is the authoritative approval system — `approvedArtists` is
* the same gate it enforces on `artistCreateListing`, `artistCreateListingBatch`
* and `artistMintForAuction`, and `owner()` is the admin that `mintForAuction`
* is restricted to. This auction contract defines no roles of its own; it
* defers to that one, so onboarding, revocation and `selfApprove` all keep
* working with nothing to mirror or re-sync here.
*/
interface IShpshftrNftAuthority {
/// @dev The platform/admin wallet — `mintForAuction`'s onlyOwner caller.
function owner() external view returns (address);
/// @dev Artist and gallery onboarding, set by `setArtistApproval` /
/// `setArtistApprovalBatch` (admin) or `selfApprove` (open approval).
function approvedArtists(address account) external view returns (bool);
/// @dev Every mint path records the listing its token came from.
function tokenToListing(uint256 tokenId) external view returns (string memory);
/// @dev A populated `artist` means this listingId is a FIXED-PRICE/EDITION
/// listing. `mintForAuction` / `artistMintForAuction` reserve their
/// listingId without ever creating a Listing, so an auction-minted token
/// resolves to the zero artist. The two mint families share one
/// `_listingIdUsed` namespace, so the distinction is exclusive.
function getListing(string calldata listingId) external view returns (
address artist,
uint256 price,
string memory metadataURI,
uint96 royaltyBps,
bool active,
uint256 editions,
uint256 editionsMinted
);
}
/**
* @title SHPSHFTRAuction
* @dev Hardened reserve-triggered auction contract for SHPSHFTR NFTs
*
* Security Features:
* - Pausable: Emergency stop for all operations
* - Pull payments: Users withdraw funds (prevents bid griefing attacks)
* - Available Auction Balance: unlocked pull-payment funds can fund a new bid
* via placeBidWithBalance() instead of a withdraw-and-resend round trip
* - Timelock: 24h delay on critical admin changes
* - ReentrancyGuard: Prevents reentrancy attacks
* - Primary-sale economics: platform fee only, no royalty at settlement
* - Comprehensive input validation
* - Full event logging for transparency
*
* Features:
* - Reserve-triggered auctions: timer starts when first bid meets reserve price
* - Anti-snipe time extension
* - Platform fees via pull payment
*
* @custom:security-contact [email protected]
*/
contract SHPSHFTRAuction is ERC721Holder, Ownable, ReentrancyGuard, Pausable {
// ============ CONSTANTS ============
uint256 public constant MAX_PLATFORM_FEE_BPS = 1000; // 10% max
uint256 public constant TIMELOCK_DURATION = 24 hours;
uint256 public constant MIN_DURATION = 10 minutes;
uint256 public constant MAX_DURATION = 30 days;
uint256 public constant MIN_RESERVE = 0.0001 ether; // Prevent dust attacks
uint256 public constant MAX_RESERVE = 1000000 ether; // Sanity check
// ============ STATE VARIABLES ============
// Platform wallet
address public platformWallet;
/// @dev SHPSHFTR NFT contract address. Set once via setShpshftrNft()
/// AFTER the NFT contract is deployed (the auction must be deployed
/// before the NFT because the splitter factory depends on the auction
/// address). Once set, it is immutable. All auctions must use this
/// NFT contract as their token source — no third-party ERC721s.
address public shpshftrNft;
// Platform fee in basis points (1000 = 10%). The deployment starts in the
// intended production state so no post-deploy 24h-timelocked fee change is
// needed. Still adjustable via proposePlatformFeeChange(), bounded by
// MAX_PLATFORM_FEE_BPS.
uint256 public platformFeeBps = 1000;
// Minimum bid increment in basis points (500 = 5%)
uint256 public minBidIncrementBps = 500;
// Time extension when bid placed near end (5 minutes)
uint256 public timeExtension = 5 minutes;
// Anti-snipe TRIGGER WINDOW (60 seconds): a subsequent bid placed within
// this many seconds of the end extends the auction by `timeExtension`.
// This is the trigger threshold ONLY and is intentionally distinct from the
// extension duration above, so a bid placed earlier in the auction (e.g. 3
// minutes from the end) does NOT reset the timer. Previously the condition
// compared against `timeExtension` itself, which made any bid inside the
// final 5 minutes extend the auction.
uint256 public antiSnipeWindow = 60 seconds;
// Auction struct
struct Auction {
address nftContract;
uint256 tokenId;
address seller;
uint256 reservePrice;
uint256 duration; // Duration in seconds (timer starts when reserve is met)
uint256 startTime; // When auction timer started (0 if not started)
uint256 endTime; // When auction ends (0 if not started)
uint256 highestBid;
address highestBidder;
bool started; // Whether first bid meeting reserve has been placed
bool settled;
}
// Auction ID counter
uint256 private _auctionIdCounter;
// Mapping auction ID to auction
mapping(uint256 => Auction) public auctions;
/// @dev One-auction-per-token ledger. Flipped to true the first time a
/// given tokenId is successfully submitted to createAuction() and never
/// cleared — even if the auction is cancelled, reclaimed, or settles.
/// This makes the auction contract a **primary-sale-only** venue:
/// secondary owners cannot re-auction a token via direct contract calls.
mapping(uint256 => bool) public hasUsedPrimaryAuction;
/// @dev C-1 fix: set true by settleAuction when the NFT could NOT be
/// delivered to the winner via safeTransferFrom — e.g. the winner is a
/// contract whose onERC721Received reverts, or a contract that does not
/// implement the receiver hook at all. In that case settlement still
/// completes (payouts are credited and `settled` is set), the NFT is held
/// in escrow by this contract, and the winner pulls it later via
/// claimNFT(). This prevents a non-receiving winner from permanently
/// bricking settleAuction() and locking the seller's proceeds + the NFT.
mapping(uint256 => bool) public nftClaimable;
// ============ PULL PAYMENT SYSTEM ============
// Pending withdrawals for each address
mapping(address => uint256) public pendingWithdrawals;
// Total pending withdrawals (for contract balance verification)
uint256 public totalPendingWithdrawals;
// ============ TIMELOCK SYSTEM ============
struct TimelockProposal {
uint256 newValue;
address newAddress;
uint256 executeTime; // 0 = no active proposal
}
// Pending fee change
TimelockProposal public pendingFeeChange;
// Pending wallet change
TimelockProposal public pendingWalletChange;
// Pending bid increment change
TimelockProposal public pendingBidIncrementChange;
// Pending time extension change
TimelockProposal public pendingTimeExtensionChange;
// ============ EVENTS ============
event AuctionCreated(
uint256 indexed auctionId,
address indexed nftContract,
uint256 indexed tokenId,
address seller,
uint256 reservePrice,
uint256 duration
);
event AuctionStarted(
uint256 indexed auctionId,
uint256 startTime,
uint256 endTime
);
event BidPlaced(
uint256 indexed auctionId,
address indexed bidder,
uint256 amount
);
/// @dev Emitted when placeBidWithBalance() funds part or all of a bid from
/// the bidder's Available Auction Balance (their unlocked
/// pendingWithdrawals). `amount` is the balance consumed. The BidPlaced
/// event emitted in the same transaction still carries the FULL bid.
event AuctionBalanceUsed(
uint256 indexed auctionId,
address indexed bidder,
uint256 amount
);
event AuctionExtended(uint256 indexed auctionId, uint256 newEndTime);
/// @dev The royalty fields on AuctionSettled are always (address(0), 0):
/// this venue sells primaries, which owe no royalty. They are retained so
/// the event's ABI shape stays identical across deployments for the
/// off-chain indexers that decode it — see settleAuction().
event AuctionSettled(
uint256 indexed auctionId,
address indexed winner,
uint256 grossSalePrice,
uint256 platformFee,
address royaltyRecipient,
uint256 royaltyAmount,
uint256 sellerNet
);
event AuctionCancelled(uint256 indexed auctionId);
/// @dev C-1 fix: emitted when settleAuction could not push the NFT to the
/// winner and escrowed it for claim instead. Payouts were still credited.
event AuctionNftEscrowed(uint256 indexed auctionId, address indexed winner);
/// @dev C-1 fix: emitted when a winner pulls an escrowed NFT via claimNFT().
event AuctionNftClaimed(
uint256 indexed auctionId,
address indexed winner,
address indexed to
);
// Timelock events
event PlatformFeeChangeProposed(uint256 currentFee, uint256 newFee, uint256 executeTime);
event PlatformFeeChangeExecuted(uint256 oldFee, uint256 newFee);
event PlatformFeeChangeCancelled(uint256 proposedFee);
event PlatformWalletChangeProposed(address currentWallet, address newWallet, uint256 executeTime);
event PlatformWalletChangeExecuted(address oldWallet, address newWallet);
event PlatformWalletChangeCancelled(address proposedWallet);
event BidIncrementChangeProposed(uint256 currentBps, uint256 newBps, uint256 executeTime);
event BidIncrementChangeExecuted(uint256 oldBps, uint256 newBps);
event BidIncrementChangeCancelled(uint256 proposedBps);
event TimeExtensionChangeProposed(uint256 currentSeconds, uint256 newSeconds, uint256 executeTime);
event TimeExtensionChangeExecuted(uint256 oldSeconds, uint256 newSeconds);
event TimeExtensionChangeCancelled(uint256 proposedSeconds);
// Payment events
event PaymentPending(address indexed recipient, uint256 amount);
event PaymentWithdrawn(address indexed recipient, uint256 amount);
// Emergency events
event EmergencyPaused(address indexed by);
event EmergencyUnpaused(address indexed by);
/// @dev Emitted once, when the SHPSHFTR NFT contract address is bound
/// to this auction via setShpshftrNft(). The bind is permanent.
event ShpshftrNftSet(address indexed nftContract);
// ============ CONSTRUCTOR ============
constructor(address _platformWallet) Ownable(msg.sender) {
require(_platformWallet != address(0), "Invalid platform wallet");
require(_platformWallet != address(this), "Cannot be auction contract");
platformWallet = _platformWallet;
}
// ============ MODIFIERS ============
modifier validAddress(address _addr) {
require(_addr != address(0), "Invalid address: zero");
require(_addr != address(this), "Invalid address: auction contract");
_;
}
// ============ SELLER FUNCTIONS ============
/**
* @dev Create a new reserve-triggered auction
* Timer does NOT start until first bid meets the reserve price
*
* PRIMARY-SALE ORIGINATION IS PERMISSIONED. The caller must be an approved
* SHPSHFTR artist/gallery or the NFT contract's admin, AND the token must
* never have been sold as a fixed-price primary. Both facts are read from
* ShpshftrNFT, which stays the single authority on who may originate work.
* @param _nftContract Address of the NFT contract
* @param _tokenId Token ID to auction
* @param _duration Auction duration in seconds (starts when reserve is met)
* @param _reservePrice Minimum price to start the auction timer
* @return auctionId The ID of the created auction
*/
function createAuction(
address _nftContract,
uint256 _tokenId,
uint256 _duration,
uint256 _reservePrice
) external nonReentrant whenNotPaused validAddress(_nftContract) returns (uint256) {
require(_duration >= MIN_DURATION, "Duration too short");
require(_duration <= MAX_DURATION, "Duration too long");
require(_reservePrice >= MIN_RESERVE, "Reserve too low");
require(_reservePrice <= MAX_RESERVE, "Reserve too high");
// POLICY: auctions are primary-sale only and restricted to the
// SHPSHFTR NFT contract. Third-party ERC721s cannot be listed (this
// also defends against hostile NFTs that would otherwise try to
// drain the seller via ERC-2981 — see C2 fix).
require(shpshftrNft != address(0), "SHPSHFTR NFT not set");
require(_nftContract == shpshftrNft, "Only SHPSHFTR NFTs");
// POLICY: one auction per token, ever. Once a token has entered
// this contract it cannot be auctioned again — even after cancel,
// reclaim, or settlement. Secondary owners must use the marketplace.
require(!hasUsedPrimaryAuction[_tokenId], "Token already auctioned");
// POLICY: only a SHPSHFTR primary actor may ORIGINATE a primary sale.
//
// Holding a SHPSHFTR token is not authority to sell one as a primary.
// Every other primary entry point on the NFT contract is gated —
// `createListing` and `mintForAuction` are onlyOwner, and
// `artistCreateListing` / `artistMintForAuction` require
// `approvedArtists[msg.sender]` — but createAuction gated on nothing
// except owning the token, so a collector who bought a piece could open
// a primary auction on this contract by calling it directly. The
// frontend never offers that; the contract has to refuse it.
//
// The gate is the NFT contract's OWN approval state, read live. No role
// is duplicated here: revoking an artist there revokes them here in the
// same transaction, and a gallery already onboarded as an approved
// artist needs no new grant.
require(
IShpshftrNftAuthority(shpshftrNft).approvedArtists(msg.sender) ||
msg.sender == IShpshftrNftAuthority(shpshftrNft).owner(),
"Not an approved SHPSHFTR seller"
);
// POLICY: the token itself must still be primary inventory.
//
// The caller gate above stops collectors, but an approved artist is
// also free to BUY other artists' work, and a fixed-price primary
// purchase must never be re-routed into the primary venue by whoever
// now holds it. A token minted for auction resolves to a listingId
// that carries no Listing; a token minted by `purchase` /
// `purchaseReserved` resolves to the real fixed-price Listing it was
// sold from. That distinction is exclusive by construction (both
// families draw from the same `_listingIdUsed` namespace) and this
// check fails closed on anything it cannot resolve.
(address listingArtist, , , , , , ) = IShpshftrNftAuthority(shpshftrNft)
.getListing(IShpshftrNftAuthority(shpshftrNft).tokenToListing(_tokenId));
require(listingArtist == address(0), "Token already sold as primary");
// Mark BEFORE the external NFT transfer (CEI pattern) so a
// reentrant createAuction via onERC721Received cannot double-list.
hasUsedPrimaryAuction[_tokenId] = true;
// Transfer NFT to auction contract
IERC721(_nftContract).safeTransferFrom(msg.sender, address(this), _tokenId);
_auctionIdCounter++;
uint256 auctionId = _auctionIdCounter;
auctions[auctionId] = Auction({
nftContract: _nftContract,
tokenId: _tokenId,
seller: msg.sender,
reservePrice: _reservePrice,
duration: _duration,
startTime: 0, // Not started yet
endTime: 0, // Not started yet
highestBid: 0,
highestBidder: address(0),
started: false,
settled: false
});
emit AuctionCreated(
auctionId,
_nftContract,
_tokenId,
msg.sender,
_reservePrice,
_duration
);
return auctionId;
}
/**
* @dev Bind the SHPSHFTR NFT contract address to this auction. One-shot,
* owner-only. Must be called after the NFT contract is deployed (the
* deployment order is: Marketplace -> Auction -> SplitterFactory -> NFT
* -> factory.setNftContract() -> auction.setShpshftrNft()). Once set,
* the binding is permanent for the lifetime of the contract.
*/
function setShpshftrNft(address _nft) external onlyOwner {
require(shpshftrNft == address(0), "Already set");
require(_nft != address(0), "Invalid address");
require(_nft != address(this), "Cannot be auction contract");
shpshftrNft = _nft;
emit ShpshftrNftSet(_nft);
}
/**
* @dev Cancel auction (only if not started — no bids meeting reserve)
*/
function cancelAuction(uint256 _auctionId) external nonReentrant {
Auction storage auction = auctions[_auctionId];
require(auction.seller == msg.sender, "Not auction seller");
require(!auction.settled, "Already settled");
require(!auction.started, "Auction already started");
auction.settled = true;
// Return NFT to seller
IERC721(auction.nftContract).safeTransferFrom(
address(this),
auction.seller,
auction.tokenId
);
emit AuctionCancelled(_auctionId);
}
// ============ BIDDER FUNCTIONS ============
/**
* @dev Place a bid on an auction funded entirely by msg.value
* (uses pull payment for previous bidder refunds)
* First bid must meet reserve price and starts the auction timer
* Subsequent bids must be at least minBidIncrement% higher
*/
function placeBid(uint256 _auctionId) external payable nonReentrant whenNotPaused {
_placeBid(_auctionId, msg.value);
}
/**
* @dev Place a bid funded partly or wholly from the caller's Available
* Auction Balance — the unlocked ETH already held for them in
* `pendingWithdrawals` (outbid refunds, sale proceeds and platform fees
* credited by THIS contract). Lets a bidder reuse that ETH on any auction
* on this contract without withdrawing it and sending it straight back.
*
* Deterministic accounting: `_bidAmount` is the TOTAL bid and `msg.value`
* is the new ETH supplied from the wallet, so the balance consumed is
* exactly `_bidAmount - msg.value`, fixed by the signed calldata. The
* contract never decides how much balance to use from whatever happens
* to be pending at mining time.
*
* Only ETH already in `pendingWithdrawals[msg.sender]` is spendable. ETH
* backing a live highest bid lives in `Auction.highestBid`, never in the
* pending map, so it stays locked. The debit happens BEFORE `_placeBid`
* releases the previous highest bid, so a bidder raising their own
* winning bid cannot spend the refund created by this same transaction.
*
* The contract's ETH balance is unchanged by the reuse (only msg.value
* arrives): value moves from `totalPendingWithdrawals` into the auction's
* `highestBid`, and returns in full via `_addPendingWithdrawal` if the
* bidder is later outbid. No external calls are made, so the pull-payment
* model and withdraw() are untouched.
*
* @param _auctionId The auction to bid on
* @param _bidAmount Total bid = msg.value + Available Auction Balance used
*/
function placeBidWithBalance(uint256 _auctionId, uint256 _bidAmount)
external
payable
nonReentrant
whenNotPaused
{
require(_bidAmount >= msg.value, "Bid below sent value");
uint256 balanceUsed = _bidAmount - msg.value;
if (balanceUsed > 0) {
require(
pendingWithdrawals[msg.sender] >= balanceUsed,
"Insufficient auction balance"
);
pendingWithdrawals[msg.sender] -= balanceUsed;
totalPendingWithdrawals -= balanceUsed;
emit AuctionBalanceUsed(_auctionId, msg.sender, balanceUsed);
}
_placeBid(_auctionId, _bidAmount);
}
/**
* @dev Shared bid logic for placeBid() and placeBidWithBalance().
* `_bidAmount` is the full bid being recorded, however it was funded.
* Both external entry points hold the reentrancy lock and pause check.
*/
function _placeBid(uint256 _auctionId, uint256 _bidAmount) internal {
Auction storage auction = auctions[_auctionId];
require(!auction.settled, "Auction settled");
require(auction.seller != address(0), "Auction does not exist");
require(msg.sender != auction.seller, "Seller cannot bid");
// If auction has started, check it hasn't ended
if (auction.started) {
require(block.timestamp < auction.endTime, "Auction ended");
}
uint256 minBid;
bool isFirstBid = !auction.started;
if (isFirstBid) {
// First bid must meet reserve price to start the auction
minBid = auction.reservePrice;
require(_bidAmount >= minBid, "Bid must meet reserve to start auction");
// Start the auction timer
auction.started = true;
auction.startTime = block.timestamp;
auction.endTime = block.timestamp + auction.duration;
emit AuctionStarted(_auctionId, auction.startTime, auction.endTime);
} else {
// Subsequent bids must be at least minBidIncrement% higher
minBid = auction.highestBid + (auction.highestBid * minBidIncrementBps) / 10000;
require(_bidAmount >= minBid, "Bid too low");
}
// Credit previous highest bidder using pull pattern (prevents bid griefing)
if (auction.highestBidder != address(0)) {
_addPendingWithdrawal(auction.highestBidder, auction.highestBid);
}
// Update auction
auction.highestBid = _bidAmount;
auction.highestBidder = msg.sender;
// Anti-snipe: extend auction ONLY if a subsequent bid is placed within
// the final `antiSnipeWindow` (60s). The trigger threshold is the
// window, while the extension amount stays `timeExtension` (5 min).
// Skip on the first bid — it just started the timer at the seller's intended duration.
if (!isFirstBid && auction.endTime - block.timestamp < antiSnipeWindow) {
auction.endTime = block.timestamp + timeExtension;
emit AuctionExtended(_auctionId, auction.endTime);
}
emit BidPlaced(_auctionId, msg.sender, _bidAmount);
}
// ============ SETTLEMENT ============
/**
* @dev Settle an ended auction (uses pull payments)
* Can only settle auctions that started (reserve was met) and have ended
*
* PRIMARY SALE ECONOMICS — NO ROYALTY IS CHARGED HERE.
*
* This contract is a primary-sale-only venue: createAuction() accepts only
* the canonical SHPSHFTR NFT and refuses any token that has already been
* auctioned (`hasUsedPrimaryAuction`), so every settlement it performs is
* an artwork's FIRST sale. A first sale owes the platform fee and nothing
* else — exactly as ShpshftrNFT.purchase() splits a fixed-price primary
* mint into platformFee + artistPayment.
*
* Settlement used to query ERC-2981 `royaltyInfo` and pay the result,
* subtracting it from the seller. That is the SECONDARY formula
* (SHPSHFTRMarketplace.buyNFT), and applying it to a first sale charged a
* resale royalty before any resale had happened: a 0.01 ETH auction of a
* token minted at the default 1000 bps paid 10% platform, 10% royalty and
* only 80% to the seller, against a published 10/90 split.
*
* The token's ERC-2981 royalty is UNTOUCHED. It is set once at mint
* (ShpshftrNFT._setTokenRoyalty) to the artist's splitter and remains in
* force for every future secondary sale through the marketplace — which is
* the venue it was always meant for. Removing the charge here removes the
* charge, not the entitlement.
*
* Do not reinstate a royaltyInfo lookup in this function. If a genuinely
* secondary auction is ever supported, it needs its own explicit sale-type
* identity at creation, not an ERC-2981 read at settlement.
*/
function settleAuction(uint256 _auctionId) external nonReentrant {
Auction storage auction = auctions[_auctionId];
require(!auction.settled, "Already settled");
require(auction.started, "Auction never started");
require(block.timestamp >= auction.endTime, "Auction not ended");
auction.settled = true;
uint256 finalSalePrice = auction.highestBid;
// Calculate fees. The platform fee is the ONLY deduction on a primary
// sale; everything else is the seller's.
uint256 platformFee = (finalSalePrice * platformFeeBps) / 10000;
// Guard: the platform fee must not exceed the sale price. With
// MAX_PLATFORM_FEE_BPS = 1000 this can never fail, but the guard is
// kept as belt-and-suspenders in case the constant is ever increased.
require(platformFee <= finalSalePrice, "Fees exceed sale price");
uint256 sellerNet = finalSalePrice - platformFee;
require(sellerNet > 0, "Seller net must be positive");
// Credit pending withdrawals (pull pattern). Two recipients only —
// no royalty recipient is credited by an auction settlement.
_addPendingWithdrawal(platformWallet, platformFee);
_addPendingWithdrawal(auction.seller, sellerNet);
// The royalty fields are retained in the event signature and emitted
// as zero. Three off-chain consumers decode AuctionSettled positionally
// and by topic0 (lib/blockchain/auction-verify.ts,
// api/auctions/[id]/settle, api/cron/index-auctions), including against
// logs from earlier deployments, so the shape must not change.
emit AuctionSettled(
_auctionId,
auction.highestBidder,
finalSalePrice,
platformFee,
address(0),
0,
sellerNet
);
// C-1 fix: deliver the NFT LAST, after settlement state and all
// payouts are finalized. Attempt to push it to the winner, but if the
// winner cannot receive an ERC-721 (reverting/absent onERC721Received),
// escrow it for the winner to pull via claimNFT() instead of reverting
// the whole settlement. The auction is already `settled`, payouts are
// already credited, so a hostile/incompatible winner can only delay
// their own NFT receipt — it can never block the seller's proceeds or
// the platform fee, or lock the NFT permanently.
_deliverOrEscrowNft(
_auctionId,
auction.nftContract,
auction.tokenId,
auction.highestBidder
);
}
/**
* @dev C-1 fix: try to push the NFT to the winner; on any failure of the
* external transfer (winner reverts in onERC721Received or is a
* non-receiver contract) mark the NFT claimable so the winner can pull it
* later via claimNFT(). Never reverts — settlement must always complete.
*/
function _deliverOrEscrowNft(
uint256 _auctionId,
address _nftContract,
uint256 _tokenId,
address _winner
) internal {
try
IERC721(_nftContract).safeTransferFrom(address(this), _winner, _tokenId)
{
// Delivered directly to the winner.
} catch {
// Winner cannot receive the NFT right now. Hold it in escrow; the
// winner pulls it via claimNFT(). Payouts are unaffected.
nftClaimable[_auctionId] = true;
emit AuctionNftEscrowed(_auctionId, _winner);
}
}
/**
* @dev C-1 fix: pull an escrowed NFT after settlement. Only the auction
* winner (highestBidder) may claim, and they may direct delivery to any
* valid address they control — this lets a winner whose bidding contract
* cannot receive ERC-721 still recover the NFT to an EOA or compatible
* wallet. Uses safeTransferFrom so the NFT cannot be pushed into a
* non-receiver; if the chosen destination reverts, the claim simply
* reverts and the winner can retry with a different destination — the NFT
* stays safely escrowed in the meantime.
* @param _auctionId The settled auction whose NFT is escrowed
* @param _to Destination address for the NFT (winner-controlled)
*/
function claimNFT(uint256 _auctionId, address _to)
external
nonReentrant
validAddress(_to)
{
Auction storage auction = auctions[_auctionId];
require(auction.settled, "Auction not settled");
require(nftClaimable[_auctionId], "Nothing to claim");
require(msg.sender == auction.highestBidder, "Not auction winner");
// Effect before interaction (CEI): clear the claim flag first so a
// reentrant claim cannot double-deliver.
nftClaimable[_auctionId] = false;
IERC721(auction.nftContract).safeTransferFrom(
address(this),
_to,
auction.tokenId
);
emit AuctionNftClaimed(_auctionId, auction.highestBidder, _to);
}
/**
* @dev Reclaim NFT from an auction that was never started (seller only)
* Use this if reserve was never met and you want your NFT back
*/
function reclaimUnsoldNFT(uint256 _auctionId) external nonReentrant {
Auction storage auction = auctions[_auctionId];
require(auction.seller == msg.sender, "Not auction seller");
require(!auction.settled, "Already settled");
require(!auction.started, "Auction was started");
auction.settled = true;
// Return NFT to seller
IERC721(auction.nftContract).safeTransferFrom(
address(this),
auction.seller,
auction.tokenId
);
emit AuctionCancelled(_auctionId);
}
// ============ PULL PAYMENT FUNCTIONS ============
/**
* @dev Internal function to add pending withdrawal
*/
function _addPendingWithdrawal(address _recipient, uint256 _amount) internal {
pendingWithdrawals[_recipient] += _amount;
totalPendingWithdrawals += _amount;
emit PaymentPending(_recipient, _amount);
}
/**
* @dev Withdraw pending funds
* Can be called even when paused (users should always be able to withdraw)
*/
function withdraw() external nonReentrant {
uint256 amount = pendingWithdrawals[msg.sender];
require(amount > 0, "No funds to withdraw");
// Clear before transfer (CEI pattern)
pendingWithdrawals[msg.sender] = 0;
totalPendingWithdrawals -= amount;
// Transfer funds
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Withdrawal failed");
emit PaymentWithdrawn(msg.sender, amount);
}
/**
* @dev Check pending withdrawal amount
*/
function getPendingWithdrawal(address _address) external view returns (uint256) {
return pendingWithdrawals[_address];
}
// ============ TIMELOCK FUNCTIONS ============
/**
* @dev Propose platform fee change (24h timelock)
*/
function proposePlatformFeeChange(uint256 _newFeeBps) external onlyOwner {
require(_newFeeBps <= MAX_PLATFORM_FEE_BPS, "Fee exceeds maximum");
require(pendingFeeChange.executeTime == 0, "Existing proposal active");
pendingFeeChange = TimelockProposal({
newValue: _newFeeBps,
newAddress: address(0),
executeTime: block.timestamp + TIMELOCK_DURATION
});
emit PlatformFeeChangeProposed(platformFeeBps, _newFeeBps, pendingFeeChange.executeTime);
}
/**
* @dev Execute platform fee change after timelock
*/
function executePlatformFeeChange() external onlyOwner {
require(pendingFeeChange.executeTime > 0, "No pending change");
require(block.timestamp >= pendingFeeChange.executeTime, "Timelock not expired");
uint256 oldFee = platformFeeBps;
platformFeeBps = pendingFeeChange.newValue;
delete pendingFeeChange;
emit PlatformFeeChangeExecuted(oldFee, platformFeeBps);
}
/**
* @dev Cancel pending fee change
*/
function cancelPlatformFeeChange() external onlyOwner {
require(pendingFeeChange.executeTime > 0, "No pending change");
uint256 proposedFee = pendingFeeChange.newValue;
delete pendingFeeChange;
emit PlatformFeeChangeCancelled(proposedFee);
}
/**
* @dev Propose platform wallet change (24h timelock)
*/
function proposePlatformWalletChange(address _newWallet) external onlyOwner validAddress(_newWallet) {
require(pendingWalletChange.executeTime == 0, "Existing proposal active");
pendingWalletChange = TimelockProposal({
newValue: 0,
newAddress: _newWallet,
executeTime: block.timestamp + TIMELOCK_DURATION
});
emit PlatformWalletChangeProposed(platformWallet, _newWallet, pendingWalletChange.executeTime);
}
/**
* @dev Execute platform wallet change after timelock
*/
function executePlatformWalletChange() external onlyOwner {
require(pendingWalletChange.executeTime > 0, "No pending change");
require(block.timestamp >= pendingWalletChange.executeTime, "Timelock not expired");
address oldWallet = platformWallet;
platformWallet = pendingWalletChange.newAddress;
delete pendingWalletChange;
emit PlatformWalletChangeExecuted(oldWallet, platformWallet);
}
/**
* @dev Cancel pending wallet change
*/
function cancelPlatformWalletChange() external onlyOwner {
require(pendingWalletChange.executeTime > 0, "No pending change");
address proposedWallet = pendingWalletChange.newAddress;
delete pendingWalletChange;
emit PlatformWalletChangeCancelled(proposedWallet);
}
// ============ TIMELOCKED ADMIN FUNCTIONS ============
/**
* @dev Propose min bid increment change (24h timelock)
*/
function proposeBidIncrementChange(uint256 _newBps) external onlyOwner {
require(_newBps >= 100 && _newBps <= 2000, "Invalid increment"); // 1-20%
require(pendingBidIncrementChange.executeTime == 0, "Existing proposal active");
pendingBidIncrementChange = TimelockProposal({
newValue: _newBps,
newAddress: address(0),
executeTime: block.timestamp + TIMELOCK_DURATION
});
emit BidIncrementChangeProposed(minBidIncrementBps, _newBps, pendingBidIncrementChange.executeTime);
}
/**
* @dev Execute bid increment change after timelock
*/
function executeBidIncrementChange() external onlyOwner {
require(pendingBidIncrementChange.executeTime > 0, "No pending change");
require(block.timestamp >= pendingBidIncrementChange.executeTime, "Timelock not expired");
uint256 oldBps = minBidIncrementBps;
minBidIncrementBps = pendingBidIncrementChange.newValue;
delete pendingBidIncrementChange;
emit BidIncrementChangeExecuted(oldBps, minBidIncrementBps);
}
/**
* @dev Cancel pending bid increment change
*/
function cancelBidIncrementChange() external onlyOwner {
require(pendingBidIncrementChange.executeTime > 0, "No pending change");
uint256 proposedBps = pendingBidIncrementChange.newValue;
delete pendingBidIncrementChange;
emit BidIncrementChangeCancelled(proposedBps);
}
/**
* @dev Propose time extension change (24h timelock)
*/
function proposeTimeExtensionChange(uint256 _newSeconds) external onlyOwner {
require(_newSeconds >= 1 minutes && _newSeconds <= 30 minutes, "Invalid extension");
require(pendingTimeExtensionChange.executeTime == 0, "Existing proposal active");
pendingTimeExtensionChange = TimelockProposal({
newValue: _newSeconds,
newAddress: address(0),
executeTime: block.timestamp + TIMELOCK_DURATION
});
emit TimeExtensionChangeProposed(timeExtension, _newSeconds, pendingTimeExtensionChange.executeTime);
}
/**
* @dev Execute time extension change after timelock
*/
function executeTimeExtensionChange() external onlyOwner {
require(pendingTimeExtensionChange.executeTime > 0, "No pending change");
require(block.timestamp >= pendingTimeExtensionChange.executeTime, "Timelock not expired");
uint256 oldSeconds = timeExtension;
timeExtension = pendingTimeExtensionChange.newValue;
delete pendingTimeExtensionChange;
emit TimeExtensionChangeExecuted(oldSeconds, timeExtension);
}
/**
* @dev Cancel pending time extension change
*/
function cancelTimeExtensionChange() external onlyOwner {
require(pendingTimeExtensionChange.executeTime > 0, "No pending change");
uint256 proposedSeconds = pendingTimeExtensionChange.newValue;
delete pendingTimeExtensionChange;
emit TimeExtensionChangeCancelled(proposedSeconds);
}
// ============ EMERGENCY FUNCTIONS ============
/**
* @dev Pause auction creation and bidding
* Withdrawals and settlement remain enabled
*/
function pause() external onlyOwner {
_pause();
emit EmergencyPaused(msg.sender);
}
/**
* @dev Unpause the contract
*/
function unpause() external onlyOwner {
_unpause();
emit EmergencyUnpaused(msg.sender);
}
// ============ VIEW FUNCTIONS ============
function getAuction(uint256 _auctionId) external view returns (Auction memory) {
return auctions[_auctionId];
}
function isAuctionActive(uint256 _auctionId) external view returns (bool) {
Auction memory auction = auctions[_auctionId];
return auction.started &&
!auction.settled &&
block.timestamp < auction.endTime;
}
function isAuctionEnded(uint256 _auctionId) external view returns (bool) {
Auction memory auction = auctions[_auctionId];
return auction.started && block.timestamp >= auction.endTime;
}
function totalAuctions() external view returns (uint256) {
return _auctionIdCounter;
}
/**
* @dev Get pending timelock info for fee change
*/
function getPendingFeeChange() external view returns (uint256 newFee, uint256 executeTime) {
return (pendingFeeChange.newValue, pendingFeeChange.executeTime);
}
/**
* @dev Get pending timelock info for wallet change
*/
function getPendingWalletChange() external view returns (address newWallet, uint256 executeTime) {
return (pendingWalletChange.newAddress, pendingWalletChange.executeTime);
}
/**
* @dev Get pending timelock info for bid increment change
*/
function getPendingBidIncrementChange() external view returns (uint256 newBps, uint256 executeTime) {
return (pendingBidIncrementChange.newValue, pendingBidIncrementChange.executeTime);
}
/**
* @dev Get pending timelock info for time extension change
*/
function getPendingTimeExtensionChange() external view returns (uint256 newSeconds, uint256 executeTime) {
return (pendingTimeExtensionChange.newValue, pendingTimeExtensionChange.executeTime);
}
// ============ FALLBACK PROTECTION ============
/**
* @dev Reject direct ETH transfers (must use placeBid function)
*/
receive() external payable {
revert("Use placeBid() to bid");
}
fallback() external payable {
revert("Function does not exist");
}
}
@openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
@openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* 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 calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity >=0.5.0;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
* {IERC721-setApprovalForAll}.
*/
abstract contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
return this.onERC721Received.selector;
}
}
@openzeppelin/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
@openzeppelin/contracts/utils/Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
@openzeppelin/contracts/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.