zellic-audit
Initial commit
f998fcd
raw
history blame
80.2 kB
{
"language": "Solidity",
"sources": {
"contracts/libs/SettlementLib.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @author: manifold.xyz\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport \"../IIdentityVerifier.sol\";\nimport \"../ILazyDelivery.sol\";\nimport \"../IPriceEngine.sol\";\n\nimport \"./MarketplaceLib.sol\";\nimport \"./TokenLib.sol\";\nimport \"./BidTreeLib.sol\";\n\n/**\n * @dev Marketplace settlement logic\n */\nlibrary SettlementLib {\n\n using BidTreeLib for BidTreeLib.BidTree;\n\n event Escrow(address indexed receiver, address erc20, uint256 amount);\n\n /**\n * Purchase logic\n */\n function performPurchase(address payable referrer, uint40 listingId, MarketplaceLib.Listing storage listing, uint24 count, mapping(address => uint256) storage feesCollected, bytes memory data) public {\n require(listing.details.startTime <= block.timestamp, \"Listing has not started\");\n require(listing.details.endTime > block.timestamp || listing.details.startTime == 0, \"Listing is expired\");\n\n listing.totalSold += count*listing.details.totalPerSale;\n require(listing.totalSold <= listing.details.totalAvailable, \"Not enough left\");\n\n // If startTime is 0, start on first purchase\n if (listing.details.startTime == 0) {\n listing.details.startTime = uint48(block.timestamp);\n listing.details.endTime += uint48(block.timestamp);\n }\n\n uint256 totalPrice = computeTotalPrice(listing, count, true);\n if (listing.details.erc20 == address(0)) {\n if (listing.details.type_ == MarketplaceLib.ListingType.DYNAMIC_PRICE) {\n // For dynamic price auctions, price may have changed so allow for a mismatch of funds sent\n receiveTokens(listing, msg.sender, totalPrice, true, false);\n } else {\n receiveTokens(listing, msg.sender, totalPrice, false, true);\n }\n } else {\n require(msg.value == 0, \"Invalid amount\");\n }\n \n // Identity verifier check\n if (listing.details.identityVerifier != address(0)) {\n require(IIdentityVerifier(listing.details.identityVerifier).verify(listingId, msg.sender, listing.token.address_, listing.token.id, count, totalPrice, listing.details.erc20, data), \"Permission denied\");\n }\n\n if (listing.token.lazy) {\n // Lazy delivered\n deliverTokenLazy(listingId, listing, msg.sender, count, totalPrice, 0);\n } else {\n // Single item\n deliverToken(listing, msg.sender, count, totalPrice, false);\n }\n\n // Automatically finalize listing if all sold\n if (listing.details.totalAvailable == listing.totalSold) {\n listing.flags |= MarketplaceLib.FLAG_MASK_FINALIZED;\n }\n\n // Pay seller\n if (listing.details.erc20 == address(0)) {\n _paySeller(listing, address(this), totalPrice, referrer, feesCollected);\n } else {\n _paySeller(listing, msg.sender, totalPrice, referrer, feesCollected);\n }\n \n emit MarketplaceLib.PurchaseEvent(listingId, referrer, msg.sender, count, totalPrice);\n }\n\n\n /**\n * Bid logic\n */\n function _preBidCheck(uint40 listingId, MarketplaceLib.Listing storage listing, uint256 bidAmount, bytes memory data) private {\n require(listing.details.startTime <= block.timestamp, \"Listing has not started\");\n require(listing.details.endTime > block.timestamp || listing.details.startTime == 0, \"Listing is expired\");\n\n // If startTime is 0, start on first purchase\n if (listing.details.startTime == 0) {\n listing.details.startTime = uint48(block.timestamp);\n listing.details.endTime += uint48(block.timestamp);\n }\n\n // Identity verifier check\n if (listing.details.identityVerifier != address(0)) {\n require(IIdentityVerifier(listing.details.identityVerifier).verify(listingId, msg.sender, listing.token.address_, listing.token.id, 1, bidAmount, listing.details.erc20, data), \"Permission denied\");\n }\n }\n\n function _postBidExtension(MarketplaceLib.Listing storage listing) private {\n if (listing.details.extensionInterval > 0 && listing.details.endTime <= (block.timestamp + listing.details.extensionInterval)) {\n // Extend auction time if necessary\n listing.details.endTime = uint48(block.timestamp) + listing.details.extensionInterval;\n } \n }\n\n function performBidIndividual(uint40 listingId, MarketplaceLib.Listing storage listing, uint256 bidAmount, address payable referrer, bool increase, mapping(address => mapping(address => uint256)) storage escrow, bytes memory data) public {\n // Basic auction\n _preBidCheck(listingId, listing, bidAmount, data);\n\n address payable bidder = payable(msg.sender);\n MarketplaceLib.Bid storage currentBid = listing.bid;\n if ((listing.flags & MarketplaceLib.FLAG_MASK_HAS_BID) != 0) {\n if (currentBid.bidder == bidder) {\n // Bidder is the current high bidder\n require(bidAmount > 0 && increase, \"Existing bid\");\n receiveTokens(listing, bidder, bidAmount, false, true);\n bidAmount += currentBid.amount;\n } else {\n // Bidder is not the current high bidder\n // Check minimum bid requirements\n require(bidAmount >= computeMinBid(listing.details.initialAmount, currentBid.amount, listing.details.minIncrementBPS), \"Minimum bid not met\");\n receiveTokens(listing, bidder, bidAmount, false, true);\n // Refund bid amount\n refundTokens(listing.details.erc20, currentBid.bidder, currentBid.amount, escrow);\n }\n } else {\n // Check minimum bid requirements\n require(bidAmount >= listing.details.initialAmount, \"Invalid bid amount\");\n receiveTokens(listing, bidder, bidAmount, false, true);\n listing.flags |= MarketplaceLib.FLAG_MASK_HAS_BID;\n }\n // Update referrer if necessary\n if (currentBid.referrer != referrer && listing.referrerBPS > 0) currentBid.referrer = referrer;\n // Update bidder if necessary\n if (currentBid.bidder != bidder) currentBid.bidder = bidder;\n // Update amount\n currentBid.amount = bidAmount;\n emit MarketplaceLib.BidEvent(listingId, referrer, bidder, bidAmount);\n\n _postBidExtension(listing);\n }\n\n function performBidRanked(uint40 listingId, MarketplaceLib.Listing storage listing, BidTreeLib.BidTree storage bidTree, uint256 bidAmount, bool increase, mapping(address => mapping(address => uint256)) storage escrow, bytes memory data) public {\n // Ranked auction\n _preBidCheck(listingId, listing, bidAmount, data);\n\n address payable bidder = payable(msg.sender);\n if ((listing.flags & MarketplaceLib.FLAG_MASK_HAS_BID) != 0 && bidTree.exists(bidder)) {\n // Has already bid, this is a bid update\n BidTreeLib.Bid storage currentBid = bidTree.getBid(bidder);\n require(increase, \"Existing bid\");\n receiveTokens(listing, bidder, bidAmount, false, true);\n uint256 newBidAmount = currentBid.amount + bidAmount;\n bidTree.remove(bidder);\n bidTree.insert(bidder, newBidAmount, uint48(block.timestamp));\n emit MarketplaceLib.BidEvent(listingId, address(0), bidder, newBidAmount);\n } else {\n // Has not yet bid\n require(bidAmount >= listing.details.initialAmount, \"Invalid bid amount\");\n if (bidTree.size == listing.details.totalAvailable) {\n address payable lowestBidder = payable(bidTree.last());\n BidTreeLib.Bid storage lowestBid = bidTree.getBid(lowestBidder);\n // At max bids, so this bid must be greater than the lowest bid\n require(bidAmount >= computeMinBid(listing.details.initialAmount, lowestBid.amount, listing.details.minIncrementBPS), \"Minimum bid not met\");\n // Receive amount\n receiveTokens(listing, bidder, bidAmount, false, true);\n // Return lowest bid amount\n refundTokens(listing.details.erc20, lowestBidder, lowestBid.amount, escrow);\n bidTree.remove(lowestBidder);\n bidTree.insert(bidder, bidAmount, uint48(block.timestamp));\n } else {\n // Receive amount\n receiveTokens(listing, bidder, bidAmount, false, true);\n // Still have bid slots left.\n bidTree.insert(bidder, bidAmount, uint48(block.timestamp));\n listing.flags |= MarketplaceLib.FLAG_MASK_HAS_BID;\n }\n emit MarketplaceLib.BidEvent(listingId, address(0), bidder, bidAmount);\n }\n\n _postBidExtension(listing);\n }\n\n /**\n * Deliver tokens\n */\n function deliverToken(MarketplaceLib.Listing storage listing, address to, uint24 count, uint256 payableAmount, bool reverse) public {\n // Check listing deliver fees if applicable\n if (payableAmount > 0 && (listing.fees.deliverDeciBPS > 0)) {\n uint256 deliveryFee = computeDeliverFee(listing, payableAmount);\n receiveTokens(listing, msg.sender, deliveryFee, false, true);\n // Pay out\n distributeFees(listing, address(this), deliveryFee);\n }\n \n if (listing.token.spec == TokenLib.Spec.ERC721) {\n require(count == 1, \"Invalid amount\");\n TokenLib._erc721Transfer(listing.token.address_, listing.token.id, address(this), to);\n } else if (listing.token.spec == TokenLib.Spec.ERC1155) {\n if (!reverse) {\n TokenLib._erc1155Transfer(listing.token.address_, listing.token.id, listing.details.totalPerSale*count, address(this), to);\n } else if (listing.details.totalAvailable > listing.totalSold) {\n require(count == 1, \"Invalid amount\");\n TokenLib._erc1155Transfer(listing.token.address_, listing.token.id, listing.details.totalAvailable-listing.totalSold, address(this), to);\n }\n } else {\n revert(\"Unsupported token spec\");\n }\n }\n\n /**\n * Deliver lazy tokens\n */\n function deliverTokenLazy(uint40 listingId, MarketplaceLib.Listing storage listing, address to, uint24 count, uint256 payableAmount, uint256 index) public returns(uint256) {\n // Check listing deliver fees if applicable\n if (payableAmount > 0 && (listing.fees.deliverDeciBPS > 0)) {\n // Receive tokens for fees\n uint256 deliveryFee = computeDeliverFee(listing, payableAmount);\n receiveTokens(listing, msg.sender, deliveryFee, false, true);\n // Pay out\n distributeFees(listing, address(this), deliveryFee);\n }\n\n // Call deliver (which can mint)\n return ILazyDelivery(listing.token.address_).deliver(listingId, to, listing.token.id, count, payableAmount, listing.details.erc20, index);\n }\n\n /**\n * Distribute fees\n */\n function distributeFees(MarketplaceLib.Listing storage listing, address source, uint256 amount) public {\n sendTokens(listing.details.erc20, source, listing.fees.deliverAddress, amount);\n }\n\n /**\n * Distribute proceeds\n */\n function distributeProceeds(MarketplaceLib.Listing storage listing, address source, uint256 amount) public {\n if (listing.receivers.length > 0) {\n uint256 totalSent;\n uint256 receiverIndex;\n for (receiverIndex = 0; receiverIndex < listing.receivers.length-1; receiverIndex++) {\n uint256 receiverAmount = amount*listing.receivers[receiverIndex].receiverBPS/10000;\n sendTokens(listing.details.erc20, source, listing.receivers[receiverIndex].receiver, receiverAmount);\n totalSent += receiverAmount;\n }\n require(totalSent < amount, \"Settlement error\");\n sendTokens(listing.details.erc20, source, listing.receivers[receiverIndex].receiver, amount-totalSent);\n } else {\n sendTokens(listing.details.erc20, source, listing.seller, amount);\n }\n }\n\n /**\n * Receive tokens. Returns amount received.\n */\n function receiveTokens(MarketplaceLib.Listing storage listing, address source, uint256 amount, bool refundExcess, bool strict) public {\n if (source == address(this)) return;\n\n if (listing.details.erc20 == address(0)) {\n if (strict) {\n require(msg.value == amount, msg.value < amount ? \"Insufficient funds\" : \"Invalid amount\");\n } else {\n if (msg.value < amount) {\n revert(\"Insufficient funds\");\n } else if (msg.value > amount && refundExcess) {\n // Refund excess\n (bool success, ) = payable(source).call{value:msg.value-amount}(\"\");\n require(success, \"Token send failure\");\n }\n }\n } else {\n require(msg.value == 0, \"Invalid amount\");\n require(IERC20(listing.details.erc20).transferFrom(source, address(this), amount), \"Insufficient funds\");\n }\n }\n\n /**\n * Send proceeds to receiver\n */\n function sendTokens(address erc20, address source, address payable to, uint256 amount) public {\n require(source != to, \"Invalid send request\");\n\n if (erc20 == address(0)) {\n (bool success,) = to.call{value:amount}(\"\");\n require(success, \"Token send failure\");\n } else {\n if (source == address(this)) {\n require(IERC20(erc20).transfer(to, amount), \"Insufficient funds\");\n } else {\n require(IERC20(erc20).transferFrom(source, to, amount), \"Insufficient funds\");\n }\n }\n }\n\n /**\n * Refund tokens\n */\n function refundTokens(address erc20, address payable to, uint256 amount, mapping(address => mapping(address => uint256)) storage escrow) public {\n if (erc20 == address(0)) {\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, ) = to.call{value:amount, gas:20000}(\"\");\n if (!success) {\n escrow[to][erc20] += amount;\n emit Escrow(to, erc20, amount);\n }\n } else {\n try IERC20(erc20).transfer(to, amount) {\n } catch {\n escrow[to][erc20] += amount;\n emit Escrow(to, erc20, amount);\n }\n }\n }\n\n /**\n * Compute deliver fee\n */\n function computeDeliverFee(MarketplaceLib.Listing memory listing, uint256 price) public pure returns(uint256) {\n return price*listing.fees.deliverDeciBPS/100000;\n }\n\n /**\n * Compute current listing price\n */\n function computeListingPrice(MarketplaceLib.Listing storage listing, BidTreeLib.BidTree storage bidTree) public view returns(uint256 currentPrice) {\n currentPrice = listing.details.initialAmount;\n if (listing.details.type_ == MarketplaceLib.ListingType.DYNAMIC_PRICE) {\n currentPrice = IPriceEngine(listing.token.address_).price(listing.token.id, listing.totalSold, 1);\n } else {\n if ((listing.flags & MarketplaceLib.FLAG_MASK_HAS_BID) != 0) {\n if (listing.details.type_ == MarketplaceLib.ListingType.INDIVIDUAL_AUCTION) {\n currentPrice = computeMinBid(listing.details.initialAmount, listing.bid.amount, listing.details.minIncrementBPS);\n } else if (listing.details.type_ == MarketplaceLib.ListingType.RANKED_AUCTION && bidTree.size == listing.details.totalAvailable) {\n currentPrice = computeMinBid(listing.details.initialAmount, bidTree.getBid(bidTree.last()).amount, listing.details.minIncrementBPS);\n }\n }\n }\n return currentPrice;\n }\n\n /**\n * Compute total price for a <COUNT> of items to buy\n */\n function computeTotalPrice(MarketplaceLib.Listing storage listing, uint24 count, bool totalSoldIncreased) public view returns(uint256) {\n if (listing.details.type_ != MarketplaceLib.ListingType.DYNAMIC_PRICE) {\n return listing.details.initialAmount*count;\n } else {\n if (totalSoldIncreased) {\n // If totalSold value was increased prior to call, need to reduce it in order to get the proper pricing\n return IPriceEngine(listing.token.address_).price(listing.token.id, listing.totalSold-count*listing.details.totalPerSale, count);\n } else {\n return IPriceEngine(listing.token.address_).price(listing.token.id, listing.totalSold, count);\n }\n }\n }\n\n /**\n * Get the min bid\n */\n function computeMinBid(uint256 baseAmount, uint256 currentAmount, uint16 minIncrementBPS) pure public returns (uint256) {\n if (currentAmount == 0) {\n return baseAmount;\n }\n if (minIncrementBPS == 0) {\n return currentAmount+1;\n }\n uint256 incrementAmount = currentAmount*minIncrementBPS/10000;\n if (incrementAmount == 0) incrementAmount = 1;\n return currentAmount + incrementAmount;\n }\n\n /**\n * Helper to settle bid, which pays seller\n */\n function settleBid(MarketplaceLib.Bid storage bid, MarketplaceLib.Listing storage listing, mapping(address => uint256) storage feesCollected) public {\n settleBid(bid, listing, 0, feesCollected);\n }\n\n function settleBid(MarketplaceLib.Bid storage bid, MarketplaceLib.Listing storage listing, uint256 refundAmount, mapping(address => uint256) storage feesCollected) public {\n require(!bid.refunded, \"Bid has been refunded\");\n if (!bid.settled) {\n bid.settled = true;\n _paySeller(listing, address(this), bid.amount-refundAmount, bid.referrer, feesCollected);\n }\n }\n function settleBid(BidTreeLib.Bid storage bid, MarketplaceLib.Listing storage listing, mapping(address => uint256) storage feesCollected) public {\n settleBid(bid, listing, 0, feesCollected);\n }\n\n function settleBid(BidTreeLib.Bid storage bid, MarketplaceLib.Listing storage listing, uint256 refundAmount, mapping(address => uint256) storage feesCollected) public {\n require(!bid.refunded, \"Bid has been refunded\");\n if (!bid.settled) {\n bid.settled = true;\n _paySeller(listing, address(this), bid.amount-refundAmount, payable(address(0)), feesCollected);\n }\n }\n\n /**\n * Refund bid\n */\n function refundBid(address payable bidder, BidTreeLib.Bid storage bid, MarketplaceLib.Listing storage listing, uint256 holdbackBPS, mapping(address => mapping(address => uint256)) storage escrow) public {\n require(!bid.settled, \"Cannot refund, already settled\");\n if (!bid.refunded) {\n bid.refunded = true;\n _refundBid(bidder, bid.amount, listing, holdbackBPS, escrow);\n }\n }\n function refundBid(MarketplaceLib.Bid storage bid, MarketplaceLib.Listing storage listing, uint256 holdbackBPS, mapping(address => mapping(address => uint256)) storage escrow) public {\n require(!bid.settled, \"Cannot refund, already settled\");\n if (!bid.refunded) {\n bid.refunded = true;\n _refundBid(bid.bidder, bid.amount, listing, holdbackBPS, escrow);\n }\n }\n function _refundBid(address payable bidder, uint256 amount, MarketplaceLib.Listing storage listing, uint256 holdbackBPS, mapping(address => mapping(address => uint256)) storage escrow) private {\n uint256 refundAmount = amount;\n\n // Refund amount (less holdback)\n if (holdbackBPS > 0) {\n uint256 holdbackAmount = refundAmount*holdbackBPS/10000;\n refundAmount -= holdbackAmount;\n // Distribute holdback\n distributeProceeds(listing, address(this), holdbackAmount);\n }\n // Refund bidder\n refundTokens(listing.details.erc20, bidder, refundAmount, escrow);\n }\n\n /**\n * Helper to pay seller given amount\n */\n function _paySeller(MarketplaceLib.Listing storage listing, address source, uint256 amount, address payable referrer, mapping(address => uint256) storage feesCollected) private {\n uint256 sellerAmount = amount;\n if (listing.marketplaceBPS > 0) {\n uint256 marketplaceAmount = amount*listing.marketplaceBPS/10000;\n sellerAmount -= marketplaceAmount;\n receiveTokens(listing, source, marketplaceAmount, false, false);\n feesCollected[listing.details.erc20] += marketplaceAmount;\n }\n if (listing.referrerBPS > 0 && referrer != address(0)) {\n uint256 referrerAmount = amount*listing.referrerBPS/10000;\n sellerAmount -= referrerAmount;\n sendTokens(listing.details.erc20, source, referrer, referrerAmount);\n }\n\n distributeProceeds(listing, source, sellerAmount);\n }\n\n}\n"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n"
},
"contracts/IIdentityVerifier.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @author: manifold.xyz\n\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\ninterface IIdentityVerifier is IERC165 {\n\n /**\n * @dev Verify that the buyer can purchase/bid\n *\n * @param listingId The listingId associated with this verification\n * @param identity The identity to verify\n * @param tokenAddress The tokenAddress associated with this verification\n * @param tokenId The tokenId associated with this verification\n * @param requestCount The number of items being requested to purchase/bid\n * @param requestAmount The amount being requested\n * @param requestERC20 The erc20 token address of the amount (0x0 if ETH)\n * @param data Additional data needed to verify\n *\n */\n function verify(uint40 listingId, address identity, address tokenAddress, uint256 tokenId, uint24 requestCount, uint256 requestAmount, address requestERC20, bytes calldata data) external returns (bool);\n\n}"
},
"contracts/ILazyDelivery.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @author: manifold.xyz\n\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\ninterface ILazyDelivery is IERC165 {\n\n /**\n * @dev Deliver an asset and deliver to the specified party\n * When implementing this interface, please ensure you restrict access.\n * If using LazyDeliver.sol, you can use authorizedDelivererRequired modifier to restrict access. \n * Delivery can be for an existing asset or newly minted assets.\n * \n * @param listingId The listingId associated with this delivery. Useful for permissioning.\n * @param to The address to deliver the asset to\n * @param assetId The assetId to deliver\n * @param payableCount The number of assets to deliver\n * @param payableAmount The amount seller will receive upon delivery of asset\n * @param payableERC20 The erc20 token address of the amount (0x0 if ETH)\n * @param index (Optional): Index value for certain sales methods, such as ranked auctions\n *\n * @return any Only used for Ranked Auctions and represents the refund amount you want to give.\n * Value is unused for all other listing types\n *\n * Suggestion: If determining a refund amount based on total sales data, do not enable this function\n * until the sales data is finalized and recorded in contract\n *\n * Exploit Prevention for dynamic/random assignment\n * 1. Ensure attributes are not assigned until AFTER underlying mint if using _safeMint.\n * This is to ensure a receiver cannot check attribute values on receive and revert transaction.\n * However, even if this is the case, the recipient can wrap its mint in a contract that checks \n * post mint completion and reverts if unsuccessful.\n * 2. Ensure that \"to\" is not a contract address. This prevents a contract from doing the lazy \n * mint, which could exploit random assignment by reverting if they do not receive the desired\n * item post mint.\n */\n function deliver(uint40 listingId, address to, uint256 assetId, uint24 payableCount, uint256 payableAmount, address payableERC20, uint256 index) external returns(uint256);\n\n}"
},
"contracts/IPriceEngine.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @author: manifold.xyz\n\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\ninterface IPriceEngine is IERC165 {\n\n /**\n * @dev Determine price of an asset given the number\n * already minted.\n */\n function price(uint256 assetId, uint256 alreadyMinted, uint24 count) view external returns (uint256);\n\n}"
},
"contracts/libs/MarketplaceLib.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @author: manifold.xyz\n\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport \"@openzeppelin/contracts/utils/introspection/ERC165Checker.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\n\nimport \"@manifoldxyz/libraries-solidity/contracts/access/IAdminControl.sol\";\n\nimport \"../IIdentityVerifier.sol\";\nimport \"../ILazyDelivery.sol\";\nimport \"../IPriceEngine.sol\";\n\nimport \"./TokenLib.sol\";\n\n/**\n * Interface for Ownable contracts\n */\ninterface IOwnable {\n function owner() external view returns(address);\n}\n\n/**\n * @dev Marketplace libraries\n */\nlibrary MarketplaceLib {\n using AddressUpgradeable for address;\n\n // Events\n event CreateListing(uint40 indexed listingId, uint16 marketplaceBPS, uint16 referrerBPS, uint8 listingType, uint24 totalAvailable, uint24 totalPerSale, uint48 startTime, uint48 endTime, uint256 initialAmount, uint16 extensionInterval, uint16 minIncrementBPS, address erc20, address identityVerifier);\n event CreateListingTokenDetails(uint40 indexed listingId, uint256 id, address address_, uint8 spec, bool lazy);\n\n event PurchaseEvent(uint40 indexed listingId, address referrer, address buyer, uint24 count, uint256 amount);\n event BidEvent(uint40 indexed listingId, address referrer, address bidder, uint256 amount);\n event ModifyListing(uint40 indexed listingId, uint256 initialAmount, uint48 startTime, uint48 endTime);\n event CompleteListing(uint40 indexed listingId, uint16 deliverDeciBPS, address deliverAddress);\n event FinalizeListing(uint40 indexed listingId);\n event CancelListing(uint40 indexed listingId, address requestor, uint16 holdbackBPS);\n\n // Listing types\n enum ListingType {\n INVALID,\n INDIVIDUAL_AUCTION,\n FIXED_PRICE,\n DYNAMIC_PRICE,\n RANKED_AUCTION\n }\n\n /**\n * @dev Listing structure\n *\n * @param seller - the selling party\n * @param flags - bit flag (hasBid, finalized, tokenCreator). See FLAG_MASK_*\n * @param totalSold - total number of items sold. This IS NOT the number of sales. Number of sales is totalSold/details.totalPerSale.\n * @param marketplaceBPS - Marketplace fee BPS\n * @param referrerBPS - Fee BPS for referrer if there is one\n * @param details - ListingDetails. Contains listing configuration\n * @param token - TokenDetails. Contains the details of token being sold\n * @param receivers - Array of ListingReceiver structs. If provided, will distribute sales proceeds to receivers accordingly.\n * @param bid - Active bid. Only valid for INDIVIDUAL_AUCTION (1 bid)\n * @param fees - DeliveryFees. Contains the delivery fee configuration for the listing\n */\n struct Listing {\n address payable seller;\n uint8 flags;\n uint24 totalSold;\n uint16 marketplaceBPS;\n uint16 referrerBPS;\n ListingDetails details;\n TokenDetails token;\n ListingReceiver[] receivers;\n Bid bid;\n DeliveryFees fees;\n }\n\n uint8 internal constant FLAG_MASK_HAS_BID = 0x1;\n uint8 internal constant FLAG_MASK_FINALIZED = 0x2;\n uint8 internal constant FLAG_MASK_COMPLETABLE = 0x4;\n\n /**\n * @dev Listing details structure\n *\n * @param initialAmount - The initial amount of the listing. For auctions, it represents the reserve price. For DYNAMIC_PRICE listings, it must be 0.\n * @param type_ - Listing type\n * @param totalAvailable - Total number of tokens available. Must be divisible by totalPerSale. For INDIVIDUAL_AUCTION, totalAvailable must equal totalPerSale\n * @param totalPerSale - Number of tokens the buyer will get per purchase. Must be 1 if it is a lazy token\n * @param extensionInterval - Only valid for *_AUCTION types. Indicates how long an auction will extend if a bid is made within the last <extensionInterval> seconds of the auction.\n * @param minIncrementBPS - Only valid for *_AUCTION types. Indicates the minimum bid increase required\n * @param erc20 - If not 0x0, it indicates the erc20 token accepted for this sale\n * @param identityVerifier - If not 0x0, it indicates the buyers should be verified before any bid or purchase\n * @param startTime - The start time of the sale. If set to 0, startTime will be set to the first bid/purchase.\n * @param endTime - The end time of the sale. If startTime is 0, represents the duration of the listing upon first bid/purchase.\n */\n struct ListingDetails {\n uint256 initialAmount;\n ListingType type_;\n uint24 totalAvailable;\n uint24 totalPerSale;\n uint16 extensionInterval;\n uint16 minIncrementBPS;\n address erc20;\n address identityVerifier;\n uint48 startTime;\n uint48 endTime;\n }\n\n /**\n * @dev Token detail structure\n *\n * @param address_ - The contract address of the token\n * @param id - The token id (or for a lazy asset, the asset id)\n * @param spec - The spec of the token. If it's a lazy token, it must be blank.\n * @param lazy - True if token is to be lazy minted, false otherwise. If lazy, the contract address must support ILazyDelivery\n */\n struct TokenDetails {\n uint256 id;\n address address_;\n TokenLib.Spec spec;\n bool lazy;\n }\n\n /**\n * @dev Fee configuration for listing\n *\n * @param deliverDeciBPS - Additional fee needed to deliver the token (BPS)\n * @param deliverAddress - Additional fee delivery address\n */\n struct DeliveryFees {\n uint16 deliverDeciBPS;\n address payable deliverAddress;\n }\n\n /**\n * Listing receiver. The array of listing receivers must add up to 10000 BPS if provided.\n */\n struct ListingReceiver {\n address payable receiver;\n uint16 receiverBPS;\n }\n\n /**\n * Represents an active bid\n *\n * @param referrer - The referrer\n * @param bidder - The bidder\n * @param delivered - Whether or not the token has been delivered.\n * @param settled - Whether or not the seller has been paid\n * @param refunded - Whether or not the bid has been refunded\n */\n struct Bid {\n uint256 amount;\n address payable bidder;\n bool delivered;\n bool settled;\n bool refunded;\n uint48 timestamp;\n address payable referrer;\n }\n\n /**\n * Construct a marketplace listing\n */\n function constructListing(uint40 listingId, Listing storage listing, ListingDetails calldata listingDetails, TokenDetails calldata tokenDetails, ListingReceiver[] calldata listingReceivers) public {\n require(tokenDetails.address_.isContract(), \"Token address must be a contract\");\n require(listingDetails.endTime > listingDetails.startTime, \"End time must be after start time\");\n require(listingDetails.startTime == 0 || listingDetails.startTime > block.timestamp, \"Start and end time cannot occur in the past\");\n require(listingDetails.totalAvailable % listingDetails.totalPerSale == 0, \"Invalid token config\");\n \n if (listingDetails.identityVerifier != address(0)) {\n require(ERC165Checker.supportsInterface(listingDetails.identityVerifier, type(IIdentityVerifier).interfaceId), \"Misconfigured verifier\");\n }\n \n if (listingReceivers.length > 0) {\n uint256 totalBPS;\n for (uint i = 0; i < listingReceivers.length; i++) {\n listing.receivers.push(listingReceivers[i]);\n totalBPS += listingReceivers[i].receiverBPS;\n }\n require(totalBPS == 10000, \"Invalid receiver config\");\n }\n\n if (listingDetails.type_ == ListingType.INDIVIDUAL_AUCTION) {\n require(listingDetails.totalAvailable == listingDetails.totalPerSale, \"Invalid token config\");\n } else if (listingDetails.type_ == ListingType.DYNAMIC_PRICE) {\n require(tokenDetails.lazy && listingDetails.initialAmount == 0, \"Invalid listing config\");\n require(ERC165Checker.supportsInterface(tokenDetails.address_, type(IPriceEngine).interfaceId), \"Lazy delivered dynamic price items requires token address to implement IPriceEngine\");\n } else if (listingDetails.type_ == ListingType.RANKED_AUCTION) {\n require(tokenDetails.lazy && listingDetails.totalAvailable <= 256, \"Invalid listing config\");\n }\n\n // Purchase types \n if (!isAuction(listingDetails.type_)) {\n require(listingDetails.extensionInterval == 0 && listingDetails.minIncrementBPS == 0, \"Invalid listing config\");\n } else if (listingDetails.type_ == ListingType.INDIVIDUAL_AUCTION) {\n // Pre-initialize values to reduce cost of first bid\n listing.bid.amount = 1;\n listing.bid.timestamp = 1;\n }\n\n if (tokenDetails.lazy) {\n require(listingDetails.totalPerSale == 1, \"Invalid token config\");\n require(ERC165Checker.supportsInterface(tokenDetails.address_, type(ILazyDelivery).interfaceId), \"Lazy delivery requires token address to implement ILazyDelivery\");\n } else {\n require(listingDetails.type_ == ListingType.INDIVIDUAL_AUCTION || listingDetails.type_ == ListingType.FIXED_PRICE, \"Invalid type\");\n _intakeToken(tokenDetails.spec, tokenDetails.address_, tokenDetails.id, listingDetails.totalAvailable, listing.seller);\n }\n\n // Set Listing Data\n listing.details = listingDetails;\n listing.token = tokenDetails;\n \n _emitCreateListing(listingId, listing);\n\n }\n\n function _emitCreateListing(uint40 listingId, Listing storage listing) private {\n emit CreateListing(listingId, listing.marketplaceBPS, listing.referrerBPS, uint8(listing.details.type_), listing.details.totalAvailable, listing.details.totalPerSale, listing.details.startTime, listing.details.endTime, listing.details.initialAmount, listing.details.extensionInterval, listing.details.minIncrementBPS, listing.details.erc20, listing.details.identityVerifier);\n emit CreateListingTokenDetails(listingId, listing.token.id, listing.token.address_, uint8(listing.token.spec), listing.token.lazy);\n }\n\n function _intakeToken(TokenLib.Spec tokenSpec, address tokenAddress, uint256 tokenId, uint256 tokensToTransfer, address from) private {\n if (tokenSpec == TokenLib.Spec.ERC721) {\n require(tokensToTransfer == 1, \"ERC721 invalid number of tokens to transfer\");\n TokenLib._erc721Transfer(tokenAddress, tokenId, from, address(this));\n } else if (tokenSpec == TokenLib.Spec.ERC1155) {\n TokenLib._erc1155Transfer(tokenAddress, tokenId, tokensToTransfer, from, address(this));\n } else {\n revert(\"Unsupported token spec\");\n }\n }\n\n function isAuction(ListingType type_) public pure returns (bool) {\n return (type_ == MarketplaceLib.ListingType.INDIVIDUAL_AUCTION || type_ == MarketplaceLib.ListingType.RANKED_AUCTION);\n }\n\n function modifyListing(uint40 listingId, Listing storage listing, uint256 initialAmount, uint48 startTime, uint48 endTime) public {\n require(endTime > startTime, \"End time must be after start time\");\n require(startTime == 0 || startTime > block.timestamp, \"Start and end time cannot occur in the past\");\n require(listing.details.startTime == 0 || (block.timestamp < listing.details.startTime && (listing.flags & MarketplaceLib.FLAG_MASK_FINALIZED) == 0)\n || (!isAuction(listing.details.type_) && listing.totalSold == 0)|| (isAuction(listing.details.type_) && listing.bid.amount == 1), \"Cannot modify listing that has already started or completed\");\n require(listing.details.type_ != MarketplaceLib.ListingType.DYNAMIC_PRICE || initialAmount == 0, \"Invalid listing config\");\n listing.details.initialAmount = initialAmount;\n listing.details.startTime = startTime;\n listing.details.endTime = endTime;\n\n emit ModifyListing(listingId, initialAmount, startTime, endTime);\n }\n\n function completeListing(uint40 listingId, Listing storage listing, DeliveryFees calldata fees) public {\n require((listing.flags & MarketplaceLib.FLAG_MASK_FINALIZED) == 0, \"Listing not found\");\n require(listing.details.startTime != 0 && listing.details.endTime < block.timestamp, \"Listing still active\");\n listing.fees = fees;\n listing.flags |= MarketplaceLib.FLAG_MASK_COMPLETABLE;\n\n emit CompleteListing(listingId, fees.deliverDeciBPS, fees.deliverAddress);\n }\n\n}"
},
"contracts/libs/TokenLib.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @author: manifold.xyz\n\nimport \"@openzeppelin/contracts/token/ERC721/IERC721.sol\";\nimport \"@openzeppelin/contracts/token/ERC1155/IERC1155.sol\";\n\n/**\n * @dev Token specs and functions\n */\nlibrary TokenLib {\n // Spec types\n enum Spec {\n NONE,\n ERC721,\n ERC1155\n }\n\n function _getSpecString(Spec spec) internal pure returns (string memory) {\n if (spec == Spec.ERC721) {\n return \"erc721\";\n } else if (spec == Spec.ERC1155) {\n return \"erc1155\";\n } else {\n return \"\";\n }\n }\n\n function _erc721Transfer(address tokenAddress, uint256 tokenId, address from, address to) internal {\n // Transfer token\n IERC721(tokenAddress).transferFrom(from, to, tokenId);\n }\n\n function _erc1155Transfer(address tokenAddress, uint256 tokenId, uint256 value, address from, address to) internal {\n // Transfer token\n IERC1155(tokenAddress).safeTransferFrom(from, to, tokenId, value, \"\");\n }\n\n}"
},
"contracts/libs/BidTreeLib.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * Bid tree library (sorts from highest amount to lowest amount, then by oldest to newest if they're the same value)\n */\nlibrary BidTreeLib {\n /**\n * Represents an active bid\n *\n * @param delivered - Whether or not the token has been delivered.\n * @param settled - Whether or not the seller has been paid\n * @param refunded - Whether or not the bid has been refunded\n */\n struct Bid {\n uint256 amount;\n bool delivered;\n bool settled;\n bool refunded;\n uint48 timestamp;\n }\n\n struct Node {\n Bid data;\n address parent;\n address left;\n address right;\n bool red;\n }\n\n struct BidTree {\n address root;\n uint16 size;\n mapping(address => Node) nodes;\n }\n\n address private constant EMPTY = address(0);\n\n function first(BidTree storage self) internal view returns (address _key) {\n _key = self.root;\n if (_key != EMPTY) {\n while (self.nodes[_key].left != EMPTY) {\n _key = self.nodes[_key].left;\n }\n }\n }\n function last(BidTree storage self) internal view returns (address _key) {\n _key = self.root;\n if (_key != EMPTY) {\n while (self.nodes[_key].right != EMPTY) {\n _key = self.nodes[_key].right;\n }\n }\n }\n function next(BidTree storage self, address target) internal view returns (address cursor) {\n require(target != EMPTY);\n if (self.nodes[target].right != EMPTY) {\n cursor = bidTreeMinimum(self, self.nodes[target].right);\n } else {\n cursor = self.nodes[target].parent;\n while (cursor != EMPTY && target == self.nodes[cursor].right) {\n target = cursor;\n cursor = self.nodes[cursor].parent;\n }\n }\n }\n function prev(BidTree storage self, address target) internal view returns (address cursor) {\n require(target != EMPTY);\n if (self.nodes[target].left != EMPTY) {\n cursor = bidTreeMaximum(self, self.nodes[target].left);\n } else {\n cursor = self.nodes[target].parent;\n while (cursor != EMPTY && target == self.nodes[cursor].left) {\n target = cursor;\n cursor = self.nodes[cursor].parent;\n }\n }\n }\n function exists(BidTree storage self, address key) internal view returns (bool) {\n return (key != EMPTY) && ((key == self.root) || (self.nodes[key].parent != EMPTY));\n }\n function isEmpty(address key) internal pure returns (bool) {\n return key == EMPTY;\n }\n function getEmpty() internal pure returns (address) {\n return EMPTY;\n }\n function getBid(BidTree storage self, address key) internal view returns (Bid storage) {\n require(exists(self, key));\n return(self.nodes[key].data);\n }\n\n function insert(BidTree storage self, address key, uint256 amount, uint48 timestamp) internal {\n require(key != EMPTY);\n require(!exists(self, key));\n address cursor = EMPTY;\n address probe = self.root;\n Bid storage cursorData;\n while (probe != EMPTY) {\n cursor = probe;\n cursorData = self.nodes[cursor].data;\n if (amount > cursorData.amount || (amount == cursorData.amount && timestamp < cursorData.timestamp)) {\n probe = self.nodes[probe].left;\n } else {\n probe = self.nodes[probe].right;\n }\n }\n self.nodes[key] = Node({data: Bid({amount: amount, delivered: false, settled: false, refunded: false, timestamp: timestamp}), parent: cursor, left: EMPTY, right: EMPTY, red: true});\n if (cursor == EMPTY) {\n self.root = key;\n } else {\n cursorData = self.nodes[cursor].data;\n if (amount > cursorData.amount || (amount == cursorData.amount && timestamp < cursorData.timestamp)) {\n self.nodes[cursor].left = key;\n } else {\n self.nodes[cursor].right = key;\n }\n }\n insertFixup(self, key);\n self.size += 1;\n }\n function remove(BidTree storage self, address key) internal {\n require(key != EMPTY);\n require(exists(self, key));\n address probe;\n address cursor;\n if (self.nodes[key].left == EMPTY || self.nodes[key].right == EMPTY) {\n cursor = key;\n } else {\n cursor = self.nodes[key].right;\n while (self.nodes[cursor].left != EMPTY) {\n cursor = self.nodes[cursor].left;\n }\n }\n if (self.nodes[cursor].left != EMPTY) {\n probe = self.nodes[cursor].left;\n } else {\n probe = self.nodes[cursor].right;\n }\n address yParent = self.nodes[cursor].parent;\n self.nodes[probe].parent = yParent;\n if (yParent != EMPTY) {\n if (cursor == self.nodes[yParent].left) {\n self.nodes[yParent].left = probe;\n } else {\n self.nodes[yParent].right = probe;\n }\n } else {\n self.root = probe;\n }\n bool doFixup = !self.nodes[cursor].red;\n if (cursor != key) {\n replaceParent(self, cursor, key);\n self.nodes[cursor].left = self.nodes[key].left;\n self.nodes[self.nodes[cursor].left].parent = cursor;\n self.nodes[cursor].right = self.nodes[key].right;\n self.nodes[self.nodes[cursor].right].parent = cursor;\n self.nodes[cursor].red = self.nodes[key].red;\n (cursor, key) = (key, cursor);\n }\n if (doFixup) {\n removeFixup(self, probe);\n }\n delete self.nodes[cursor];\n self.size -= 1;\n }\n\n function bidTreeMinimum(BidTree storage self, address key) private view returns (address) {\n while (self.nodes[key].left != EMPTY) {\n key = self.nodes[key].left;\n }\n return key;\n }\n function bidTreeMaximum(BidTree storage self, address key) private view returns (address) {\n while (self.nodes[key].right != EMPTY) {\n key = self.nodes[key].right;\n }\n return key;\n }\n\n function rotateLeft(BidTree storage self, address key) private {\n address cursor = self.nodes[key].right;\n address keyParent = self.nodes[key].parent;\n address cursorLeft = self.nodes[cursor].left;\n self.nodes[key].right = cursorLeft;\n if (cursorLeft != EMPTY) {\n self.nodes[cursorLeft].parent = key;\n }\n self.nodes[cursor].parent = keyParent;\n if (keyParent == EMPTY) {\n self.root = cursor;\n } else if (key == self.nodes[keyParent].left) {\n self.nodes[keyParent].left = cursor;\n } else {\n self.nodes[keyParent].right = cursor;\n }\n self.nodes[cursor].left = key;\n self.nodes[key].parent = cursor;\n }\n function rotateRight(BidTree storage self, address key) private {\n address cursor = self.nodes[key].left;\n address keyParent = self.nodes[key].parent;\n address cursorRight = self.nodes[cursor].right;\n self.nodes[key].left = cursorRight;\n if (cursorRight != EMPTY) {\n self.nodes[cursorRight].parent = key;\n }\n self.nodes[cursor].parent = keyParent;\n if (keyParent == EMPTY) {\n self.root = cursor;\n } else if (key == self.nodes[keyParent].right) {\n self.nodes[keyParent].right = cursor;\n } else {\n self.nodes[keyParent].left = cursor;\n }\n self.nodes[cursor].right = key;\n self.nodes[key].parent = cursor;\n }\n\n function insertFixup(BidTree storage self, address key) private {\n address cursor;\n while (key != self.root && self.nodes[self.nodes[key].parent].red) {\n address keyParent = self.nodes[key].parent;\n if (keyParent == self.nodes[self.nodes[keyParent].parent].left) {\n cursor = self.nodes[self.nodes[keyParent].parent].right;\n if (self.nodes[cursor].red) {\n self.nodes[keyParent].red = false;\n self.nodes[cursor].red = false;\n self.nodes[self.nodes[keyParent].parent].red = true;\n key = self.nodes[keyParent].parent;\n } else {\n if (key == self.nodes[keyParent].right) {\n key = keyParent;\n rotateLeft(self, key);\n }\n keyParent = self.nodes[key].parent;\n self.nodes[keyParent].red = false;\n self.nodes[self.nodes[keyParent].parent].red = true;\n rotateRight(self, self.nodes[keyParent].parent);\n }\n } else {\n cursor = self.nodes[self.nodes[keyParent].parent].left;\n if (self.nodes[cursor].red) {\n self.nodes[keyParent].red = false;\n self.nodes[cursor].red = false;\n self.nodes[self.nodes[keyParent].parent].red = true;\n key = self.nodes[keyParent].parent;\n } else {\n if (key == self.nodes[keyParent].left) {\n key = keyParent;\n rotateRight(self, key);\n }\n keyParent = self.nodes[key].parent;\n self.nodes[keyParent].red = false;\n self.nodes[self.nodes[keyParent].parent].red = true;\n rotateLeft(self, self.nodes[keyParent].parent);\n }\n }\n }\n self.nodes[self.root].red = false;\n }\n\n function replaceParent(BidTree storage self, address a, address b) private {\n address bParent = self.nodes[b].parent;\n self.nodes[a].parent = bParent;\n if (bParent == EMPTY) {\n self.root = a;\n } else {\n if (b == self.nodes[bParent].left) {\n self.nodes[bParent].left = a;\n } else {\n self.nodes[bParent].right = a;\n }\n }\n }\n function removeFixup(BidTree storage self, address key) private {\n address cursor;\n while (key != self.root && !self.nodes[key].red) {\n address keyParent = self.nodes[key].parent;\n if (key == self.nodes[keyParent].left) {\n cursor = self.nodes[keyParent].right;\n if (self.nodes[cursor].red) {\n self.nodes[cursor].red = false;\n self.nodes[keyParent].red = true;\n rotateLeft(self, keyParent);\n cursor = self.nodes[keyParent].right;\n }\n if (!self.nodes[self.nodes[cursor].left].red && !self.nodes[self.nodes[cursor].right].red) {\n self.nodes[cursor].red = true;\n key = keyParent;\n } else {\n if (!self.nodes[self.nodes[cursor].right].red) {\n self.nodes[self.nodes[cursor].left].red = false;\n self.nodes[cursor].red = true;\n rotateRight(self, cursor);\n cursor = self.nodes[keyParent].right;\n }\n self.nodes[cursor].red = self.nodes[keyParent].red;\n self.nodes[keyParent].red = false;\n self.nodes[self.nodes[cursor].right].red = false;\n rotateLeft(self, keyParent);\n key = self.root;\n }\n } else {\n cursor = self.nodes[keyParent].left;\n if (self.nodes[cursor].red) {\n self.nodes[cursor].red = false;\n self.nodes[keyParent].red = true;\n rotateRight(self, keyParent);\n cursor = self.nodes[keyParent].left;\n }\n if (!self.nodes[self.nodes[cursor].right].red && !self.nodes[self.nodes[cursor].left].red) {\n self.nodes[cursor].red = true;\n key = keyParent;\n } else {\n if (!self.nodes[self.nodes[cursor].left].red) {\n self.nodes[self.nodes[cursor].right].red = false;\n self.nodes[cursor].red = true;\n rotateLeft(self, cursor);\n cursor = self.nodes[keyParent].left;\n }\n self.nodes[cursor].red = self.nodes[keyParent].red;\n self.nodes[keyParent].red = false;\n self.nodes[self.nodes[cursor].left].red = false;\n rotateRight(self, keyParent);\n key = self.root;\n }\n }\n }\n self.nodes[key].red = false;\n }\n}\n// ----------------------------------------------------------------------------\n// End - BokkyPooBah's Red-Black BidTree Library\n// ----------------------------------------------------------------------------"
},
"@openzeppelin/contracts/utils/introspection/IERC165.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
},
"@openzeppelin/contracts/token/ERC721/IERC721.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n}\n"
},
"@openzeppelin/contracts/utils/introspection/ERC165Checker.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Library used to query support of an interface declared via {IERC165}.\n *\n * Note that these functions return the actual result of the query: they do not\n * `revert` if an interface is not supported. It is up to the caller to decide\n * what to do in these cases.\n */\nlibrary ERC165Checker {\n // As per the EIP-165 spec, no interface should ever match 0xffffffff\n bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;\n\n /**\n * @dev Returns true if `account` supports the {IERC165} interface,\n */\n function supportsERC165(address account) internal view returns (bool) {\n // Any contract that implements ERC165 must explicitly indicate support of\n // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid\n return\n _supportsERC165Interface(account, type(IERC165).interfaceId) &&\n !_supportsERC165Interface(account, _INTERFACE_ID_INVALID);\n }\n\n /**\n * @dev Returns true if `account` supports the interface defined by\n * `interfaceId`. Support for {IERC165} itself is queried automatically.\n *\n * See {IERC165-supportsInterface}.\n */\n function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {\n // query support of both ERC165 as per the spec and support of _interfaceId\n return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);\n }\n\n /**\n * @dev Returns a boolean array where each value corresponds to the\n * interfaces passed in and whether they're supported or not. This allows\n * you to batch check interfaces for a contract where your expectation\n * is that some interfaces may not be supported.\n *\n * See {IERC165-supportsInterface}.\n *\n * _Available since v3.4._\n */\n function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)\n internal\n view\n returns (bool[] memory)\n {\n // an array of booleans corresponding to interfaceIds and whether they're supported or not\n bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);\n\n // query support of ERC165 itself\n if (supportsERC165(account)) {\n // query support of each interface in interfaceIds\n for (uint256 i = 0; i < interfaceIds.length; i++) {\n interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);\n }\n }\n\n return interfaceIdsSupported;\n }\n\n /**\n * @dev Returns true if `account` supports all the interfaces defined in\n * `interfaceIds`. Support for {IERC165} itself is queried automatically.\n *\n * Batch-querying can lead to gas savings by skipping repeated checks for\n * {IERC165} support.\n *\n * See {IERC165-supportsInterface}.\n */\n function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {\n // query support of ERC165 itself\n if (!supportsERC165(account)) {\n return false;\n }\n\n // query support of each interface in _interfaceIds\n for (uint256 i = 0; i < interfaceIds.length; i++) {\n if (!_supportsERC165Interface(account, interfaceIds[i])) {\n return false;\n }\n }\n\n // all interfaces supported\n return true;\n }\n\n /**\n * @notice Query if a contract implements an interface, does not check ERC165 support\n * @param account The address of the contract to query for support of an interface\n * @param interfaceId The interface identifier, as specified in ERC-165\n * @return true if the contract at account indicates support of the interface with\n * identifier interfaceId, false otherwise\n * @dev Assumes that account contains a contract that supports ERC165, otherwise\n * the behavior of this method is undefined. This precondition can be checked\n * with {supportsERC165}.\n * Interface identification is specified in ERC-165.\n */\n function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {\n bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);\n (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams);\n if (result.length < 32) return false;\n return success && abi.decode(result, (bool));\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n assembly {\n size := extcodesize(account)\n }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
},
"@manifoldxyz/libraries-solidity/contracts/access/IAdminControl.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\n/// @author: manifold.xyz\n\nimport \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\n/**\n * @dev Interface for admin control\n */\ninterface IAdminControl is IERC165 {\n\n event AdminApproved(address indexed account, address indexed sender);\n event AdminRevoked(address indexed account, address indexed sender);\n\n /**\n * @dev gets address of all admins\n */\n function getAdmins() external view returns (address[] memory);\n\n /**\n * @dev add an admin. Can only be called by contract owner.\n */\n function approveAdmin(address admin) external;\n\n /**\n * @dev remove an admin. Can only be called by contract owner.\n */\n function revokeAdmin(address admin) external;\n\n /**\n * @dev checks whether or not given address is an admin\n * Returns True if they are\n */\n function isAdmin(address admin) external view returns (bool);\n\n}"
},
"@openzeppelin/contracts/token/ERC1155/IERC1155.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC1155 compliant contract, as defined in the\n * https://eips.ethereum.org/EIPS/eip-1155[EIP].\n *\n * _Available since v3.1._\n */\ninterface IERC1155 is IERC165 {\n /**\n * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.\n */\n event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);\n\n /**\n * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all\n * transfers.\n */\n event TransferBatch(\n address indexed operator,\n address indexed from,\n address indexed to,\n uint256[] ids,\n uint256[] values\n );\n\n /**\n * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to\n * `approved`.\n */\n event ApprovalForAll(address indexed account, address indexed operator, bool approved);\n\n /**\n * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.\n *\n * If an {URI} event was emitted for `id`, the standard\n * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value\n * returned by {IERC1155MetadataURI-uri}.\n */\n event URI(string value, uint256 indexed id);\n\n /**\n * @dev Returns the amount of tokens of token type `id` owned by `account`.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function balanceOf(address account, uint256 id) external view returns (uint256);\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.\n *\n * Requirements:\n *\n * - `accounts` and `ids` must have the same length.\n */\n function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)\n external\n view\n returns (uint256[] memory);\n\n /**\n * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,\n *\n * Emits an {ApprovalForAll} event.\n *\n * Requirements:\n *\n * - `operator` cannot be the caller.\n */\n function setApprovalForAll(address operator, bool approved) external;\n\n /**\n * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.\n *\n * See {setApprovalForAll}.\n */\n function isApprovedForAll(address account, address operator) external view returns (bool);\n\n /**\n * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.\n *\n * Emits a {TransferSingle} event.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.\n * - `from` must have a balance of tokens of type `id` of at least `amount`.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the\n * acceptance magic value.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 id,\n uint256 amount,\n bytes calldata data\n ) external;\n\n /**\n * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.\n *\n * Emits a {TransferBatch} event.\n *\n * Requirements:\n *\n * - `ids` and `amounts` must have the same length.\n * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the\n * acceptance magic value.\n */\n function safeBatchTransferFrom(\n address from,\n address to,\n uint256[] calldata ids,\n uint256[] calldata amounts,\n bytes calldata data\n ) external;\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 500
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}