Skip to content
Verified contractExactMIT

InventorySale

Address0x3d103ea1c6c05ef939a22c85b4355f889d26b3be
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.37

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.37+commit.f401782d
Language
solidity
Optimization
No
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,358,754
Creation transaction
0xa30edcff4b…9c41e61612

src/InventorySale.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.37;

import { ReentrancyGuard } from "../vendor/openzeppelin/ReentrancyGuard.sol";
import { ICore721, IERC721Receiver } from "./interfaces/IMedallionsDependencies.sol";
import { RevenueLedger } from "./RevenueLedger.sol";

/// @notice Sequential sale of existing Medallions #134–#421. Never mints tokens.
/// @dev No Core extension/admin registration, proxy, mutable economics or arbitrary calls.
contract InventorySale is ReentrancyGuard, IERC721Receiver {
    address public constant CORE = 0x624C2f90C9861E0a1169fbf617b28E660B7218eB;
    uint256 public constant FIRST_TOKEN = 134;
    uint256 public constant LAST_TOKEN = 421;
    uint256 public constant MAX_QUANTITY = 8;
    uint256 public constant CURVE_K = 10_412_160_000_000_000_000_000;

    enum SaleState {
        Setup,
        Active,
        Paused,
        Closed,
        SoldOut
    }
    SaleState public state;
    uint256 public nextTokenId = FIRST_TOKEN;
    address public immutable controller;
    address public immutable recovery;
    RevenueLedger public immutable ledger;

    error InvalidAddress();
    error OnlyController();
    error WrongState();
    error InvalidToken(uint256 tokenId);
    error InvalidQuantity();
    error StaleFirstToken(uint256 expected, uint256 actual);
    error IncorrectPayment(uint256 expected, uint256 actual);
    error InventoryMissing(uint256 tokenId);
    error TokensNotIncreasing();
    error InvalidDeposit();

    event StateChanged(SaleState previous, SaleState current);
    event Purchased(
        address indexed buyer, uint256 indexed firstTokenId, uint256 quantity, uint256 amount
    );
    event Recovered(uint256 indexed tokenId, address indexed recipient);

    constructor(address controller_, address recovery_) {
        if (
            controller_ == address(0) || recovery_ == address(0) || controller_ == address(this)
                || recovery_ == address(this)
        ) revert InvalidAddress();
        controller = controller_;
        recovery = recovery_;
        // Constructor-created child eliminates any temporary setter, linkage race,
        // or dependency on predicting an externally deployed contract address.
        ledger = new RevenueLedger();
    }

    modifier onlyController() {
        if (msg.sender != controller) revert OnlyController();
        _;
    }

    /// @notice Number of unsold positions; after closure some may already be recovered.
    function remainingInventory() external view returns (uint256) {
        return LAST_TOKEN + 1 - nextTokenId;
    }

    /// @notice Price for an individual inventory ID, in wei. Both divisions floor separately.
    function price(uint256 tokenId) public pure returns (uint256) {
        if (tokenId < FIRST_TOKEN || tokenId > LAST_TOKEN) revert InvalidToken(tokenId);
        uint256 remaining = LAST_TOKEN + 2 - tokenId;
        return CURVE_K / (remaining - 1) - CURVE_K / remaining;
    }

    /// @dev A quote is not a reservation or a statement that the sale is active.
    function quote(uint256 expectedFirst, uint256 quantity) public view returns (uint256 total) {
        if (expectedFirst != nextTokenId) revert StaleFirstToken(expectedFirst, nextTokenId);
        if (quantity == 0 || quantity > MAX_QUANTITY || quantity > LAST_TOKEN + 1 - expectedFirst) {
            revert InvalidQuantity();
        }
        for (uint256 i; i < quantity; ++i) {
            total += price(expectedFirst + i);
        }
    }

    /// @notice Activate only after every committed existing artwork is in escrow.
    function activate() external onlyController nonReentrant {
        if (state != SaleState.Setup) revert WrongState();
        for (uint256 id = FIRST_TOKEN; id <= LAST_TOKEN; ++id) {
            if (ICore721(CORE).ownerOf(id) != address(this)) revert InventoryMissing(id);
        }
        _setState(SaleState.Active);
    }

    /// @notice Purchase 1–8 consecutive existing artworks to the calling account only.
    function buy(uint256 expectedFirst, uint256 quantity) external payable nonReentrant {
        if (state != SaleState.Active) revert WrongState();
        uint256 total = quote(expectedFirst, quantity);
        if (msg.value != total) revert IncorrectPayment(total, msg.value);
        nextTokenId = expectedFirst + quantity;
        if (nextTokenId > LAST_TOKEN) _setState(SaleState.SoldOut);
        // Funding and every delivery are one transaction. Any downstream failure
        // rolls back all state, transfers, payments and logs, including nested claims.
        ledger.fund{ value: total }();
        for (uint256 i; i < quantity; ++i) {
            ICore721(CORE).safeTransferFrom(address(this), msg.sender, expectedFirst + i);
        }
        emit Purchased(msg.sender, expectedFirst, quantity, total);
    }

    function pause() external onlyController nonReentrant {
        if (state != SaleState.Active) revert WrongState();
        _setState(SaleState.Paused);
    }

    function resume() external onlyController nonReentrant {
        if (state != SaleState.Paused) revert WrongState();
        _setState(SaleState.Active);
    }

    /// @notice Irreversibly end this sale; does not pause or change the claims ledger.
    /// @dev Also available during setup if loading the full inventory cannot be completed.
    function close() external onlyController nonReentrant {
        if (state == SaleState.Closed) revert WrongState();
        _setState(SaleState.Closed);
    }

    /// @notice After closure, return up to eight unsold works to the fixed recovery address.
    /// @dev IDs may be chosen for batching only after the entire sale is permanently closed.
    function recover(uint256[] calldata tokenIds) external onlyController nonReentrant {
        if (state != SaleState.Closed) revert WrongState();
        uint256 count = tokenIds.length;
        if (count == 0 || count > MAX_QUANTITY) revert InvalidQuantity();
        uint256 previous;
        for (uint256 i; i < count; ++i) {
            uint256 id = tokenIds[i];
            if (id < nextTokenId || id > LAST_TOKEN) revert InvalidToken(id);
            if (id <= previous) revert TokensNotIncreasing();
            previous = id;
            if (ICore721(CORE).ownerOf(id) != address(this)) revert InventoryMissing(id);
        }
        for (uint256 i; i < count; ++i) {
            ICore721(CORE).safeTransferFrom(address(this), recovery, tokenIds[i]);
            emit Recovered(tokenIds[i], recovery);
        }
    }

    /// @dev Accept safe deposits of the committed Core inventory only, during setup.
    ///      Unsafe transferFrom can bypass ERC721 receiver hooks; do not send other assets.
    function onERC721Received(address, address, uint256 tokenId, bytes calldata)
        external
        view
        returns (bytes4)
    {
        if (
            msg.sender != CORE || state != SaleState.Setup || tokenId < FIRST_TOKEN
                || tokenId > LAST_TOKEN
        ) revert InvalidDeposit();
        return IERC721Receiver.onERC721Received.selector;
    }

    function _setState(SaleState next) private {
        SaleState previous = state;
        state = next;
        emit StateChanged(previous, next);
    }
}

