Skip to content
Verified contractPartialGPL-3.0

SovereignAuctionHouseV2Factory

Address0x77ab853543286c9cdd7dd6c01222a7cc4ac93d63
Balance

0 ETH

 

Transactions

6

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
GPL-3.0
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,901,772
Creation transaction
0x5202cc23f3…3db64e52cb

src/SovereignAuctionHouseV2Factory.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {Clones} from "openzeppelin-contracts/contracts/proxy/Clones.sol";
import {SovereignAuctionHouseV2} from "./SovereignAuctionHouseV2.sol";

/// @notice Immutable factory for V2 ERC721 auction-house clones.
contract SovereignAuctionHouseV2Factory {
    address public immutable implementation;
    uint16 public immutable defaultProtocolFeeBps;
    address payable public immutable defaultFeeRecipient;
    mapping(address => address) public houseOf;
    address[] public allHouses;
    mapping(address => bool) public isHouse;

    event AuctionHouseCreated(address indexed owner, address indexed house, address feeRecipient, uint16 protocolFeeBps);

    constructor(address implementation_, address payable defaultFeeRecipient_, uint16 defaultProtocolFeeBps_) {
        require(implementation_ != address(0) && implementation_.code.length != 0, "implementation required");
        require(defaultProtocolFeeBps_ <= 500, "fee above cap");
        require(defaultProtocolFeeBps_ == 0 || defaultFeeRecipient_ != address(0), "fee recipient required when fee > 0");
        implementation = implementation_;
        defaultFeeRecipient = defaultFeeRecipient_;
        defaultProtocolFeeBps = defaultProtocolFeeBps_;
    }

    function createAuctionHouse() external returns (address house) {
        require(houseOf[msg.sender] == address(0), "House already exists");
        house = Clones.cloneDeterministic(implementation, bytes32(uint256(uint160(msg.sender))));
        SovereignAuctionHouseV2(payable(house)).initialize(msg.sender, defaultFeeRecipient, defaultProtocolFeeBps);
        houseOf[msg.sender] = house;
        allHouses.push(house);
        isHouse[house] = true;
        emit AuctionHouseCreated(msg.sender, house, defaultFeeRecipient, defaultProtocolFeeBps);
    }

    function predictHouseAddress(address owner) external view returns (address) {
        return Clones.predictDeterministicAddress(implementation, bytes32(uint256(uint160(owner))));
    }

    function totalHouses() external view returns (uint256) {
        return allHouses.length;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @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.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        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) {
        OwnableStorage storage $ = _getOwnableStorage();
        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 {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    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;
    }
}

lib/openzeppelin-contracts/contracts/proxy/Clones.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (proxy/Clones.sol)

pragma solidity ^0.8.20;

import {Errors} from "../utils/Errors.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        return clone(implementation, 0);
    }

    /**
     * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
     * to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function clone(address implementation, uint256 value) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(value, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        return cloneDeterministic(implementation, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
     * a `value` parameter to send native currency to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministic(
        address implementation,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(value, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/IERC1155.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC-1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[ERC].
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the value of tokens of token type `id` owned by `account`.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the zero address.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155Received} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `value` amount.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
     *
     * Requirements:
     *
     * - `ids` and `values` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external;
}

lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC-1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC-1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

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);
}

lib/openzeppelin-contracts/contracts/utils/Errors.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts/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;
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @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);
}

src/ISovereignAuctionHouseV2.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

/// @title Sovereign Auction House V2 interface
/// @notice ETH reserve auctions for ERC721 and ERC1155 tokens. Settlement
///         pays the seller only after the winner's delivery is verified.
///         Delivery is attempted with a fixed gas stipend; on failure,
///         neither the seller nor the protocol fee is paid, and both the
///         winning bid and the lot stay escrowed for a permissionless retry
///         via claimLot. If the lot is still undelivered
///         PENDING_DELIVERY_TIMEOUT after deferral, unwindStuckLot retries
///         delivery once more and, on a second failure, unwinds the sale:
///         the winner's bid is credited to pendingRefunds for withdrawal and
///         the lot is returned to the seller. If that return also fails, the
///         lot stays locked until returnUnwoundLot succeeds.
interface ISovereignAuctionHouseV2 {
    enum TokenStandard {
        ERC721,
        ERC1155
    }

    struct Auction {
        uint256 tokenId;
        address tokenContract;
        uint64 firstBidTime;
        uint256 amount;
        uint256 reservePrice;
        address tokenOwner;
        address payable fundsRecipient;
        uint64 endTime;
        address payable bidder;
        uint64 duration;
        uint256 quantity;
        TokenStandard standard;
    }

    event AuctionCreated(
        uint256 indexed auctionId,
        uint256 indexed tokenId,
        address indexed tokenContract,
        uint256 duration,
        uint256 reservePrice,
        address tokenOwner,
        address fundsRecipient,
        uint64 listingExpiry
    );
    event Auction1155Created(
        uint256 indexed auctionId,
        uint256 indexed tokenId,
        address indexed tokenContract,
        uint256 quantity,
        uint256 duration,
        uint256 reservePrice,
        address tokenOwner,
        address fundsRecipient,
        uint64 listingExpiry
    );
    event AuctionReservePriceUpdated(uint256 indexed auctionId, uint256 reservePrice);
    event AuctionDurationUpdated(uint256 indexed auctionId, uint256 duration);
    event AuctionFundsRecipientUpdated(uint256 indexed auctionId, address fundsRecipient);
    event AuctionListingExpiryUpdated(uint256 indexed auctionId, uint64 listingExpiry);
    event AuctionBid(
        uint256 indexed auctionId,
        address indexed bidder,
        uint256 amount,
        bool firstBid,
        bool extended
    );
    event AuctionEndTimeUpdated(uint256 indexed auctionId, uint64 newEndTime);
    event AuctionEnded(
        uint256 indexed auctionId,
        address tokenOwner,
        address winner,
        uint256 sellerProceeds,
        uint256 protocolFee
    );
    /// @notice Emitted when the token transfer attempted during endAuction
    ///         fails. Neither the seller nor the protocol fee has been paid;
    ///         the winning bid stays escrowed. The lot is retryable by
    ///         anyone via claimLot.
    event DeliveryDeferred(uint256 indexed auctionId, address indexed winner);
    /// @notice Emitted when claimLot or unwindStuckLot delivers a deferred
    ///         lot to the winner. Settlement (state cleanup and the seller
    ///         and protocol fee payout) happens in the same call.
    event LotClaimed(uint256 indexed auctionId, address indexed winner, address recipient);
    /// @notice Emitted when unwindStuckLot's retry to the winner still fails
    ///         PENDING_DELIVERY_TIMEOUT after deferral and the sale unwinds:
    ///         `refundAmount`, the winner's full bid, is credited to
    ///         pendingRefunds for withdrawal. Neither the seller nor the
    ///         protocol was ever paid on this auction. If the same call also
    ///         succeeds at returning the lot to `tokenOwner`, no further
    ///         event follows; if that return fails, LotReturnDeferred is
    ///         emitted alongside this one.
    event LotUnwound(uint256 indexed auctionId, address indexed winner, uint256 refundAmount, address tokenOwner);
    /// @notice Emitted alongside LotUnwound when the attempt to return the
    ///         lot to `tokenOwner` fails. The lot stays locked until
    ///         returnUnwoundLot succeeds.
    event LotReturnDeferred(uint256 indexed auctionId, address indexed tokenOwner);
    /// @notice Emitted when returnUnwoundLot delivers a previously deferred
    ///         return to `tokenOwner`.
    event LotReturned(uint256 indexed auctionId, address indexed tokenOwner);
    event AuctionCanceled(uint256 indexed auctionId);
    event RefundCredited(address indexed to, uint256 amount);
    event RefundWithdrawn(address indexed account, address indexed recipient, uint256 amount);
    event StuckERC721Recovered(address indexed tokenContract, uint256 indexed tokenId, address to);
    event StuckERC1155Recovered(address indexed tokenContract, uint256 indexed tokenId, uint256 quantity, address to);

    /// @notice Lists an ERC721 for auction. The house owner may list a
    ///         third party's token (consignment): `tokenOwner` is read from
    ///         the token itself and proceeds go to that owner's
    ///         `fundsRecipient`, not the house owner. `listingExpiry_` sets
    ///         the no-bid close date for the listing: 0 means no expiry, a
    ///         nonzero value must be strictly in the future and is stored
    ///         in `listingExpiry`. A bid placed before the expiry starts the
    ///         normal auction clock and the expiry no longer applies;
    ///         `createBid` only checks it while `firstBidTime` is unset. The
    ///         token owner can still change or clear it pre-bid via
    ///         `setAuctionListingExpiry`, or cancel entirely via
    ///         `cancelAuction`.
    function createAuction(
        uint256 tokenId,
        address tokenContract,
        uint256 duration,
        uint256 reservePrice,
        uint64 listingExpiry_
    ) external returns (uint256 auctionId);

    function create1155Auction(
        uint256 tokenId,
        address tokenContract,
        uint256 quantity,
        uint256 duration,
        uint256 reservePrice,
        uint64 listingExpiry_
    ) external returns (uint256 auctionId);

    /// @notice Returns the full auction record as a struct. The mapping's
    ///         auto-generated getter returns the same data as a flat tuple;
    ///         this exists so callers that need the whole record can decode
    ///         one struct instead of the full field list.
    function getAuction(uint256 auctionId) external view returns (Auction memory);

    function createBid(uint256 auctionId) external payable;

    /// @notice Settle a finished auction. Attempts token delivery to the
    ///         winner with a fixed gas stipend so the outcome cannot depend
    ///         on caller-supplied gas. The protocol fee and seller are paid
    ///         only if that delivery succeeds. On delivery failure nobody is
    ///         paid; the lot is deferred to claimLot instead. Reverts if the
    ///         auction is already settled or unwound, or with
    ///         InsufficientGas when called without enough gas to honor the
    ///         delivery stipend.
    function endAuction(uint256 auctionId) external;
    function cancelAuction(uint256 auctionId) external;
    function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice) external;
    function setAuctionDuration(uint256 auctionId, uint256 duration) external;
    function setAuctionFundsRecipient(uint256 auctionId, address payable fundsRecipient) external;
    function setAuctionListingExpiry(uint256 auctionId, uint64 expiry) external;
    function expireAuction(uint256 auctionId) external;
    function withdrawRefund() external;
    function withdrawRefundTo(address payable recipient) external;

    /// @notice Claims a lot whose delivery was deferred at settlement.
    ///         Anyone may call this with `to == address(0)` to trigger
    ///         delivery to the recorded winner; only that winner may redirect
    ///         delivery elsewhere via a nonzero `to`. Reverts if the auction
    ///         has no deferred delivery, or if a non-winner passes a nonzero
    ///         `to`. A revert during delivery reverts the whole call, leaving
    ///         the claim retryable. Settlement (state cleanup and the seller
    ///         and protocol fee payout) happens in this call, after delivery
    ///         succeeds. The redirect is best-effort: the pending state is
    ///         consumed by whichever call succeeds first, so a third party
    ///         triggering delivery to the winner with `to == address(0)`
    ///         before the winner redirects permanently forecloses that
    ///         redirect. The token always still reaches the winner's own bid
    ///         address in that case.
    function claimLot(uint256 auctionId, address to) external;

    /// @notice Resolves a lot still pending delivery PENDING_DELIVERY_TIMEOUT
    ///         after deferral. Anyone may call this. It first retries
    ///         delivery to the recorded winner; if that succeeds, the sale
    ///         finalizes normally and the seller is paid. If it fails again,
    ///         the sale unwinds: the winner's full bid is credited to
    ///         pendingRefunds and the lot is returned to the seller. If that
    ///         return also fails, the lot stays locked until
    ///         returnUnwoundLot succeeds.
    function unwindStuckLot(uint256 auctionId) external;

    /// @notice Delivers a lot whose return to the seller failed during
    ///         unwindStuckLot. Anyone may call this; it only ever delivers to
    ///         the auction's recorded tokenOwner. Reverts if the auction has
    ///         no deferred return.
    function returnUnwoundLot(uint256 auctionId) external;
}

src/SovereignAuctionHouseV2.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;

import {IERC721} from "openzeppelin-contracts/contracts/token/ERC721/IERC721.sol";
import {IERC1155} from "openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol";
import {IERC1155Receiver} from "openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol";
import {IERC165} from "openzeppelin-contracts/contracts/utils/introspection/IERC165.sol";
import {ReentrancyGuard} from "openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol";
import {Initializable} from "openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol";
import {OwnableUpgradeable} from "openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol";

import {ISovereignAuctionHouseV2} from "./ISovereignAuctionHouseV2.sol";

/// @title Sovereign Auction House V2
/// @notice ERC721 and ERC1155 reserve auctions. Settlement pays the seller
///         only after the winner provably holds the lot: endAuction attempts
///         delivery through a try/catch self-call capped at a fixed gas
///         stipend, and pays the protocol fee and seller only if that
///         delivery succeeds. A failed delivery pays nobody; both the ETH and
///         the lot stay escrowed and the delivery is retryable by anyone
///         through claimLot. If the lot is still undelivered
///         PENDING_DELIVERY_TIMEOUT after deferral, unwindStuckLot retries
///         delivery once more and, on a second failure, unwinds the sale:
///         the winner's bid is credited to pendingRefunds for withdrawal and
///         the lot is returned to the seller. If that return also fails, the
///         lot stays locked until returnUnwoundLot succeeds. The token
///         transfer is always the last external interaction before any
///         payout takes effect, so no seller-controlled callback can run
///         after the lot has moved and before the seller is paid. V1 clones
///         are immutable and remain governed by their original
///         implementation.
contract SovereignAuctionHouseV2 is
    ISovereignAuctionHouseV2,
    IERC1155Receiver,
    Initializable,
    ReentrancyGuard,
    OwnableUpgradeable
{
    bytes4 private constant ERC721_INTERFACE_ID = 0x80ac58cd;
    bytes4 private constant ERC1155_INTERFACE_ID = 0xd9b67a26;

    uint256 public constant TIME_BUFFER = 15 minutes;
    uint16 public constant MIN_BID_INCREMENT_BPS = 500;
    uint256 public constant MAX_DURATION = 365 days * 100;

    error AuctionDoesNotExist();
    error AuctionAlreadyStarted();
    error AuctionExpired();
    error AuctionNotEnded();
    error AuctionHasNoBids();
    error AuctionAlreadyExistsForToken();
    error BidBelowReserve();
    error BidBelowMinimum();
    error BidMustBePositive();
    error EscrowFailed();
    error DeliveryFailed();
    error FundsRecipientRequired();
    error OnlySelf();
    error OwnershipLocked();
    error AuctionAlreadySettled();
    error NoPendingDelivery();
    error NoPendingReturn();
    error NotWinner();
    error InsufficientGas();
    error UnwindTooEarly();

    uint256 internal constant DELIVER_GAS_LIMIT = 500_000;

    /// @notice A deferred lot still undelivered after this timeout becomes
    ///         eligible for unwindStuckLot, which retries delivery once more
    ///         and, if that also fails, unwinds the sale.
    uint64 public constant PENDING_DELIVERY_TIMEOUT = 30 days;

    mapping(uint256 => Auction) public auctions;
    mapping(uint256 => uint64) public listingExpiry;

    /// @notice True for an auction whose delivery attempt at endAuction
    ///         failed. Neither the seller nor the protocol fee has been
    ///         paid. The auction record, and its `_auctionIdByToken` entry,
    ///         stay in storage until claimLot or unwindStuckLot resolves it.
    mapping(uint256 => bool) public pendingDelivery;

    /// @notice Timestamp a lot entered pendingDelivery, keyed by auctionId.
    ///         Set in endAuction's deferral branch; read by unwindStuckLot to
    ///         enforce PENDING_DELIVERY_TIMEOUT.
    mapping(uint256 => uint64) public deliveryDeferredAt;

    /// @notice True for an auction that unwindStuckLot unwound but whose lot
    ///         return to the seller failed. The winner's bid is already
    ///         credited to pendingRefunds; the auction record and its
    ///         `_auctionIdByToken` entry stay in storage, locking the lot,
    ///         until returnUnwoundLot delivers it to the seller.
    mapping(uint256 => bool) public pendingReturn;

    // A settled-but-undelivered lot keeps its entry here, which blocks a
    // duplicate listing and stuck-token recovery for the same token until
    // claimLot, unwindStuckLot, or returnUnwoundLot clears it.
    mapping(address => mapping(uint256 => uint256)) private _auctionIdByToken;
    mapping(address => uint256) public pendingRefunds;

    uint16 public protocolFeeBps;
    address payable public feeRecipient;
    uint256 private _nextAuctionId;

    // A safe ERC1155 transfer invokes the receiver. Bind that callback to the
    // exact pull underway so an unrelated token cannot be sent into custody.
    address private _pull1155Token;
    uint256 private _pull1155Id;
    uint256 private _pull1155Quantity;

    modifier auctionExists(uint256 auctionId) {
        if (!_exists(auctionId)) revert AuctionDoesNotExist();
        _;
    }

    constructor() {
        _disableInitializers();
    }

    function initialize(
        address initialOwner,
        address payable feeRecipient_,
        uint16 protocolFeeBps_
    ) external initializer {
        require(initialOwner != address(0), "owner required");
        require(protocolFeeBps_ <= 500, "fee above cap");
        require(
            protocolFeeBps_ == 0 || feeRecipient_ != address(0),
            "fee recipient required when fee > 0"
        );
        __Ownable_init(initialOwner);
        feeRecipient = feeRecipient_;
        protocolFeeBps = protocolFeeBps_;
    }

    function transferOwnership(address) public pure override {
        revert OwnershipLocked();
    }

    function renounceOwnership() public pure override {
        revert OwnershipLocked();
    }

    function createAuction(
        uint256 tokenId,
        address tokenContract,
        uint256 duration,
        uint256 reservePrice,
        uint64 listingExpiry_
    ) external override nonReentrant onlyOwner returns (uint256) {
        return _createAuction(tokenId, tokenContract, duration, reservePrice, listingExpiry_);
    }

    /// @notice One listingExpiry_ applies to every auction created in the batch.
    function bulkCreateAuctions(
        address tokenContract,
        uint256[] calldata tokenIds,
        uint256 reservePrice,
        uint256 duration,
        uint64 listingExpiry_
    ) external nonReentrant onlyOwner returns (uint256[] memory auctionIds) {
        auctionIds = new uint256[](tokenIds.length);
        for (uint256 i; i < tokenIds.length; ++i) {
            auctionIds[i] = _createAuction(tokenIds[i], tokenContract, duration, reservePrice, listingExpiry_);
        }
    }

    function _createAuction(
        uint256 tokenId,
        address tokenContract,
        uint256 duration,
        uint256 reservePrice,
        uint64 listingExpiry_
    ) internal returns (uint256 auctionId) {
        require(IERC165(tokenContract).supportsInterface(ERC721_INTERFACE_ID), "tokenContract is not ERC721");
        _validateDuration(duration);
        require(listingExpiry_ == 0 || listingExpiry_ > block.timestamp, "expiry must be future");
        if (_auctionIdByToken[tokenContract][tokenId] != 0) revert AuctionAlreadyExistsForToken();

        address tokenOwner = IERC721(tokenContract).ownerOf(tokenId);
        require(
            msg.sender == tokenOwner ||
                msg.sender == IERC721(tokenContract).getApproved(tokenId) ||
                IERC721(tokenContract).isApprovedForAll(tokenOwner, msg.sender),
            "Not token owner or approved"
        );

        auctionId = _nextAuctionId++;
        auctions[auctionId] = Auction({
            tokenId: tokenId,
            tokenContract: tokenContract,
            firstBidTime: 0,
            amount: 0,
            reservePrice: reservePrice,
            tokenOwner: tokenOwner,
            fundsRecipient: payable(tokenOwner),
            endTime: 0,
            bidder: payable(address(0)),
            duration: uint64(duration),
            quantity: 1,
            standard: TokenStandard.ERC721
        });
        _auctionIdByToken[tokenContract][tokenId] = auctionId + 1;
        if (listingExpiry_ != 0) listingExpiry[auctionId] = listingExpiry_;

        IERC721(tokenContract).transferFrom(tokenOwner, address(this), tokenId);
        if (IERC721(tokenContract).ownerOf(tokenId) != address(this)) revert EscrowFailed();

        emit AuctionCreated(
            auctionId,
            tokenId,
            tokenContract,
            duration,
            reservePrice,
            tokenOwner,
            tokenOwner,
            listingExpiry_
        );
    }

    /// @notice Escrows one indivisible ERC1155 lot. Unlike ERC721, ERC1155
    ///         has no ownerOf, so only this house's owner may list its balance.
    function create1155Auction(
        uint256 tokenId,
        address tokenContract,
        uint256 quantity,
        uint256 duration,
        uint256 reservePrice,
        uint64 listingExpiry_
    ) external override onlyOwner nonReentrant returns (uint256 auctionId) {
        require(IERC165(tokenContract).supportsInterface(ERC1155_INTERFACE_ID), "tokenContract is not ERC1155");
        require(quantity != 0, "quantity zero");
        _validateDuration(duration);
        require(listingExpiry_ == 0 || listingExpiry_ > block.timestamp, "expiry must be future");
        if (_auctionIdByToken[tokenContract][tokenId] != 0) revert AuctionAlreadyExistsForToken();
        require(IERC1155(tokenContract).balanceOf(msg.sender, tokenId) >= quantity, "insufficient balance");
        require(IERC1155(tokenContract).isApprovedForAll(msg.sender, address(this)), "house not approved");

        auctionId = _nextAuctionId++;
        auctions[auctionId] = Auction({
            tokenId: tokenId,
            tokenContract: tokenContract,
            firstBidTime: 0,
            amount: 0,
            reservePrice: reservePrice,
            tokenOwner: msg.sender,
            fundsRecipient: payable(msg.sender),
            endTime: 0,
            bidder: payable(address(0)),
            duration: uint64(duration),
            quantity: quantity,
            standard: TokenStandard.ERC1155
        });
        _auctionIdByToken[tokenContract][tokenId] = auctionId + 1;
        if (listingExpiry_ != 0) listingExpiry[auctionId] = listingExpiry_;
        _pull1155(tokenContract, tokenId, quantity, msg.sender);
        emit Auction1155Created(
            auctionId, tokenId, tokenContract, quantity, duration, reservePrice, msg.sender, msg.sender, listingExpiry_
        );
    }

    function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice)
        external
        override
        nonReentrant
        auctionExists(auctionId)
    {
        Auction storage a = auctions[auctionId];
        require(msg.sender == a.tokenOwner, "Not token owner");
        if (a.firstBidTime != 0) revert AuctionAlreadyStarted();
        a.reservePrice = reservePrice;
        emit AuctionReservePriceUpdated(auctionId, reservePrice);
    }

    /// @notice Lets the captured NFT owner choose any bounded duration before
    ///         bidding starts. The duration is immutable once a bid lands.
    function setAuctionDuration(uint256 auctionId, uint256 duration)
        external
        override
        nonReentrant
        auctionExists(auctionId)
    {
        Auction storage a = auctions[auctionId];
        require(msg.sender == a.tokenOwner, "Not token owner");
        if (a.firstBidTime != 0) revert AuctionAlreadyStarted();
        _validateDuration(duration);
        a.duration = uint64(duration);
        emit AuctionDurationUpdated(auctionId, duration);
    }

    /// @notice Direct sale proceeds before bidding starts. An approved house
    ///         owner cannot redirect a third-party token owner's proceeds.
    function setAuctionFundsRecipient(uint256 auctionId, address payable fundsRecipient)
        external
        override
        nonReentrant
        auctionExists(auctionId)
    {
        Auction storage a = auctions[auctionId];
        require(msg.sender == a.tokenOwner, "Not token owner");
        if (a.firstBidTime != 0) revert AuctionAlreadyStarted();
        if (fundsRecipient == address(0)) revert FundsRecipientRequired();
        a.fundsRecipient = fundsRecipient;
        emit AuctionFundsRecipientUpdated(auctionId, fundsRecipient);
    }

    /// @notice Optionally lets the captured owner set a no-bid listing expiry.
    ///         Zero means the listing stays open until canceled by its owner.
    function setAuctionListingExpiry(uint256 auctionId, uint64 expiry)
        external
        override
        nonReentrant
        auctionExists(auctionId)
    {
        Auction storage a = auctions[auctionId];
        require(msg.sender == a.tokenOwner, "Not token owner");
        if (a.firstBidTime != 0) revert AuctionAlreadyStarted();
        require(expiry == 0 || expiry > block.timestamp, "expiry must be future");
        listingExpiry[auctionId] = expiry;
        emit AuctionListingExpiryUpdated(auctionId, expiry);
    }

    function createBid(uint256 auctionId)
        external
        payable
        override
        auctionExists(auctionId)
        nonReentrant
    {
        Auction storage a = auctions[auctionId];
        uint64 expiry = listingExpiry[auctionId];
        if (a.firstBidTime == 0 && expiry != 0 && block.timestamp >= expiry) revert AuctionExpired();
        uint256 amount = msg.value;
        if (amount == 0) revert BidMustBePositive();
        if (a.firstBidTime != 0 && block.timestamp >= a.endTime) revert AuctionExpired();
        if (amount < a.reservePrice) revert BidBelowReserve();
        if (a.amount != 0) {
            uint256 increment = (a.amount * MIN_BID_INCREMENT_BPS) / 10_000;
            if (increment == 0) increment = 1;
            if (amount < a.amount + increment) revert BidBelowMinimum();
        }

        bool firstBid = a.firstBidTime == 0;
        address payable lastBidder = a.bidder;
        uint256 previousAmount = a.amount;
        if (firstBid) {
            a.firstBidTime = uint64(block.timestamp);
            a.endTime = uint64(block.timestamp + a.duration);
        }
        a.amount = amount;
        a.bidder = payable(msg.sender);
        if (!firstBid) {
            _sendOrCredit(lastBidder, previousAmount);
        }

        bool extended;
        if (a.endTime - block.timestamp < TIME_BUFFER) {
            a.endTime = uint64(block.timestamp + TIME_BUFFER);
            extended = true;
        }
        emit AuctionBid(auctionId, msg.sender, amount, firstBid, extended);
        if (extended) emit AuctionEndTimeUpdated(auctionId, a.endTime);
    }

    /// @notice Resolves every ended auction. Attempts token delivery through
    ///         a try/catch self-call capped at DELIVER_GAS_LIMIT gas, so the
    ///         outcome cannot depend on how much gas the caller of endAuction
    ///         supplied. The protocol fee and seller are paid only if that
    ///         delivery succeeds, through _finalizeSale. A failed delivery
    ///         pays nobody: the auction is marked pendingDelivery for a
    ///         permissionless retry via claimLot, and the winning bid stays
    ///         in the contract. Because delivery is attempted before any
    ///         payout, no seller-controlled callback can run between the lot
    ///         leaving escrow and the seller being paid.
    function endAuction(uint256 auctionId)
        external
        override
        auctionExists(auctionId)
        nonReentrant
    {
        Auction memory a = auctions[auctionId];
        if (a.firstBidTime == 0) revert AuctionHasNoBids();
        if (block.timestamp < a.endTime) revert AuctionNotEnded();
        if (pendingDelivery[auctionId]) revert AuctionAlreadySettled();
        if (pendingReturn[auctionId]) revert AuctionAlreadySettled();

        // EIP-150 forwards at most 63/64 of remaining gas, so a gas-starved
        // call could hand delivery less than DELIVER_GAS_LIMIT and defer a
        // transfer that would have succeeded. Require enough headroom that
        // the stipend is always honored in full.
        if (gasleft() < DELIVER_GAS_LIMIT + 80_000) revert InsufficientGas();

        bool delivered;
        if (a.standard == TokenStandard.ERC721) {
            try this.deliverERC721{gas: DELIVER_GAS_LIMIT}(a.tokenContract, a.tokenId, a.bidder) {
                delivered = true;
            } catch {}
        } else {
            try this.deliverERC1155{gas: DELIVER_GAS_LIMIT}(a.tokenContract, a.tokenId, a.quantity, a.bidder) {
                delivered = true;
            } catch {}
        }

        if (delivered) {
            _finalizeSale(auctionId, a);
        } else {
            pendingDelivery[auctionId] = true;
            deliveryDeferredAt[auctionId] = uint64(block.timestamp);
            emit DeliveryDeferred(auctionId, a.bidder);
        }
    }

    /// @dev Runs only once delivery has been verified. Deletes all per-lot
    ///      storage first, then pays the protocol fee and seller through
    ///      _payout. Deleting state before paying means a reentrant call
    ///      during the payout sees a cleared auction record, not a settled
    ///      one it could act on again.
    function _finalizeSale(uint256 auctionId, Auction memory a) internal {
        delete auctions[auctionId];
        delete _auctionIdByToken[a.tokenContract][a.tokenId];
        delete listingExpiry[auctionId];
        delete pendingDelivery[auctionId];
        delete deliveryDeferredAt[auctionId];
        delete pendingReturn[auctionId];

        uint256 protocolFee;
        if (protocolFeeBps != 0) {
            protocolFee = (a.amount * protocolFeeBps) / 10_000;
            _payout(feeRecipient, protocolFee);
        }
        uint256 sellerProceeds = a.amount - protocolFee;
        _payout(a.fundsRecipient, sellerProceeds);
        emit AuctionEnded(auctionId, a.tokenOwner, a.bidder, sellerProceeds, protocolFee);
    }

    /// @dev Delivery target for endAuction's and unwindStuckLot's gas-capped
    ///      try/catch self-calls. Used both to deliver to the winner and,
    ///      from unwindStuckLot, to return the lot to the seller: `to` is
    ///      whichever recipient the caller supplies, not necessarily the
    ///      auction's recorded winner. Reverting here rolls back the
    ///      transfer and its ownerOf verification together.
    function deliverERC721(address tokenContract, uint256 tokenId, address to) external {
        if (msg.sender != address(this)) revert OnlySelf();
        IERC721(tokenContract).transferFrom(address(this), to, tokenId);
        if (IERC721(tokenContract).ownerOf(tokenId) != to) revert DeliveryFailed();
    }

    function deliverERC1155(address tokenContract, uint256 tokenId, uint256 quantity, address to) external {
        if (msg.sender != address(this)) revert OnlySelf();
        uint256 beforeBalance = IERC1155(tokenContract).balanceOf(to, tokenId);
        IERC1155(tokenContract).safeTransferFrom(address(this), to, tokenId, quantity, "");
        if (IERC1155(tokenContract).balanceOf(to, tokenId) < beforeBalance + quantity) revert DeliveryFailed();
    }

    /// @notice Delivery of a lot deferred by endAuction. Anyone may call this
    ///         to trigger delivery to the recorded winner (`to` must be
    ///         address(0) in that case), which lets a keeper rescue a winner
    ///         that has no way to call this itself. Only the recorded winner
    ///         may redirect delivery elsewhere via a nonzero `to`. Runs with
    ///         full gas and no try/catch, so a revert rolls back the whole
    ///         call and leaves the claim retryable. Delivery happens before
    ///         the auction record is cleared and the seller is paid, so no
    ///         external code runs between the lot moving and the seller's
    ///         payout except the payout call itself. The redirect is
    ///         best-effort: the pending state is consumed by whichever call
    ///         succeeds first, so a third party triggering delivery to the
    ///         winner with `to == address(0)` before the winner redirects
    ///         permanently forecloses that redirect. The token always still
    ///         reaches the winner's own bid address in that case.
    function claimLot(uint256 auctionId, address to) external override nonReentrant {
        if (!pendingDelivery[auctionId]) revert NoPendingDelivery();
        Auction memory a = auctions[auctionId];
        if (msg.sender != a.bidder && to != address(0)) revert NotWinner();

        address recipient = to == address(0) ? a.bidder : to;

        if (a.standard == TokenStandard.ERC721) {
            IERC721(a.tokenContract).transferFrom(address(this), recipient, a.tokenId);
            if (IERC721(a.tokenContract).ownerOf(a.tokenId) != recipient) revert DeliveryFailed();
        } else {
            uint256 beforeBalance = IERC1155(a.tokenContract).balanceOf(recipient, a.tokenId);
            IERC1155(a.tokenContract).safeTransferFrom(address(this), recipient, a.tokenId, a.quantity, "");
            if (IERC1155(a.tokenContract).balanceOf(recipient, a.tokenId) < beforeBalance + a.quantity) {
                revert DeliveryFailed();
            }
        }

        _finalizeSale(auctionId, a);
        emit LotClaimed(auctionId, a.bidder, recipient);
    }

    /// @notice Resolves a lot still pendingDelivery PENDING_DELIVERY_TIMEOUT
    ///         after deferral. Anyone may call this. It first retries capped
    ///         delivery to the recorded winner, exactly as endAuction did: a
    ///         delivery failure can be temporary (a paused collection
    ///         unpauses, a receiver later becomes compatible), so this is not
    ///         a straight unwind. If that retry succeeds, the sale finalizes
    ///         normally and the seller is paid. If it fails again, the sale
    ///         unwinds: the winner's full bid is credited to pendingRefunds
    ///         for withdrawal, unconditionally, before any token movement is
    ///         attempted, and a capped attempt returns the lot to the seller.
    ///         If that return also fails, the lot stays locked, escrowed and
    ///         un-relistable, until returnUnwoundLot succeeds. Nobody is paid
    ///         from this function unless the winner ends up holding the lot.
    /// @dev Sized for two capped self-calls (retry-to-winner, then
    ///      return-to-seller) so a gas-starved caller cannot force either
    ///      attempt to run under-stipend and be misclassified as a genuine
    ///      delivery failure.
    function unwindStuckLot(uint256 auctionId) external nonReentrant auctionExists(auctionId) {
        if (!pendingDelivery[auctionId]) revert NoPendingDelivery();
        if (block.timestamp <= deliveryDeferredAt[auctionId] + PENDING_DELIVERY_TIMEOUT) revert UnwindTooEarly();
        Auction memory a = auctions[auctionId];

        if (gasleft() < 2 * DELIVER_GAS_LIMIT + 100_000) revert InsufficientGas();

        bool delivered;
        if (a.standard == TokenStandard.ERC721) {
            try this.deliverERC721{gas: DELIVER_GAS_LIMIT}(a.tokenContract, a.tokenId, a.bidder) {
                delivered = true;
            } catch {}
        } else {
            try this.deliverERC1155{gas: DELIVER_GAS_LIMIT}(a.tokenContract, a.tokenId, a.quantity, a.bidder) {
                delivered = true;
            } catch {}
        }

        if (delivered) {
            _finalizeSale(auctionId, a);
            emit LotClaimed(auctionId, a.bidder, a.bidder);
            return;
        }

        delete pendingDelivery[auctionId];
        delete deliveryDeferredAt[auctionId];

        // Credited before any token movement is attempted: the winner's
        // refund never depends on whether the lot can be returned.
        pendingRefunds[a.bidder] += a.amount;
        emit RefundCredited(a.bidder, a.amount);

        bool returned;
        if (a.standard == TokenStandard.ERC721) {
            try this.deliverERC721{gas: DELIVER_GAS_LIMIT}(a.tokenContract, a.tokenId, a.tokenOwner) {
                returned = true;
            } catch {}
        } else {
            try this.deliverERC1155{gas: DELIVER_GAS_LIMIT}(a.tokenContract, a.tokenId, a.quantity, a.tokenOwner) {
                returned = true;
            } catch {}
        }

        if (returned) {
            delete auctions[auctionId];
            delete _auctionIdByToken[a.tokenContract][a.tokenId];
            delete listingExpiry[auctionId];
        } else {
            pendingReturn[auctionId] = true;
            emit LotReturnDeferred(auctionId, a.tokenOwner);
        }

        emit LotUnwound(auctionId, a.bidder, a.amount, a.tokenOwner);
    }

    /// @notice Delivers a lot whose return to the seller failed during
    ///         unwindStuckLot. Anyone may call this; it only ever delivers to
    ///         the auction's recorded tokenOwner. Runs with full gas and no
    ///         try/catch, so a revert rolls back the whole call and leaves
    ///         the return retryable.
    function returnUnwoundLot(uint256 auctionId) external nonReentrant auctionExists(auctionId) {
        if (!pendingReturn[auctionId]) revert NoPendingReturn();
        Auction memory a = auctions[auctionId];

        if (a.standard == TokenStandard.ERC721) {
            IERC721(a.tokenContract).transferFrom(address(this), a.tokenOwner, a.tokenId);
            if (IERC721(a.tokenContract).ownerOf(a.tokenId) != a.tokenOwner) revert DeliveryFailed();
        } else {
            uint256 beforeBalance = IERC1155(a.tokenContract).balanceOf(a.tokenOwner, a.tokenId);
            IERC1155(a.tokenContract).safeTransferFrom(address(this), a.tokenOwner, a.tokenId, a.quantity, "");
            if (IERC1155(a.tokenContract).balanceOf(a.tokenOwner, a.tokenId) < beforeBalance + a.quantity) {
                revert DeliveryFailed();
            }
        }

        delete pendingReturn[auctionId];
        delete auctions[auctionId];
        delete _auctionIdByToken[a.tokenContract][a.tokenId];
        delete listingExpiry[auctionId];
        emit LotReturned(auctionId, a.tokenOwner);
    }

    function cancelAuction(uint256 auctionId)
        external
        override
        nonReentrant
        auctionExists(auctionId)
    {
        Auction memory a = auctions[auctionId];
        require(msg.sender == a.tokenOwner, "Not token owner");
        if (a.firstBidTime != 0) revert AuctionAlreadyStarted();
        if (a.standard == TokenStandard.ERC721) {
            IERC721(a.tokenContract).transferFrom(address(this), a.tokenOwner, a.tokenId);
            if (IERC721(a.tokenContract).ownerOf(a.tokenId) != a.tokenOwner) revert DeliveryFailed();
        } else {
            uint256 beforeBalance = IERC1155(a.tokenContract).balanceOf(a.tokenOwner, a.tokenId);
            IERC1155(a.tokenContract).safeTransferFrom(address(this), a.tokenOwner, a.tokenId, a.quantity, "");
            if (IERC1155(a.tokenContract).balanceOf(a.tokenOwner, a.tokenId) < beforeBalance + a.quantity) {
                revert DeliveryFailed();
            }
        }
        delete _auctionIdByToken[a.tokenContract][a.tokenId];
        delete auctions[auctionId];
        delete listingExpiry[auctionId];
        emit AuctionCanceled(auctionId);
    }

    /// @notice Anyone may clear a no-bid listing once its owner-selected
    ///         expiry has passed. The lot is always returned to that owner.
    function expireAuction(uint256 auctionId) external override nonReentrant auctionExists(auctionId) {
        Auction memory a = auctions[auctionId];
        uint64 expiry = listingExpiry[auctionId];
        if (a.firstBidTime != 0 || expiry == 0 || block.timestamp < expiry) revert AuctionNotEnded();
        if (a.standard == TokenStandard.ERC721) {
            IERC721(a.tokenContract).transferFrom(address(this), a.tokenOwner, a.tokenId);
            if (IERC721(a.tokenContract).ownerOf(a.tokenId) != a.tokenOwner) revert DeliveryFailed();
        } else {
            uint256 beforeBalance = IERC1155(a.tokenContract).balanceOf(a.tokenOwner, a.tokenId);
            IERC1155(a.tokenContract).safeTransferFrom(address(this), a.tokenOwner, a.tokenId, a.quantity, "");
            if (IERC1155(a.tokenContract).balanceOf(a.tokenOwner, a.tokenId) < beforeBalance + a.quantity) {
                revert DeliveryFailed();
            }
        }
        delete _auctionIdByToken[a.tokenContract][a.tokenId];
        delete auctions[auctionId];
        delete listingExpiry[auctionId];
        emit AuctionCanceled(auctionId);
    }

    function withdrawRefund() external override nonReentrant {
        _withdrawRefund(payable(msg.sender));
    }

    function withdrawRefundTo(address payable recipient) external override nonReentrant {
        if (recipient == address(0)) revert FundsRecipientRequired();
        _withdrawRefund(recipient);
    }

    function _withdrawRefund(address payable recipient) internal {
        uint256 amount = pendingRefunds[msg.sender];
        require(amount != 0, "No refund available");
        pendingRefunds[msg.sender] = 0;
        (bool sent,) = recipient.call{value: amount}("");
        require(sent, "Withdraw failed");
        emit RefundWithdrawn(msg.sender, recipient, amount);
    }

    function recoverStuckERC721(address tokenContract, uint256 tokenId, address to)
        external
        onlyOwner
        nonReentrant
    {
        require(to != address(0), "to required");
        if (_auctionIdByToken[tokenContract][tokenId] != 0) revert AuctionAlreadyExistsForToken();
        IERC721(tokenContract).transferFrom(address(this), to, tokenId);
        emit StuckERC721Recovered(tokenContract, tokenId, to);
    }

    function recoverStuckERC1155(address tokenContract, uint256 tokenId, uint256 quantity, address to)
        external
        onlyOwner
        nonReentrant
    {
        require(to != address(0), "to required");
        if (_auctionIdByToken[tokenContract][tokenId] != 0) revert AuctionAlreadyExistsForToken();
        uint256 beforeBalance = IERC1155(tokenContract).balanceOf(to, tokenId);
        IERC1155(tokenContract).safeTransferFrom(address(this), to, tokenId, quantity, "");
        if (IERC1155(tokenContract).balanceOf(to, tokenId) < beforeBalance + quantity) revert DeliveryFailed();
        emit StuckERC1155Recovered(tokenContract, tokenId, quantity, to);
    }

    /// @inheritdoc ISovereignAuctionHouseV2
    function getAuction(uint256 auctionId) external view override returns (Auction memory) {
        return auctions[auctionId];
    }

    function getAuctionFor(address tokenContract, uint256 tokenId) external view returns (bool exists, uint256 auctionId) {
        uint256 stored = _auctionIdByToken[tokenContract][tokenId];
        return stored == 0 ? (false, 0) : (true, stored - 1);
    }

    function nextAuctionId() external view returns (uint256) {
        return _nextAuctionId;
    }

    /// @notice Distinguishes V2 tuple layout from the immutable V1 ABI.
    function auctionVersion() external pure returns (uint8) {
        return 2;
    }

    function supportsInterface(bytes4 interfaceId) external pure override returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || interfaceId == type(IERC165).interfaceId;
    }

    function onERC1155Received(address, address, uint256 id, uint256 value, bytes calldata)
        external
        view
        override
        returns (bytes4)
    {
        if (msg.sender != _pull1155Token || id != _pull1155Id || value != _pull1155Quantity) revert EscrowFailed();
        return IERC1155Receiver.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata)
        external
        pure
        override
        returns (bytes4)
    {
        revert EscrowFailed();
    }

    /// @dev Outbid-refund path in createBid only. Runs before any delivery
    ///      has been attempted, so the recipient's code, if any, cannot use
    ///      this callback to affect the lot. Pushes with a 30_000 gas
    ///      stipend and credits pendingRefunds on failure.
    function _sendOrCredit(address to, uint256 amount) internal {
        if (amount == 0) return;
        (bool sent,) = to.call{value: amount, gas: 30_000}("");
        if (!sent) {
            pendingRefunds[to] += amount;
            emit RefundCredited(to, amount);
        }
    }

    /// @dev Seller-proceeds and protocol-fee payout leg of settlement, used
    ///      only after delivery has been verified. An EOA recipient (no
    ///      code) is pushed a 30_000 gas call; a contract recipient
    ///      (including an EIP-7702-delegated account, which has code) is
    ///      never called at all and is instead credited to pendingRefunds
    ///      for a pull withdrawal. Settlement runs after delivery, so no
    ///      external code may execute after the lot has moved: routing every
    ///      contract recipient through a pull, rather than a push callback
    ///      that could run at this point, closes that off without needing to
    ///      pay before delivery.
    function _payout(address to, uint256 amount) internal {
        if (amount == 0) return;
        if (to.code.length == 0) {
            (bool sent,) = to.call{value: amount, gas: 30_000}("");
            if (sent) return;
        }
        pendingRefunds[to] += amount;
        emit RefundCredited(to, amount);
    }

    function _pull1155(address tokenContract, uint256 tokenId, uint256 quantity, address from) internal {
        uint256 beforeBalance = IERC1155(tokenContract).balanceOf(address(this), tokenId);
        _pull1155Token = tokenContract;
        _pull1155Id = tokenId;
        _pull1155Quantity = quantity;
        IERC1155(tokenContract).safeTransferFrom(from, address(this), tokenId, quantity, "");
        _pull1155Token = address(0);
        _pull1155Id = 0;
        _pull1155Quantity = 0;
        if (IERC1155(tokenContract).balanceOf(address(this), tokenId) < beforeBalance + quantity) revert EscrowFailed();
    }

    function _validateDuration(uint256 duration) internal pure {
        require(duration != 0, "duration zero");
        require(duration <= MAX_DURATION, "duration too large");
    }

    function _exists(uint256 auctionId) internal view returns (bool) {
        return auctions[auctionId].tokenOwner != address(0);
    }

    receive() external payable {
        revert("Direct ETH not accepted");
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "erc721a-upgradeable/=lib/ERC721A-Upgradeable/",
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "ERC721A-Upgradeable/=lib/ERC721A-Upgradeable/contracts/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.