Verified contractExactMIT
GachaCore
Address0xbfc71b88c8e8dfcae836dc5128ff318deed54939
- Balance
0.02352 ETH
- Transactions
448
- Compiler
solc 0.8.26
- Same code
Only this contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,805,602
- Creation transaction
- 0xf25f3e8e5f…79fe4a3383
11 files
- src/core/GachaCore.solmain58.54 KB
- lib/solady/src/auth/Ownable.sol12.55 KB
- lib/solady/src/utils/ReentrancyGuard.sol2.33 KB
- lib/solady/src/utils/SafeTransferLib.sol32.8 KB
- src/core/CuratedAssetRegistry.sol8.58 KB
- src/interfaces/IERC721Minimal.sol384 B
- src/interfaces/IGachaIncentives.sol1.3 KB
- src/interfaces/IProtocolRewards.sol647 B
- src/interfaces/IRandomnessProvider.sol1.03 KB
- src/interfaces/ITokenAdmissionPolicy.sol272 B
- src/libraries/SparseWeightTree.sol2.18 KB
src/core/GachaCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Ownable} from "solady/src/auth/Ownable.sol";
import {ReentrancyGuard} from "solady/src/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {CuratedAssetRegistry} from "./CuratedAssetRegistry.sol";
import {IERC721Minimal} from "../interfaces/IERC721Minimal.sol";
import {IGachaIncentives} from "../interfaces/IGachaIncentives.sol";
import {IProtocolRewards} from "../interfaces/IProtocolRewards.sol";
import {IRandomnessProvider} from "../interfaces/IRandomnessProvider.sol";
import {SparseWeightTree} from "../libraries/SparseWeightTree.sol";
/// @title Curated Gacha Core
/// @notice NFT-backed acquisition pool with inverse-backing odds and ordered randomness processing.
/// @dev Pre-audit implementation. Do not deploy with valuable assets.
contract GachaCore is Ownable, ReentrancyGuard {
using SparseWeightTree for SparseWeightTree.Tree;
uint256 internal constant BPS = 10_000;
uint256 internal constant SCALE = 1e36;
uint256 internal constant INVERSE_WEIGHT_NUMERATOR = 1e36;
uint32 internal constant MAX_PENDING_ACQUISITIONS_LIMIT = 256;
uint32 internal constant MAX_BATCH_ACQUISITIONS_LIMIT = 5;
bytes32 internal constant DIRECT_DEPOSIT_MAGIC = keccak256("CURATED_GACHA_DIRECT_DEPOSIT_V1");
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
enum ListingStatus {
None,
PendingActivation,
Active,
Allocated,
Settled,
Withdrawn
}
enum AcquisitionStatus {
None,
Pending,
RandomReady,
Expired,
Processed,
Refunded
}
enum SettlementAction {
KeepNFT,
RelistNFT,
TakeBacking,
DepositorReleaseNFT,
DepositorReclaimNFT,
FinalizeUnsettled,
RecoverStuckNFT,
TakeMomo
}
struct Listing {
address collection;
address depositor;
address purchaser;
uint256 tokenId;
uint256 backing;
uint256 weight;
uint256 feeDebt;
uint64 activationSequence;
uint64 allocatedAt;
ListingStatus status;
bool projectedActive;
}
struct Acquisition {
address purchaser;
bytes32 providerRequestId;
uint256 priceEscrowed;
uint256 quotedPrice;
uint256 minWeightedValue;
uint256 randomWord;
uint256 listingId;
uint64 requestedAt;
uint64 deadline;
uint32 maxNegativeSlippageBps;
uint32 minListingCount;
AcquisitionStatus status;
}
struct DepositIntent {
address depositor;
uint256 backing;
}
struct Mutation {
uint256 listingId;
}
struct EconomicConfig {
/// @notice Expected NFT backing returned per 10,000 wei of acquisition price.
uint32 assetRtpBps;
uint32 acquisitionProtocolFeeBps;
uint32 backingPayoutBps;
uint32 keepNFTFeeBps;
uint32 positiveSlippageBps;
uint32 settlementWindow;
uint32 finalizationWindow;
uint32 randomnessTimeout;
uint32 maxPendingAcquisitions;
uint32 maxBatchAcquisitions;
}
/// @notice Request-time economic terms. Owner changes affect new requests immediately,
/// while a purchaser's already-paid pull keeps the terms it was quoted.
struct EconomicTerms {
uint32 assetRtpBps;
uint32 acquisitionProtocolFeeBps;
uint32 backingPayoutBps;
uint32 keepNFTFeeBps;
uint32 positiveSlippageBps;
uint32 settlementWindow;
uint32 finalizationWindow;
}
CuratedAssetRegistry public immutable registry;
IRandomnessProvider public randomnessProvider;
IGachaIncentives public incentives;
IProtocolRewards public rewards;
EconomicConfig public economicConfig;
uint256 public acquisitionConfigVersion = 1;
bool public acquisitionsEnabled;
bool public depositsEnabled = true;
bool public withdrawOnly;
/// @notice Current receiver for realized protocol fees and the only authorized MOMO settlement router.
/// @dev Owner changes remain immediate; the public getter makes the live economic route independently verifiable.
address public protocolFeeRecipient;
mapping(address collection => mapping(uint256 tokenId => DepositIntent intent)) public depositIntents;
uint256 private _nextListingId = 1;
mapping(uint256 listingId => Listing listing) public listings;
uint64 public lastIssuedSequence;
uint64 public lastProcessedSequence;
mapping(uint64 sequence => Acquisition acquisition) public acquisitions;
mapping(uint64 sequence => EconomicTerms terms) private _acquisitionTerms;
mapping(uint256 listingId => EconomicTerms terms) public listingTerms;
/// @notice Randomness adapter snapshotted when a request is paid.
/// @dev Provider rotation only affects future requests; an old adapter can still
/// complete or terminally expire the requests it originally created.
mapping(uint64 sequence => address provider) private _acquisitionProvider;
mapping(address provider => mapping(bytes32 providerRequestId => uint64 sequence)) private _providerRequestSequence;
mapping(address provider => mapping(bytes32 providerRequestId => bool used)) private _providerRequestIdUsed;
mapping(uint64 sequence => Mutation[] mutations) internal _mutations;
mapping(uint64 sequence => uint256 cursor) private _mutationCursor;
mapping(uint256 listingId => uint256 indexPlusOne) private _activationMutationIndex;
SparseWeightTree.Tree internal _selectionTree;
uint256 public liveListingCount;
uint256 public liveTotalWeight;
uint256 public liveWeightedBacking;
uint256 public projectedListingCount;
uint256 public projectedTotalWeight;
uint256 public projectedWeightedBacking;
/// @notice Acquisition-fee index shared equally by active listings.
uint256 private _accFeePerListing;
mapping(address account => uint256 amount) public claimableETH;
mapping(uint256 listingId => address recipient) private _stuckNFTRecipient;
uint256 public totalDepositIntentEscrow;
uint256 public totalBackingLiability;
uint256 public totalAcquisitionEscrow;
uint256 public totalUserLiability;
uint256 public accruedProtocolFees;
event DepositsEnabledSet(bool enabled);
event AcquisitionsEnabledSet(bool enabled);
event WithdrawOnlySet(bool enabled);
event EconomicConfigSet(EconomicConfig config);
event RandomnessProviderSet(address indexed provider);
event IncentivesSet(address indexed incentives);
event RewardsSet(address indexed rewards);
event ProtocolFeeRecipientSet(address indexed recipient);
event DepositIntentCreated(
address indexed collection, uint256 indexed tokenId, address indexed depositor, uint256 backing
);
event DepositIntentCancelled(
address indexed collection, uint256 indexed tokenId, address indexed depositor, uint256 backing
);
event DepositIntentConsumed(address indexed collection, uint256 indexed tokenId, uint256 indexed listingId);
event ListingSubmitted(
uint256 indexed listingId,
uint64 indexed activationSequence,
address indexed depositor,
address collection,
uint256 tokenId,
uint256 backing,
uint256 weight
);
event ListingActivated(uint256 indexed listingId, uint64 indexed sequence);
event ListingWithdrawn(uint256 indexed listingId, address indexed depositor, uint256 backing);
event ListingBackingUpdated(
uint256 indexed listingId,
address indexed depositor,
uint256 oldBacking,
uint256 newBacking,
uint256 oldWeight,
uint256 newWeight
);
event ListingFeesAccrued(uint256 indexed listingId, address indexed depositor, uint256 amount);
/// @dev For a batch, the first sequence carries the total provider fee and later sequences carry zero.
event AcquisitionRequested(
uint64 indexed sequence,
bytes32 indexed providerRequestId,
address indexed purchaser,
uint256 maxPriceEscrowed,
uint256 randomnessFee
);
event RandomnessStored(uint64 indexed sequence, bytes32 indexed providerRequestId);
event AcquisitionExpired(uint64 indexed sequence);
event RandomnessIgnored(uint64 indexed sequence, bytes32 indexed providerRequestId);
event AcquisitionRefunded(uint64 indexed sequence, address indexed purchaser, uint256 amount);
event ListingAllocated(
uint64 indexed sequence,
uint256 indexed listingId,
address indexed purchaser,
uint256 acquisitionPrice,
uint256 randomWord,
uint256 selectionTotalWeight
);
event NFTKept(
uint256 indexed listingId,
address indexed purchaser,
address indexed depositor,
uint256 depositorBackingCredit,
uint256 protocolFee
);
event NFTRelisted(
uint256 indexed oldListingId,
uint256 indexed newListingId,
address indexed purchaser,
uint256 depositorBackingCredit,
uint256 protocolFee
);
event BackingTaken(
uint256 indexed listingId,
address indexed purchaser,
address indexed depositor,
uint256 purchaserCredit,
uint256 retained
);
event NFTDeliveryDeferred(uint256 indexed listingId, address indexed recipient);
event StuckNFTRecovered(uint256 indexed listingId, address indexed recipient);
event ETHCredited(address indexed account, uint256 amount);
event ETHClaimed(address indexed account, address indexed recipient, uint256 amount);
event ProtocolFeesAccrued(uint256 amount);
event ProtocolFeesPaid(address indexed recipient, uint256 amount);
error InvalidAddress();
error InvalidConfiguration();
error DepositsDisabled();
error AcquisitionsDisabled();
error AcquisitionsMustBePaused();
error EmptyPool();
error InvalidPayment();
error PriceAboveLimit();
error WeightedValueBelowLimit();
error TooManyPendingAcquisitions();
error BatchTooLarge();
error InsufficientInventory();
error ProviderRequestCollision();
error InvalidProviderResponse();
error AcquisitionConfigurationChanged();
error InvalidAcquisitionStatus();
error RandomnessNotReady();
error RandomnessTimeoutNotReached();
error InvalidSequence();
error NotDepositor();
error NotPurchaser();
error WithdrawLocked();
error WithdrawOnlyActive();
error InvalidListingStatus();
error IneligibleTreeResult();
error SettlementWindowOpen();
error FinalizationWindowOpen();
error NothingToClaim();
error NoStuckNFT();
error Insolvent();
error NFTTransferFailed();
error DepositIntentExists();
error InvalidDepositIntent();
error NotDepositIntentOwner();
error UnexpectedNFTTransfer();
error OnlySettlementRouter();
constructor(address initialOwner, CuratedAssetRegistry registry_, IRandomnessProvider randomnessProvider_) {
if (
initialOwner == address(0) || address(registry_) == address(0) || address(randomnessProvider_) == address(0)
|| address(registry_).code.length == 0 || address(randomnessProvider_).code.length == 0
) revert InvalidAddress();
_initializeOwner(initialOwner);
registry = registry_;
randomnessProvider = randomnessProvider_;
protocolFeeRecipient = initialOwner;
economicConfig = EconomicConfig({
assetRtpBps: 9_550,
acquisitionProtocolFeeBps: 143,
backingPayoutBps: 9_450,
keepNFTFeeBps: 225,
positiveSlippageBps: 1_000,
settlementWindow: 1 days,
finalizationWindow: 7 days,
randomnessTimeout: 1 hours,
maxPendingAcquisitions: 64,
maxBatchAcquisitions: 5
});
}
receive() external payable {}
/*//////////////////////////////////////////////////////////////
ADMINISTRATION
//////////////////////////////////////////////////////////////*/
/// @notice Update every economic percentage and request-time limit immediately.
/// @dev Existing acquisitions and allocated listings retain their snapshotted terms.
function setEconomicConfig(EconomicConfig calldata newConfig) external onlyOwner {
if (
newConfig.assetRtpBps == 0 || newConfig.assetRtpBps > BPS || newConfig.acquisitionProtocolFeeBps > BPS
|| newConfig.backingPayoutBps < 5_000 || newConfig.backingPayoutBps > BPS
|| newConfig.keepNFTFeeBps > BPS || newConfig.backingPayoutBps < newConfig.keepNFTFeeBps
|| newConfig.positiveSlippageBps > BPS || newConfig.finalizationWindow < newConfig.settlementWindow
|| newConfig.settlementWindow == 0 || newConfig.randomnessTimeout == 0
|| newConfig.maxPendingAcquisitions == 0 || newConfig.maxBatchAcquisitions == 0
|| newConfig.maxPendingAcquisitions > MAX_PENDING_ACQUISITIONS_LIMIT
|| newConfig.maxBatchAcquisitions > MAX_BATCH_ACQUISITIONS_LIMIT
|| newConfig.maxBatchAcquisitions > newConfig.maxPendingAcquisitions
) revert InvalidConfiguration();
economicConfig = newConfig;
++acquisitionConfigVersion;
emit EconomicConfigSet(newConfig);
}
function setDepositsEnabled(bool enabled) external onlyOwner {
if (enabled && withdrawOnly) revert WithdrawOnlyActive();
depositsEnabled = enabled;
emit DepositsEnabledSet(enabled);
}
function setAcquisitionsEnabled(bool enabled) external onlyOwner {
if (enabled && withdrawOnly) revert WithdrawOnlyActive();
acquisitionsEnabled = enabled;
emit AcquisitionsEnabledSet(enabled);
}
/// @notice Atomically halt new capital and play while leaving settlement, expiry,
/// staged cancellation and safe active withdrawal available.
/// @dev Clearing this flag never reopens deposits or acquisitions automatically.
function setWithdrawOnly(bool enabled) external onlyOwner {
withdrawOnly = enabled;
if (enabled) {
if (depositsEnabled) {
depositsEnabled = false;
emit DepositsEnabledSet(false);
}
if (acquisitionsEnabled) {
acquisitionsEnabled = false;
emit AcquisitionsEnabledSet(false);
}
}
emit WithdrawOnlySet(enabled);
}
function setRandomnessProvider(IRandomnessProvider provider) external onlyOwner {
randomnessProvider = provider;
++acquisitionConfigVersion;
emit RandomnessProviderSet(address(provider));
}
/// @notice Bind both accounting modules exactly once while the pool is empty.
/// @dev Percentage parameters remain immediately configurable inside the bound modules.
function setModules(IGachaIncentives newIncentives, IProtocolRewards newRewards) external onlyOwner {
address newAddress = address(newIncentives);
if (
address(incentives) != address(0) || address(rewards) != address(0) || newAddress.code.length == 0
|| address(newRewards).code.length == 0 || newIncentives.gachaCore() != address(this)
|| newRewards.gachaCore() != address(this) || _nextListingId != 1
) revert InvalidConfiguration();
incentives = newIncentives;
address rewardsAddress = address(newRewards);
rewards = newRewards;
++acquisitionConfigVersion;
emit IncentivesSet(newAddress);
emit RewardsSet(rewardsAddress);
}
function setProtocolFeeRecipient(address recipient) external onlyOwner {
protocolFeeRecipient = recipient;
emit ProtocolFeeRecipientSet(recipient);
}
/*//////////////////////////////////////////////////////////////
LISTINGS
//////////////////////////////////////////////////////////////*/
function listNFT(address collection, uint256 tokenId) external payable nonReentrant returns (uint256 listingId) {
if (!depositsEnabled) revert DepositsDisabled();
registry.requireAllowed(collection, tokenId, msg.value);
if (depositIntents[collection][tokenId].depositor != address(0)) revert DepositIntentExists();
IERC721Minimal token = IERC721Minimal(collection);
token.transferFrom(msg.sender, address(this), tokenId);
if (token.ownerOf(tokenId) != address(this)) revert NFTTransferFailed();
listingId = _createListing(msg.sender, collection, tokenId, msg.value);
_assertSolvent();
}
/// @notice Escrow backing before a direct owner-initiated safe transfer.
/// @dev This path supports ERC-721C policies that allow `operator == from` but reject an
/// unlisted custody contract pulling the NFT after approval. The NFT is not part of
/// the pool until `onERC721Received` consumes this intent.
function createDepositIntent(address collection, uint256 tokenId) external payable nonReentrant {
if (!depositsEnabled) revert DepositsDisabled();
registry.requireAllowed(collection, tokenId, msg.value);
if (depositIntents[collection][tokenId].depositor != address(0)) revert DepositIntentExists();
if (IERC721Minimal(collection).ownerOf(tokenId) != msg.sender) revert NotDepositIntentOwner();
depositIntents[collection][tokenId] = DepositIntent({depositor: msg.sender, backing: msg.value});
totalDepositIntentEscrow += msg.value;
emit DepositIntentCreated(collection, tokenId, msg.sender, msg.value);
_assertSolvent();
}
/// @notice Cancel an unconsumed direct-transfer intent and credit its complete backing.
function cancelDepositIntent(address collection, uint256 tokenId) external nonReentrant {
DepositIntent memory intent = depositIntents[collection][tokenId];
if (intent.depositor == address(0)) revert InvalidDepositIntent();
if (intent.depositor != msg.sender) revert NotDepositIntentOwner();
delete depositIntents[collection][tokenId];
totalDepositIntentEscrow -= intent.backing;
_credit(intent.depositor, intent.backing);
emit DepositIntentCancelled(collection, tokenId, intent.depositor, intent.backing);
_assertSolvent();
}
/// @notice Consume a pre-funded intent when its owner directly safe-transfers the NFT.
/// @dev Transfer data must be `abi.encode(DIRECT_DEPOSIT_MAGIC)`. Requiring the NFT owner
/// to also be the transfer operator preserves the ERC-721C direct-transfer route and
/// prevents an approved third party from forcing an intent into the pool.
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external
nonReentrant
returns (bytes4)
{
if (!depositsEnabled) revert DepositsDisabled();
if (
data.length != 32 || abi.decode(data, (bytes32)) != DIRECT_DEPOSIT_MAGIC || operator != from
|| from == address(0)
) revert UnexpectedNFTTransfer();
DepositIntent memory intent = depositIntents[msg.sender][tokenId];
if (intent.depositor != from) revert InvalidDepositIntent();
registry.requireAllowed(msg.sender, tokenId, intent.backing);
if (IERC721Minimal(msg.sender).ownerOf(tokenId) != address(this)) revert NFTTransferFailed();
delete depositIntents[msg.sender][tokenId];
totalDepositIntentEscrow -= intent.backing;
uint256 listingId = _createListing(intent.depositor, msg.sender, tokenId, intent.backing);
emit DepositIntentConsumed(msg.sender, tokenId, listingId);
_assertSolvent();
return ERC721_RECEIVED;
}
/// @notice Cancel a listing before its activation sequence has been issued.
/// @dev Once that sequence exists, the listing is part of its committed candidate set.
/// Removing it before processing would let the depositor steer a known random word.
function cancelStagedListing(uint256 listingId) external nonReentrant {
Listing storage listing = listings[listingId];
if (listing.depositor != msg.sender) revert NotDepositor();
if (listing.status != ListingStatus.PendingActivation) revert InvalidListingStatus();
if (lastIssuedSequence >= listing.activationSequence) revert WithdrawLocked();
if (listing.projectedActive) {
listing.projectedActive = false;
_removeProjected(listing.backing, listing.weight);
}
_removeActivationMutation(listingId, listing.activationSequence);
_withdrawListing(listingId, listing);
}
/// @notice Withdraw an active listing together with its backing and accrued acquisition fees.
/// @dev Mirrors FWA's active-position gate: live weight cannot leave while any acquisition
/// can still select. Once every unresolved request is timeout/refund-only, this call marks
/// those requests expired and allows the withdrawal without waiting for separate keeper calls.
function withdrawListing(uint256 listingId) external nonReentrant {
_requireActiveExitUnlocked();
Listing storage listing = listings[listingId];
if (listing.depositor != msg.sender) revert NotDepositor();
if (listing.status != ListingStatus.Active) revert InvalidListingStatus();
if (listing.projectedActive) {
listing.projectedActive = false;
_removeProjected(listing.backing, listing.weight);
}
_removeLiveListing(listingId, listing);
_withdrawListing(listingId, listing);
}
/// @notice Re-price an active listing by replacing its backing and inverse selection weight.
/// @dev Uses the same exit gate as withdrawal because either direction changes live odds.
/// Increases require the exact ETH delta; decreases credit the freed backing for pull claim.
function updateBacking(uint256 listingId, uint256 newBacking) external payable nonReentrant {
Listing storage listing = listings[listingId];
if (listing.depositor != msg.sender) revert NotDepositor();
if (listing.status != ListingStatus.Active) revert InvalidListingStatus();
uint256 oldBacking = listing.backing;
if (newBacking == oldBacking) revert InvalidConfiguration();
if (withdrawOnly && newBacking > oldBacking) revert WithdrawOnlyActive();
registry.requireBackingUpdate(listing.collection, listing.tokenId, oldBacking, newBacking);
uint256 newWeight = INVERSE_WEIGHT_NUMERATOR / newBacking;
if (newWeight == 0) revert InvalidConfiguration();
if (newBacking > oldBacking) {
uint256 added = newBacking - oldBacking;
if (msg.value != added) revert InvalidPayment();
totalBackingLiability += added;
} else {
if (msg.value != 0) revert InvalidPayment();
uint256 released = oldBacking - newBacking;
totalBackingLiability -= released;
_credit(listing.depositor, released);
}
_requireActiveExitUnlocked();
_settleListingFees(listingId, listing);
_selectionTree.remove(listingId, listing.weight);
liveTotalWeight = liveTotalWeight - listing.weight + newWeight;
liveWeightedBacking = liveWeightedBacking - (listing.weight * oldBacking) + (newWeight * newBacking);
projectedTotalWeight = projectedTotalWeight - listing.weight + newWeight;
projectedWeightedBacking = projectedWeightedBacking - (listing.weight * oldBacking) + (newWeight * newBacking);
uint256 oldWeight = listing.weight;
listing.backing = newBacking;
listing.weight = newWeight;
_selectionTree.add(listingId, newWeight);
IGachaIncentives incentives_ = incentives;
if (address(incentives_) != address(0)) {
incentives_.onListingBackingUpdated(listingId, listing.depositor, oldBacking, newBacking);
}
IProtocolRewards rewards_ = rewards;
if (address(rewards_) != address(0)) {
rewards_.onActiveBackingChanged(listing.depositor, listingId, oldBacking, newBacking);
}
emit ListingBackingUpdated(listingId, listing.depositor, oldBacking, newBacking, oldWeight, newWeight);
_assertSolvent();
}
function _requireActiveExitUnlocked() internal {
uint64 issued = lastIssuedSequence;
uint64 sequence = lastProcessedSequence + 1;
while (sequence <= issued) {
Acquisition storage acquisition = acquisitions[sequence];
if (acquisition.status == AcquisitionStatus.Pending) {
// The timeout is an economic cutoff: after it, this request is refund-only and
// therefore cannot be steered by a pool exit.
// forge-lint: disable-next-line(block-timestamp)
if (block.timestamp < acquisition.deadline) revert WithdrawLocked();
_markAcquisitionExpired(sequence, acquisition);
} else if (acquisition.status != AcquisitionStatus.Expired) {
// A stored random word must be consumed against the pre-exit pool first.
revert WithdrawLocked();
}
unchecked {
++sequence;
}
}
}
function _createListing(address depositor, address collection, uint256 tokenId, uint256 backing)
internal
returns (uint256 listingId)
{
uint256 weight = INVERSE_WEIGHT_NUMERATOR / backing;
if (weight == 0) revert InvalidConfiguration();
listingId = _nextListingId++;
uint64 effectiveSequence = lastIssuedSequence + 1;
listings[listingId] = Listing({
collection: collection,
depositor: depositor,
purchaser: address(0),
tokenId: tokenId,
backing: backing,
weight: weight,
feeDebt: 0,
activationSequence: effectiveSequence,
allocatedAt: 0,
status: ListingStatus.PendingActivation,
projectedActive: true
});
totalBackingLiability += backing;
_addProjected(backing, weight);
_mutations[effectiveSequence].push(Mutation({listingId: listingId}));
_activationMutationIndex[listingId] = _mutations[effectiveSequence].length;
emit ListingSubmitted(listingId, effectiveSequence, depositor, collection, tokenId, backing, weight);
if (lastIssuedSequence == lastProcessedSequence) {
_syncMutations(effectiveSequence, 32);
}
}
function claimListingFees(uint256[] calldata listingIds) external nonReentrant returns (uint256 amount) {
uint256 length = listingIds.length;
for (uint256 i; i < length; ++i) {
Listing storage listing = listings[listingIds[i]];
if (listing.depositor != msg.sender) revert NotDepositor();
if (listing.status != ListingStatus.Active) revert InvalidListingStatus();
amount += _settleListingFees(listingIds[i], listing);
}
}
/*//////////////////////////////////////////////////////////////
ACQUISITIONS
//////////////////////////////////////////////////////////////*/
function requestAcquisition(
uint256 maxPrice,
uint256 minWeightedValue,
uint32 maxNegativeSlippageBps,
uint32 minListingCount,
uint256 expectedConfigVersion
) external payable nonReentrant returns (uint64 sequence, bytes32 providerRequestId) {
(EconomicConfig memory config, IRandomnessProvider provider, uint256 price, uint256 providerFee) = _prepareAcquisition(
1, maxPrice, minWeightedValue, maxNegativeSlippageBps, minListingCount, expectedConfigVersion
);
// `maxPrice` protects the request through FIFO processing, not only at
// transaction inclusion. Keep the full user-authorized amount in escrow
// and return the difference after the live clearing price is known.
uint256 required = maxPrice + providerFee;
if (msg.value < required) revert InvalidPayment();
sequence = lastIssuedSequence + 1;
_reserveBuyerRewards(sequence, msg.sender, price, config.assetRtpBps, 1);
bytes32[] memory requestIds = provider.requestRandomness{value: providerFee}(sequence, 1);
if (requestIds.length != 1) revert InvalidProviderResponse();
providerRequestId = requestIds[0];
_recordAcquisition(
msg.sender,
maxPrice,
price,
minWeightedValue,
maxNegativeSlippageBps,
providerFee,
minListingCount,
config,
provider,
providerRequestId
);
uint256 excess = msg.value - required;
if (excess != 0) _credit(msg.sender, excess);
_assertSolvent();
}
/// @notice Request several independently-expanded acquisitions at one current unit quote.
/// @dev The provider may use one master entropy request for the batch. It must still return
/// one domain-separated request ID and word per sequence.
function requestAcquisitionBatch(
uint32 quantity,
uint256 maxUnitPrice,
uint256 minWeightedValue,
uint32 maxNegativeSlippageBps,
uint32 minListingCount,
uint256 expectedConfigVersion
) external payable nonReentrant returns (uint64 firstSequence, bytes32[] memory providerRequestIds) {
(EconomicConfig memory config, IRandomnessProvider provider, uint256 unitPrice, uint256 providerFee) = _prepareAcquisition(
quantity, maxUnitPrice, minWeightedValue, maxNegativeSlippageBps, minListingCount, expectedConfigVersion
);
// Every independently processed item receives the same caller-approved
// ceiling. This is what makes a conservative safe-batch quote useful:
// live FIFO repricing can consume the buffer, while unused ETH is
// returned through the normal pull-credit path.
uint256 required = uint256(quantity) * maxUnitPrice + providerFee;
if (msg.value < required) revert InvalidPayment();
firstSequence = lastIssuedSequence + 1;
_reserveBuyerRewards(firstSequence, msg.sender, unitPrice, config.assetRtpBps, quantity);
providerRequestIds = provider.requestRandomness{value: providerFee}(firstSequence, quantity);
if (providerRequestIds.length != quantity) revert InvalidProviderResponse();
for (uint256 i; i < quantity; ++i) {
uint256 itemProviderFee = providerFee / quantity;
_recordAcquisition(
msg.sender,
maxUnitPrice,
unitPrice,
minWeightedValue,
maxNegativeSlippageBps,
itemProviderFee,
minListingCount,
config,
provider,
providerRequestIds[i]
);
}
uint256 excess = msg.value - required;
if (excess != 0) _credit(msg.sender, excess);
_assertSolvent();
}
function _prepareAcquisition(
uint32 quantity,
uint256 maxUnitPrice,
uint256 minWeightedValue,
uint32 maxNegativeSlippageBps,
uint32 minListingCount,
uint256 expectedConfigVersion
)
internal
view
returns (EconomicConfig memory config, IRandomnessProvider provider, uint256 price, uint256 providerFee)
{
if (!acquisitionsEnabled) revert AcquisitionsDisabled();
if (expectedConfigVersion != acquisitionConfigVersion) revert AcquisitionConfigurationChanged();
config = economicConfig;
if (quantity == 0 || quantity > config.maxBatchAcquisitions) revert BatchTooLarge();
if (maxNegativeSlippageBps > BPS) revert InvalidConfiguration();
if (projectedListingCount == 0 || projectedTotalWeight == 0) revert EmptyPool();
if (projectedListingCount < minListingCount) revert EmptyPool();
uint256 pending = lastIssuedSequence - lastProcessedSequence;
if (pending + quantity > config.maxPendingAcquisitions) revert TooManyPendingAcquisitions();
if (pending + quantity > projectedListingCount) revert InsufficientInventory();
uint256 weightedValue = projectedWeightedBacking / projectedTotalWeight;
if (weightedValue < minWeightedValue) revert WeightedValueBelowLimit();
price = _price(projectedWeightedBacking, projectedTotalWeight, config.assetRtpBps);
if (price == 0) revert EmptyPool();
if (price > maxUnitPrice) revert PriceAboveLimit();
provider = randomnessProvider;
providerFee = provider.quoteRequestFee(quantity);
}
function _recordAcquisition(
address purchaser,
uint256 maxPriceEscrowed,
uint256 quotedPrice,
uint256 minWeightedValue,
uint32 maxNegativeSlippageBps,
uint256 providerFee,
uint32 minListingCount,
EconomicConfig memory config,
IRandomnessProvider provider,
bytes32 providerRequestId
) internal {
uint64 sequence = ++lastIssuedSequence;
address providerAddress = address(provider);
if (providerRequestId == bytes32(0) || _providerRequestIdUsed[providerAddress][providerRequestId]) {
revert ProviderRequestCollision();
}
_providerRequestIdUsed[providerAddress][providerRequestId] = true;
acquisitions[sequence] = Acquisition({
purchaser: purchaser,
providerRequestId: providerRequestId,
priceEscrowed: maxPriceEscrowed,
quotedPrice: quotedPrice,
minWeightedValue: minWeightedValue,
randomWord: 0,
listingId: 0,
requestedAt: uint64(block.timestamp),
deadline: uint64(block.timestamp + config.randomnessTimeout),
maxNegativeSlippageBps: maxNegativeSlippageBps,
minListingCount: minListingCount,
status: AcquisitionStatus.Pending
});
_acquisitionTerms[sequence] = EconomicTerms({
assetRtpBps: config.assetRtpBps,
acquisitionProtocolFeeBps: config.acquisitionProtocolFeeBps,
backingPayoutBps: config.backingPayoutBps,
keepNFTFeeBps: config.keepNFTFeeBps,
positiveSlippageBps: config.positiveSlippageBps,
settlementWindow: config.settlementWindow,
finalizationWindow: config.finalizationWindow
});
_acquisitionProvider[sequence] = providerAddress;
_providerRequestSequence[providerAddress][providerRequestId] = sequence;
totalAcquisitionEscrow += maxPriceEscrowed;
emit AcquisitionRequested(sequence, providerRequestId, purchaser, maxPriceEscrowed, providerFee);
}
function _reserveBuyerRewards(
uint64 firstSequence,
address purchaser,
uint256 price,
uint32 assetRtpBps,
uint32 quantity
) internal {
IGachaIncentives incentives_ = incentives;
if (address(incentives_) != address(0)) {
incentives_.reserveBuyerRewardBatch(firstSequence, purchaser, price, assetRtpBps, quantity);
}
}
/// @notice Store a provider word. Selection and transfers are deliberately deferred.
function fulfillRandomness(bytes32 providerRequestId, uint256 randomWord) external {
uint64 sequence = _providerRequestSequence[msg.sender][providerRequestId];
if (sequence == 0) revert InvalidSequence();
Acquisition storage acquisition = acquisitions[sequence];
if (acquisition.status != AcquisitionStatus.Pending) {
delete _providerRequestSequence[msg.sender][providerRequestId];
emit RandomnessIgnored(sequence, providerRequestId);
return;
}
// The deadline is a hard economic cutoff. A late provider response cannot race
// a depositor's exit or turn an already-refund-only request back into a selection.
// Returning normally also lets push-based providers terminate the callback cleanly.
// forge-lint: disable-next-line(block-timestamp)
if (block.timestamp >= acquisition.deadline) {
_markAcquisitionExpired(sequence, acquisition);
delete _providerRequestSequence[msg.sender][providerRequestId];
emit RandomnessIgnored(sequence, providerRequestId);
return;
}
acquisition.randomWord = randomWord;
acquisition.status = AcquisitionStatus.RandomReady;
delete _providerRequestSequence[msg.sender][providerRequestId];
emit RandomnessStored(sequence, providerRequestId);
}
/// @notice Make a request refund-only after timeout or a provider-proven terminal failure.
/// @dev Only the configured adapter may expire before the coarse timeout. Its immutable
/// coordinator binding must prove that the original entropy source is unavailable.
function expireAcquisition(uint64 sequence) external {
Acquisition storage acquisition = acquisitions[sequence];
if (acquisition.status != AcquisitionStatus.Pending) revert InvalidAcquisitionStatus();
address requestProvider = _acquisitionProvider[sequence];
if (msg.sender != requestProvider) {
// This is a coarse timeout boundary, not a source of randomness or economic pricing.
// forge-lint: disable-next-line(block-timestamp)
if (block.timestamp < acquisition.deadline) revert RandomnessTimeoutNotReached();
}
_markAcquisitionExpired(sequence, acquisition);
if (msg.sender == requestProvider) {
delete _providerRequestSequence[requestProvider][acquisition.providerRequestId];
}
}
/// @notice Permissionlessly consume ready random words in canonical request order.
function processReady(uint256 maxRequests, uint256 maxMutationsPerSequence)
external
nonReentrant
returns (uint256 processed)
{
while (processed < maxRequests) {
uint64 sequence = lastProcessedSequence + 1;
if (sequence > lastIssuedSequence) break;
(, bool mutationsComplete) = _syncMutations(sequence, maxMutationsPerSequence);
if (!mutationsComplete) break;
Acquisition storage acquisition = acquisitions[sequence];
if (acquisition.status != AcquisitionStatus.RandomReady && acquisition.status != AcquisitionStatus.Expired) break;
_processAcquisition(sequence, acquisition);
lastProcessedSequence = sequence;
unchecked {
++processed;
}
}
_assertSolvent();
}
/*//////////////////////////////////////////////////////////////
SETTLEMENT
//////////////////////////////////////////////////////////////*/
/// @notice Resolve an allocated listing directly as `msg.sender`.
/// @dev The action enum is shared by purchaser, depositor, finalizer and NFT-recovery paths.
function settle(SettlementAction action, uint256 listingId) external payable nonReentrant returns (uint256 result) {
result = _executeSettlement(action, msg.sender, listingId);
}
function _executeSettlement(SettlementAction action, address actor, uint256 listingId)
internal
returns (uint256 result)
{
if (action == SettlementAction.RecoverStuckNFT) {
if (msg.value != 0) revert InvalidPayment();
address recipient = _stuckNFTRecipient[listingId];
if (recipient == address(0)) revert NoStuckNFT();
Listing storage stuckListing = listings[listingId];
if (!_tryNFTTransfer(stuckListing, recipient)) revert NFTTransferFailed();
delete _stuckNFTRecipient[listingId];
emit StuckNFTRecovered(listingId, recipient);
return 0;
}
Listing storage listing = _allocatedListing(listingId);
if (action == SettlementAction.TakeMomo) {
if (msg.value != 0 || actor != protocolFeeRecipient) revert OnlySettlementRouter();
(result,) = _settleBackingOutcome(listingId, listing, false);
SafeTransferLib.safeTransferETH(actor, result);
_assertSolvent();
return result;
}
EconomicTerms memory terms = listingTerms[listingId];
if (action == SettlementAction.KeepNFT) {
if (msg.value != 0 || listing.purchaser != actor) revert NotPurchaser();
_settleNFTToPurchaser(listingId, listing, true);
} else if (action == SettlementAction.RelistNFT) {
if (!depositsEnabled) revert DepositsDisabled();
if (listing.purchaser != actor) revert NotPurchaser();
address collection = listing.collection;
uint256 tokenId = listing.tokenId;
registry.requireAllowed(collection, tokenId, msg.value);
if (IERC721Minimal(collection).ownerOf(tokenId) != address(this)) revert NFTTransferFailed();
(uint256 depositorCredit, uint256 protocolCut) = _settleBackingToDepositor(listingId, listing);
result = _createListing(actor, collection, tokenId, msg.value);
emit NFTRelisted(listingId, result, actor, depositorCredit, protocolCut);
_assertSolvent();
} else if (action == SettlementAction.TakeBacking) {
if (msg.value != 0 || listing.purchaser != actor) revert NotPurchaser();
_settleBackingToPurchaser(listingId, listing);
} else if (action == SettlementAction.DepositorReleaseNFT) {
if (msg.value != 0 || listing.depositor != actor) revert NotDepositor();
// forge-lint: disable-next-line(block-timestamp)
if (block.timestamp < listing.allocatedAt + terms.settlementWindow) {
revert SettlementWindowOpen();
}
_settleNFTToPurchaser(listingId, listing, false);
} else if (action == SettlementAction.DepositorReclaimNFT) {
if (msg.value != 0 || listing.depositor != actor) revert NotDepositor();
// forge-lint: disable-next-line(block-timestamp)
if (block.timestamp < listing.allocatedAt + terms.settlementWindow) {
revert SettlementWindowOpen();
}
_settleBackingToPurchaser(listingId, listing);
} else {
if (msg.value != 0) revert InvalidPayment();
// forge-lint: disable-next-line(block-timestamp)
if (block.timestamp < listing.allocatedAt + terms.finalizationWindow) {
revert FinalizationWindowOpen();
}
_settleNFTToPurchaser(listingId, listing, false);
}
}
/*//////////////////////////////////////////////////////////////
PAYMENTS
//////////////////////////////////////////////////////////////*/
function claimETH(address recipient) external nonReentrant returns (uint256 amount) {
if (recipient == address(0)) revert InvalidAddress();
amount = claimableETH[msg.sender];
if (amount == 0) revert NothingToClaim();
claimableETH[msg.sender] = 0;
totalUserLiability -= amount;
SafeTransferLib.safeTransferETH(recipient, amount);
emit ETHClaimed(msg.sender, recipient, amount);
_assertSolvent();
}
function payoutProtocolFees() external nonReentrant returns (uint256 amount) {
amount = accruedProtocolFees;
if (amount == 0) revert NothingToClaim();
accruedProtocolFees = 0;
address recipient = protocolFeeRecipient;
SafeTransferLib.safeTransferETH(recipient, amount);
emit ProtocolFeesPaid(recipient, amount);
_assertSolvent();
}
/*//////////////////////////////////////////////////////////////
INTERNAL: ACQUISITION
//////////////////////////////////////////////////////////////*/
function _markAcquisitionExpired(uint64 sequence, Acquisition storage acquisition) internal {
acquisition.status = AcquisitionStatus.Expired;
emit AcquisitionExpired(sequence);
}
function _processAcquisition(uint64 sequence, Acquisition storage acquisition) internal {
uint256 escrowed = acquisition.priceEscrowed;
totalAcquisitionEscrow -= escrowed;
if (acquisition.status == AcquisitionStatus.Expired) {
acquisition.status = AcquisitionStatus.Refunded;
delete _acquisitionProvider[sequence];
_credit(acquisition.purchaser, escrowed);
emit AcquisitionRefunded(sequence, acquisition.purchaser, escrowed);
return;
}
EconomicTerms memory terms = _acquisitionTerms[sequence];
uint256 livePrice = _price(liveWeightedBacking, liveTotalWeight, terms.assetRtpBps);
uint256 liveWeightedValue = liveTotalWeight == 0 ? 0 : liveWeightedBacking / liveTotalWeight;
uint256 minimumDriftPrice = acquisition.quotedPrice * (BPS - acquisition.maxNegativeSlippageBps) / BPS;
uint256 maximumDriftPrice = acquisition.quotedPrice * (BPS + terms.positiveSlippageBps) / BPS;
if (
liveTotalWeight == 0 || liveListingCount < acquisition.minListingCount || livePrice == 0
|| liveWeightedValue < acquisition.minWeightedValue || livePrice < minimumDriftPrice
|| livePrice > maximumDriftPrice || livePrice > escrowed
) {
acquisition.status = AcquisitionStatus.Refunded;
delete _acquisitionProvider[sequence];
_credit(acquisition.purchaser, escrowed);
emit AcquisitionRefunded(sequence, acquisition.purchaser, escrowed);
return;
}
uint256 selectionTotalWeight = liveTotalWeight;
uint256 target = uint256(
keccak256(abi.encode(acquisition.randomWord, sequence, acquisition.purchaser, address(this)))
) % selectionTotalWeight;
uint256 listingId = _selectionTree.select(target);
Listing storage listing = listings[listingId];
if (listing.status != ListingStatus.Active || listing.activationSequence > sequence) {
revert IneligibleTreeResult();
}
uint256 refund = escrowed - livePrice;
if (refund != 0) _credit(acquisition.purchaser, refund);
IGachaIncentives incentives_ = incentives;
uint256 buyerRewardETH;
uint256 topListingShare;
if (address(incentives_) != address(0)) {
(buyerRewardETH, topListingShare) = incentives_.successfulAcquisitionRouting(
sequence, livePrice, terms.assetRtpBps, terms.acquisitionProtocolFeeBps
);
}
uint256 distributable = livePrice - buyerRewardETH;
uint256 protocolCut = distributable * terms.acquisitionProtocolFeeBps / BPS;
uint256 depositorDistribution = distributable - protocolCut;
_accrueProtocolFee(protocolCut);
if (address(incentives_) != address(0)) {
incentives_.fundSuccessfulAcquisition{value: buyerRewardETH + topListingShare}(
sequence, acquisition.purchaser, livePrice, terms.assetRtpBps, terms.acquisitionProtocolFeeBps
);
}
_distributeToListings(depositorDistribution - topListingShare);
_removeLiveListing(listingId, listing);
if (listing.projectedActive) {
listing.projectedActive = false;
_removeProjected(listing.backing, listing.weight);
}
listing.status = ListingStatus.Allocated;
listing.purchaser = acquisition.purchaser;
listing.allocatedAt = uint64(block.timestamp);
listingTerms[listingId] = terms;
acquisition.listingId = listingId;
acquisition.status = AcquisitionStatus.Processed;
delete _acquisitionProvider[sequence];
IProtocolRewards rewards_ = rewards;
if (address(rewards_) != address(0)) {
rewards_.onSuccessfulPlay(acquisition.purchaser, livePrice, sequence);
}
emit ListingAllocated(
sequence, listingId, acquisition.purchaser, livePrice, acquisition.randomWord, selectionTotalWeight
);
}
/*//////////////////////////////////////////////////////////////
INTERNAL: MUTATIONS
//////////////////////////////////////////////////////////////*/
function _syncMutations(uint64 sequence, uint256 maxMutations) internal returns (uint256 applied, bool complete) {
Mutation[] storage mutations = _mutations[sequence];
uint256 cursor = _mutationCursor[sequence];
uint256 length = mutations.length;
while (cursor < length && applied < maxMutations) {
Mutation storage mutation = mutations[cursor];
Listing storage listing = listings[mutation.listingId];
if (listing.status == ListingStatus.PendingActivation && listing.activationSequence == sequence) {
delete _activationMutationIndex[mutation.listingId];
_activateListing(mutation.listingId, listing, sequence);
}
unchecked {
++cursor;
++applied;
}
}
_mutationCursor[sequence] = cursor;
complete = cursor == length;
}
function _removeActivationMutation(uint256 listingId, uint64 sequence) internal {
uint256 indexPlusOne = _activationMutationIndex[listingId];
if (indexPlusOne == 0) revert InvalidConfiguration();
Mutation[] storage mutations = _mutations[sequence];
uint256 index = indexPlusOne - 1;
uint256 cursor = _mutationCursor[sequence];
uint256 lastIndex = mutations.length - 1;
if (index < cursor || index > lastIndex) revert InvalidConfiguration();
if (index != lastIndex) {
uint256 movedListingId = mutations[lastIndex].listingId;
mutations[index] = mutations[lastIndex];
_activationMutationIndex[movedListingId] = index + 1;
}
mutations.pop();
delete _activationMutationIndex[listingId];
}
function _activateListing(uint256 listingId, Listing storage listing, uint64 sequence) internal {
listing.feeDebt = _accFeePerListing;
listing.status = ListingStatus.Active;
_selectionTree.add(listingId, listing.weight);
liveListingCount += 1;
liveTotalWeight += listing.weight;
liveWeightedBacking += listing.weight * listing.backing;
IGachaIncentives incentives_ = incentives;
if (address(incentives_) != address(0)) {
incentives_.onListingActivated(listingId, listing.depositor, listing.backing);
}
IProtocolRewards rewards_ = rewards;
if (address(rewards_) != address(0)) {
rewards_.onActiveBackingChanged(listing.depositor, listingId, 0, listing.backing);
}
emit ListingActivated(listingId, sequence);
}
function _removeLiveListing(uint256 listingId, Listing storage listing) internal {
_settleListingFees(listingId, listing);
_selectionTree.remove(listingId, listing.weight);
liveListingCount -= 1;
liveTotalWeight -= listing.weight;
liveWeightedBacking -= listing.weight * listing.backing;
IGachaIncentives incentives_ = incentives;
if (address(incentives_) != address(0)) incentives_.onListingRemoved(listingId);
IProtocolRewards rewards_ = rewards;
if (address(rewards_) != address(0)) {
rewards_.onActiveBackingChanged(listing.depositor, listingId, listing.backing, 0);
}
}
/*//////////////////////////////////////////////////////////////
INTERNAL: SETTLEMENT
//////////////////////////////////////////////////////////////*/
function _allocatedListing(uint256 listingId) internal view returns (Listing storage listing) {
listing = listings[listingId];
if (listing.status != ListingStatus.Allocated) revert InvalidListingStatus();
}
function _settleNFTToPurchaser(uint256 listingId, Listing storage listing, bool safe) internal {
(uint256 depositorCredit, uint256 protocolCut) = _settleBackingToDepositor(listingId, listing);
if (safe) {
IERC721Minimal(listing.collection).safeTransferFrom(address(this), listing.purchaser, listing.tokenId);
if (IERC721Minimal(listing.collection).ownerOf(listing.tokenId) != listing.purchaser) {
revert NFTTransferFailed();
}
} else {
_deliverNFTOrDefer(listingId, listing, listing.purchaser);
}
emit NFTKept(listingId, listing.purchaser, listing.depositor, depositorCredit, protocolCut);
_assertSolvent();
}
function _settleBackingToDepositor(uint256 listingId, Listing storage listing)
internal
returns (uint256 depositorCredit, uint256 protocolCut)
{
uint256 backing = listing.backing;
protocolCut = backing * listingTerms[listingId].keepNFTFeeBps / BPS;
depositorCredit = backing - protocolCut;
listing.status = ListingStatus.Settled;
totalBackingLiability -= backing;
_credit(listing.depositor, depositorCredit);
_accrueProtocolFee(protocolCut);
}
function _settleBackingToPurchaser(uint256 listingId, Listing storage listing) internal {
_settleBackingOutcome(listingId, listing, true);
_assertSolvent();
}
function _settleBackingOutcome(uint256 listingId, Listing storage listing, bool creditPurchaser)
internal
returns (uint256 purchaserCredit, uint256 retained)
{
uint256 backing = listing.backing;
purchaserCredit = backing * listingTerms[listingId].backingPayoutBps / BPS;
retained = backing - purchaserCredit;
listing.status = ListingStatus.Settled;
totalBackingLiability -= backing;
if (creditPurchaser) _credit(listing.purchaser, purchaserCredit);
_accrueProtocolFee(retained);
_deliverNFTOrDefer(listingId, listing, listing.depositor);
emit BackingTaken(listingId, listing.purchaser, listing.depositor, purchaserCredit, retained);
}
function _withdrawListing(uint256 listingId, Listing storage listing) internal {
uint256 backing = listing.backing;
listing.status = ListingStatus.Withdrawn;
totalBackingLiability -= backing;
_credit(listing.depositor, backing);
_deliverNFTOrDefer(listingId, listing, listing.depositor);
emit ListingWithdrawn(listingId, listing.depositor, backing);
_assertSolvent();
}
function _deliverNFTOrDefer(uint256 listingId, Listing storage listing, address recipient) internal {
if (_tryNFTTransfer(listing, recipient)) return;
_stuckNFTRecipient[listingId] = recipient;
emit NFTDeliveryDeferred(listingId, recipient);
}
function _tryNFTTransfer(Listing storage listing, address recipient) internal returns (bool delivered) {
try IERC721Minimal(listing.collection).transferFrom(address(this), recipient, listing.tokenId) {
try IERC721Minimal(listing.collection).ownerOf(listing.tokenId) returns (address owner) {
delivered = owner == recipient;
} catch {}
} catch {}
}
/*//////////////////////////////////////////////////////////////
INTERNAL: ACCOUNTING
//////////////////////////////////////////////////////////////*/
function _price(uint256 weightedBacking, uint256 totalWeight, uint32 assetRtpBps) internal pure returns (uint256) {
if (totalWeight == 0) return 0;
uint256 expectedValue = weightedBacking / totalWeight;
// Round up so the configured RTP is never exceeded because of integer division.
return (expectedValue * BPS + assetRtpBps - 1) / assetRtpBps;
}
function _addProjected(uint256 backing, uint256 weight) internal {
projectedListingCount += 1;
projectedTotalWeight += weight;
projectedWeightedBacking += backing * weight;
}
function _removeProjected(uint256 backing, uint256 weight) internal {
projectedListingCount -= 1;
projectedTotalWeight -= weight;
projectedWeightedBacking -= backing * weight;
}
function _distributeToListings(uint256 amount) internal {
if (amount == 0) return;
if (liveListingCount == 0) {
_accrueProtocolFee(amount);
return;
}
_accFeePerListing += amount * SCALE / liveListingCount;
// Rounding can make a few wei permanently unclaimable. Reserving the full amount favors solvency.
totalUserLiability += amount;
}
function _settleListingFees(uint256 listingId, Listing storage listing) internal returns (uint256 amount) {
uint256 delta = _accFeePerListing - listing.feeDebt;
listing.feeDebt = _accFeePerListing;
amount = delta / SCALE;
if (amount != 0) {
claimableETH[listing.depositor] += amount;
emit ListingFeesAccrued(listingId, listing.depositor, amount);
}
}
function _credit(address account, uint256 amount) internal {
if (amount == 0) return;
claimableETH[account] += amount;
totalUserLiability += amount;
emit ETHCredited(account, amount);
}
function _accrueProtocolFee(uint256 amount) internal {
if (amount == 0) return;
accruedProtocolFees += amount;
emit ProtocolFeesAccrued(amount);
}
function _assertSolvent() internal view {
if (
address(this).balance
< totalDepositIntentEscrow + totalBackingLiability + totalAcquisitionEscrow + totalUserLiability
+ accruedProtocolFees
) revert Insolvent();
}
}
lib/solady/src/auth/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
lib/solady/src/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
/// 9 bytes is large enough to avoid collisions with lower slots,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_REENTRANCY_GUARD_SLOT, address())
}
_;
/// @solidity memory-safe-assembly
assembly {
sstore(_REENTRANCY_GUARD_SLOT, codesize())
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
_;
}
}
lib/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
/// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
/// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) {
revert(codesize(), codesize())
} // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) {
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
/// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
/// and upon failure, deploys a minimal vault to accrue the ETH.
function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
/// @solidity memory-safe-assembly
assembly {
to := shr(96, shl(96, to)) // Clean upper 96 bits.
for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
let selfBalanceBefore := selfbalance()
if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if extcodesize(mover) {
let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
mstore(0x00, to)
pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
// If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
// Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
if lt(selfBalanceBefore, selfbalance()) { invalid() }
}
let m := mload(0x40)
// If the mover is missing or bricked, deploy a minimal vault
// that withdraws all ETH to `to` when being called only by `to`.
// forgefmt: disable-next-item
mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
// Compute and store the bytecode hash.
mstore8(0x00, 0xff) // Write the prefix.
mstore(0x35, keccak256(m, 0x40))
mstore(0x01, shl(96, address())) // Deployer.
mstore(0x15, 0) // Salt.
vault := keccak256(0x00, 0x55)
pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
// The vault returns a single word on success. Failure reverts with empty data.
if iszero(returndatasize()) {
if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
}
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount := mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Performs a `token.balanceOf(account)` check.
/// `implemented` denotes whether the `token` implements `balanceOf`.
/// `amount` is zero if the `token` does not implement `balanceOf`.
function checkBalanceOf(address token, address account)
internal
view
returns (bool implemented, uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
implemented := and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
amount := mul(mload(0x20), implemented)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))
) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0x84, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
src/core/CuratedAssetRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Ownable} from "solady/src/auth/Ownable.sol";
import {ITokenAdmissionPolicy} from "../interfaces/ITokenAdmissionPolicy.sol";
/// @notice Curator-controlled admission registry for NFT collections.
/// @dev Disabling a collection blocks new listings but never changes existing custody positions.
contract CuratedAssetRegistry is Ownable {
enum AssetStandard {
Unsupported,
ERC721
}
struct CollectionConfig {
AssetStandard standard;
bool enabled;
bool permanentlyBlocked;
uint96 minBacking;
uint96 maxBacking;
}
struct CollectionUpdate {
address collection;
AssetStandard standard;
bool enabled;
uint96 minBacking;
uint96 maxBacking;
}
mapping(address collection => CollectionConfig config) public collectionConfig;
mapping(address collection => address policy) public tokenAdmissionPolicy;
event CollectionConfigured(
address indexed collection, AssetStandard standard, bool enabled, uint96 minBacking, uint96 maxBacking
);
event CollectionBlocked(address indexed collection);
event TokenAdmissionPolicySet(address indexed collection, address indexed policy);
error InvalidCollection();
error InvalidBackingRange();
error CollectionPermanentlyBlocked();
error CollectionNotAllowed();
error BackingOutOfRange();
error TokenNotAllowed();
error TokenIdRequired();
constructor(address initialOwner) {
if (initialOwner == address(0)) revert InvalidCollection();
_initializeOwner(initialOwner);
}
function configureCollection(
address collection,
AssetStandard standard,
bool enabled,
uint96 minBacking,
uint96 maxBacking
) external onlyOwner {
_configureCollection(collection, standard, enabled, minBacking, maxBacking);
}
/// @notice Apply a curator-reviewed batch. This remains callable after launch so
/// the handpicked pool can expand without replacing the registry or core.
function configureCollections(CollectionUpdate[] calldata updates) external onlyOwner {
uint256 length = updates.length;
if (length == 0) revert InvalidCollection();
for (uint256 i; i < length; ++i) {
CollectionUpdate calldata update = updates[i];
_configureCollection(
update.collection, update.standard, update.enabled, update.minBacking, update.maxBacking
);
}
}
function _configureCollection(
address collection,
AssetStandard standard,
bool enabled,
uint96 minBacking,
uint96 maxBacking
) internal {
if (collection.code.length == 0) revert InvalidCollection();
if (standard == AssetStandard.Unsupported) revert InvalidCollection();
if (minBacking == 0 || maxBacking < minBacking) revert InvalidBackingRange();
CollectionConfig storage current = collectionConfig[collection];
if (current.permanentlyBlocked) revert CollectionPermanentlyBlocked();
current.standard = standard;
current.enabled = enabled;
current.minBacking = minBacking;
current.maxBacking = maxBacking;
emit CollectionConfigured(collection, standard, enabled, minBacking, maxBacking);
}
/// @notice Irreversibly reject new listings from a compromised or malicious collection.
function permanentlyBlockCollection(address collection) external onlyOwner {
CollectionConfig storage current = collectionConfig[collection];
current.enabled = false;
current.permanentlyBlocked = true;
emit CollectionBlocked(collection);
}
/// @notice Attach a token-aware policy to a wrapper/aggregate collection.
/// @dev Address zero removes the hook. The hook is queried with STATICCALL through
/// its view interface and affects only new listings and backing increases.
function setTokenAdmissionPolicy(address collection, address policy) external onlyOwner {
if (collection.code.length == 0 || (policy != address(0) && policy.code.length == 0)) {
revert InvalidCollection();
}
tokenAdmissionPolicy[collection] = policy;
emit TokenAdmissionPolicySet(collection, policy);
}
function requireAllowed(address collection, uint256 backing) external view {
if (tokenAdmissionPolicy[collection] != address(0)) revert TokenIdRequired();
CollectionConfig memory config = collectionConfig[collection];
if (!config.enabled || config.permanentlyBlocked || config.standard != AssetStandard.ERC721) {
revert CollectionNotAllowed();
}
if (backing < config.minBacking || backing > config.maxBacking) revert BackingOutOfRange();
}
function requireAllowed(address collection, uint256 tokenId, uint256 backing) external view {
_requireCollectionAndBacking(collection, backing);
_requireTokenAllowed(collection, tokenId);
}
/// @notice Validate an in-custody listing's backing change.
/// @dev A disabled or permanently blocked collection may reduce backing so its depositor
/// is not trapped, but cannot add capital or increase its influence on pool pricing.
function requireBackingUpdate(address collection, uint256 oldBacking, uint256 newBacking) external view {
if (newBacking > oldBacking && tokenAdmissionPolicy[collection] != address(0)) revert TokenIdRequired();
CollectionConfig memory config = collectionConfig[collection];
if (config.standard != AssetStandard.ERC721) revert CollectionNotAllowed();
if (newBacking < config.minBacking || newBacking > config.maxBacking) revert BackingOutOfRange();
if (newBacking > oldBacking && (!config.enabled || config.permanentlyBlocked)) {
revert CollectionNotAllowed();
}
}
function requireBackingUpdate(address collection, uint256 tokenId, uint256 oldBacking, uint256 newBacking)
external
view
{
CollectionConfig memory config = collectionConfig[collection];
if (config.standard != AssetStandard.ERC721) revert CollectionNotAllowed();
if (newBacking < config.minBacking || newBacking > config.maxBacking) revert BackingOutOfRange();
if (newBacking > oldBacking) {
if (!config.enabled || config.permanentlyBlocked) revert CollectionNotAllowed();
_requireTokenAllowed(collection, tokenId);
}
}
function isAllowed(address collection, uint256 backing) external view returns (bool) {
if (tokenAdmissionPolicy[collection] != address(0)) return false;
CollectionConfig memory config = collectionConfig[collection];
return config.enabled && !config.permanentlyBlocked && config.standard == AssetStandard.ERC721
&& backing >= config.minBacking && backing <= config.maxBacking;
}
function isAllowed(address collection, uint256 tokenId, uint256 backing) external view returns (bool) {
CollectionConfig memory config = collectionConfig[collection];
if (
!config.enabled || config.permanentlyBlocked || config.standard != AssetStandard.ERC721
|| backing < config.minBacking || backing > config.maxBacking
) return false;
address policy = tokenAdmissionPolicy[collection];
if (policy == address(0)) return true;
try ITokenAdmissionPolicy(policy).isTokenAllowed(collection, tokenId) returns (bool allowed) {
return allowed;
} catch {
return false;
}
}
function _requireCollectionAndBacking(address collection, uint256 backing) internal view {
CollectionConfig memory config = collectionConfig[collection];
if (!config.enabled || config.permanentlyBlocked || config.standard != AssetStandard.ERC721) {
revert CollectionNotAllowed();
}
if (backing < config.minBacking || backing > config.maxBacking) revert BackingOutOfRange();
}
function _requireTokenAllowed(address collection, uint256 tokenId) internal view {
address policy = tokenAdmissionPolicy[collection];
if (policy == address(0)) return;
bool allowed;
try ITokenAdmissionPolicy(policy).isTokenAllowed(collection, tokenId) returns (bool tokenAllowed) {
allowed = tokenAllowed;
} catch {}
if (!allowed) revert TokenNotAllowed();
}
}
src/interfaces/IERC721Minimal.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Minimal ERC-721 interface used by the custody core.
interface IERC721Minimal {
function ownerOf(uint256 tokenId) external view returns (address);
function transferFrom(address from, address to, uint256 tokenId) external;
function safeTransferFrom(address from, address to, uint256 tokenId) external;
}
src/interfaces/IGachaIncentives.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Strict acquisition-incentive sink used by `GachaCore`.
interface IGachaIncentives {
function gachaCore() external view returns (address);
function reserveBuyerRewardBatch(
uint64 firstSequence,
address purchaser,
uint256 acquisitionPrice,
uint32 surchargeBps,
uint32 quantity
) external;
function activeListingCount() external view returns (uint256);
function activeBackingTotal() external view returns (uint256);
function successfulAcquisitionRouting(
uint64 sequence,
uint256 livePrice,
uint32 surchargeBps,
uint32 acquisitionProtocolFeeBps
) external view returns (uint256 buyerRewardETH, uint256 topListingShare);
function fundSuccessfulAcquisition(
uint64 sequence,
address purchaser,
uint256 livePrice,
uint32 surchargeBps,
uint32 acquisitionProtocolFeeBps
) external payable;
function onListingActivated(uint256 listingId, address depositor, uint256 backing) external;
function onListingBackingUpdated(uint256 listingId, address depositor, uint256 oldBacking, uint256 newBacking)
external;
function onListingRemoved(uint256 listingId) external;
}
src/interfaces/IProtocolRewards.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Pre-funded reward accounting for the two sides of the gacha market.
interface IProtocolRewards {
function gachaCore() external view returns (address);
/// @dev Called only after a paid acquisition successfully allocates a listing.
function onSuccessfulPlay(address player, uint256 acquisitionPrice, uint64 sequence) external;
/// @dev Strict accounting checkpoint whenever an active listing enters, exits or changes backing.
function onActiveBackingChanged(address depositor, uint256 listingId, uint256 oldBacking, uint256 newBacking)
external;
}
src/interfaces/IRandomnessProvider.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Chain-specific randomness-adapter boundary; implementations are not necessarily VRFs.
/// @dev Implementations must return one globally unique request ID per requested word.
interface IRandomnessProvider {
/// @notice Total native fee required for `wordCount` words.
function quoteRequestFee(uint32 wordCount) external view returns (uint256);
/// @notice Request words for a contiguous GachaCore sequence range.
/// @dev A provider may satisfy the batch from one master entropy request, provided every
/// returned word is expanded with unambiguous domain separation.
/// @param firstSequence First GachaCore sequence in the batch.
/// @param wordCount Number of words requested.
/// @return providerRequestIds One globally unique ID for each sequence, in order.
function requestRandomness(uint64 firstSequence, uint32 wordCount)
external
payable
returns (bytes32[] memory providerRequestIds);
}
src/interfaces/ITokenAdmissionPolicy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Optional token-level admission hook for aggregate/wrapper collections.
interface ITokenAdmissionPolicy {
function isTokenAllowed(address collection, uint256 tokenId) external view returns (bool);
}
src/libraries/SparseWeightTree.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
/// @notice Fixed-depth sparse segment tree for weighted selection.
/// @dev Supports up to 2^32 permanent listing IDs without pre-allocating storage.
library SparseWeightTree {
uint256 internal constant DEPTH = 32;
uint256 internal constant CAPACITY = 2 ** DEPTH;
uint256 internal constant LEAF_BASE = CAPACITY;
error IndexOutOfBounds();
error EmptyTree();
error TargetOutOfBounds();
struct Tree {
mapping(uint256 node => uint256 weight) nodes;
}
function add(Tree storage self, uint256 index, uint256 amount) internal {
if (index == 0 || index > CAPACITY) revert IndexOutOfBounds();
uint256 node = LEAF_BASE + index - 1;
while (true) {
self.nodes[node] += amount;
if (node == 1) break;
node >>= 1;
}
}
function remove(Tree storage self, uint256 index, uint256 amount) internal {
if (index == 0 || index > CAPACITY) revert IndexOutOfBounds();
uint256 node = LEAF_BASE + index - 1;
while (true) {
self.nodes[node] -= amount;
if (node == 1) break;
node >>= 1;
}
}
function select(Tree storage self, uint256 target) internal view returns (uint256 index) {
uint256 rootWeight = self.nodes[1];
if (rootWeight == 0) revert EmptyTree();
if (target >= rootWeight) revert TargetOutOfBounds();
uint256 node = 1;
while (node < LEAF_BASE) {
uint256 left = node << 1;
uint256 leftWeight = self.nodes[left];
if (target < leftWeight) {
node = left;
} else {
target -= leftWeight;
node = left | 1;
}
}
index = node - LEAF_BASE + 1;
}
function root(Tree storage self) internal view returns (uint256) {
return self.nodes[1];
}
function weightAt(Tree storage self, uint256 index) internal view returns (uint256) {
if (index == 0 || index > CAPACITY) revert IndexOutOfBounds();
return self.nodes[LEAF_BASE + index - 1];
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/",
"@uniswap/v4-core/=lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
"ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"hardhat/=lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
"permit2/=lib/v4-periphery/lib/permit2/",
"solmate/=lib/v4-core/lib/solmate/",
"v4-core/=lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.