src/RevenueLedger.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.37;

import { ReentrancyGuard } from "../vendor/openzeppelin/ReentrancyGuard.sol";
import { ICore721, IWETH9 } from "./interfaces/IMedallionsDependencies.sol";

/// @notice New-sale gifts attached to Medallions #1–#101, claimable by their current owners.
/// @dev Non-upgradeable. No administrator, withdrawal, pause, migration or alternate recipient.
///      Deployed by InventorySale, which becomes its sole immutable funding source.
contract RevenueLedger is ReentrancyGuard {
    address public constant CORE = 0x624C2f90C9861E0a1169fbf617b28E660B7218eB;
    address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    uint256 public constant MAX_CLAIM_TOKENS = 101;
    // Requested CALL gas; the EVM additionally supplies its value-transfer stipend.
    uint256 public constant ETH_GAS_LIMIT = 100_000;
    // Conservative reserve for canonical WETH deposit/transfer and up to 101 payout logs.
    // This is a gas-limit requirement, not a fee: unused gas is not consumed.
    uint256 public constant PAYMENT_GAS_RESERVE = 400_000;

    address public immutable sale;
    uint256 public cumulativeReceipts;
    uint256 public totalPaid;
    mapping(uint256 tokenId => uint256 amount) public paid;

    error MissingDependency();
    error OnlySale();
    error EmptyFunding();
    error InvalidClaimCount();
    error InvalidToken(uint256 tokenId);
    error TokensNotIncreasing();
    error NotTokenOwner(uint256 tokenId);
    error NothingToClaim();
    error InsufficientPaymentGas();
    error WETHTransferFailed();

    event Funded(uint256 amount, uint256 cumulativeReceipts);
    /// @param asset address(0) denotes native ETH; otherwise canonical WETH.
    event TokenClaimed(
        address indexed owner, uint256 indexed tokenId, address indexed asset, uint256 amount
    );
    event ClaimPaid(address indexed owner, address indexed asset, uint256 amount);

    constructor() {
        if (CORE.code.length == 0 || WETH.code.length == 0) revert MissingDependency();
        sale = msg.sender;
    }

    /// @notice Recognize only payments from the permanently linked inventory sale.
    /// @dev No receive/fallback. Forced ETH is not recognized and has no withdrawal path.
    function fund() external payable nonReentrant {
        if (msg.sender != sale) revert OnlySale();
        if (msg.value == 0) revert EmptyFunding();
        cumulativeReceipts += msg.value;
        emit Funded(msg.value, cumulativeReceipts);
    }

    function entitlement(uint256 tokenId) public view returns (uint256) {
        return _entitlement(tokenId, cumulativeReceipts);
    }

    /// @notice Token accounting only; ownership must be queried separately from Core.
    /// @dev A burned token can retain an accounting balance but has no owner able to claim.
    function claimable(uint256 tokenId) external view returns (uint256) {
        return entitlement(tokenId) - paid[tokenId];
    }

    /// @notice Claim one, selected, or all eligible owned tokens, sorted by ID.
    /// @dev The entire batch succeeds or reverts. Zero-balance IDs are allowed in a
    ///      positive-total batch. Approvals and previous ownership confer no claim authority.
    function claim(uint256[] calldata tokenIds) external nonReentrant returns (uint256 amount) {
        uint256 count = tokenIds.length;
        if (count == 0 || count > MAX_CLAIM_TOKENS) revert InvalidClaimCount();
        uint256 receipts = cumulativeReceipts;
        uint256[] memory amounts = new uint256[](count);
        uint256 previous;
        for (uint256 i; i < count; ++i) {
            uint256 id = tokenIds[i];
            if (id == 0 || id > MAX_CLAIM_TOKENS) revert InvalidToken(id);
            if (id <= previous) revert TokensNotIncreasing();
            previous = id;
            if (ICore721(CORE).ownerOf(id) != msg.sender) revert NotTokenOwner(id);
            amounts[i] = _entitlement(id, receipts) - paid[id];
            amount += amounts[i];
        }
        if (amount == 0) revert NothingToClaim();

        // Commit every token before handing control to the recipient or WETH.
        for (uint256 i; i < count; ++i) {
            if (amounts[i] != 0) paid[tokenIds[i]] += amounts[i];
        }
        totalPaid += amount;
        address asset = _pay(msg.sender, amount);
        for (uint256 i; i < count; ++i) {
            if (amounts[i] != 0) emit TokenClaimed(msg.sender, tokenIds[i], asset, amounts[i]);
        }
        emit ClaimPaid(msg.sender, asset, amount);
    }

    function _entitlement(uint256 tokenId, uint256 receipts) private pure returns (uint256) {
        if (tokenId == 0 || tokenId > MAX_CLAIM_TOKENS) revert InvalidToken(tokenId);
        if (tokenId == 1) return receipts / 10;
        if (tokenId <= 21) return receipts / 40;
        return receipts / 200;
    }

    function _pay(address recipient, uint256 amount) private returns (address asset) {
        if (gasleft() < ETH_GAS_LIMIT + PAYMENT_GAS_RESERVE) revert InsufficientPaymentGas();
        bool sent;
        uint256 gasLimit = ETH_GAS_LIMIT;
        // No output buffer: hostile recipients cannot make us copy arbitrary returndata.
        assembly ("memory-safe") {
            sent := call(gasLimit, recipient, amount, 0, 0, 0, 0)
        }
        if (!sent) {
            IWETH9(WETH).deposit{ value: amount }();
            if (!IWETH9(WETH).transfer(recipient, amount)) revert WETHTransferFailed();
            asset = WETH;
        }
    }
}

src/interfaces/IMedallionsDependencies.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.37;

/// @dev Only the existing Core operations used by this system.
interface ICore721 {
    function ownerOf(uint256 tokenId) external view returns (address);
    function safeTransferFrom(address from, address to, uint256 tokenId) external;
}

interface IERC721Receiver {
    function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
        external
        returns (bytes4);
}

/// @dev Ethereum's canonical WETH9, not an arbitrary configurable token.
interface IWETH9 {
    function deposit() external payable;
    function transfer(address to, uint256 amount) external returns (bool);
}

vendor/openzeppelin/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;
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "optimizer": {
    "runs": 200,
    "details": {
      "cse": true,
      "yul": false,
      "inliner": true,
      "peephole": true,
      "deduplicate": true,
      "orderLiterals": true,
      "jumpdestRemover": true,
      "constantOptimizer": true,
      "simpleCounterForLoopUncheckedIncrement": true
    }
  },
  "evmVersion": "cancun",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.